Documentation ¶
Overview ¶
Package resp provides a reader, writer, and server implementation for the RESP protocol. http://redis.io/topics/protocol
RESP is short for "REdis Serialization Protocol". While the protocol was designed specifically for Redis, it can be used for other client-server software projects.
RESP has the advantages of being human readable and with performance of a binary protocol.
Index ¶
- type AOF
- type Conn
- type Reader
- type Server
- type SyncPolicy
- type Type
- type Value
- func AnyValue(v interface{}) Value
- func ArrayValue(vals []Value) Value
- func BoolValue(t bool) Value
- func BytesValue(b []byte) Value
- func ErrorValue(err error) Value
- func FloatValue(f float64) Value
- func IntegerValue(i int) Value
- func MultiBulkValue(commandName string, args ...interface{}) Value
- func NullValue() Value
- func SimpleStringValue(s string) Value
- func StringValue(s string) Value
- func (v Value) Array() []Value
- func (v Value) Bool() bool
- func (v Value) Bytes() []byte
- func (v Value) Equals(value Value) bool
- func (v Value) Error() error
- func (v Value) Float() float64
- func (v Value) Integer() int
- func (v Value) IsNull() bool
- func (v Value) MarshalRESP() ([]byte, error)
- func (v Value) String() string
- func (v Value) Type() Type
- type Writer
- func (wr *Writer) WriteArray(vals []Value) error
- func (wr *Writer) WriteBytes(b []byte) error
- func (wr *Writer) WriteError(err error) error
- func (wr *Writer) WriteInteger(i int) error
- func (wr *Writer) WriteMultiBulk(commandName string, args ...interface{}) error
- func (wr *Writer) WriteNull() error
- func (wr *Writer) WriteSimpleString(s string) error
- func (wr *Writer) WriteString(s string) error
- func (wr *Writer) WriteValue(v Value) error
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type AOF ¶
type AOF struct {
// contains filtered or unexported fields
}
AOF represents an open file descriptor.
Example ¶
os.RemoveAll("appendonly.aof") // create and fill an appendonly file aof, err := OpenAOF("appendonly.aof") if err != nil { log.Fatal(err) } // append a couple values and close the file aof.Append(MultiBulkValue("set", "leader", "Charlie")) aof.Append(MultiBulkValue("set", "follower", "Skyler")) aof.Close() // reopen and scan all values aof, err = OpenAOF("appendonly.aof") if err != nil { log.Fatal(err) } defer aof.Close() aof.Scan(func(v Value) { fmt.Printf("%s\n", v.String()) })
Output: [set leader Charlie] [set follower Skyler]
func OpenAOF ¶
OpenAOF will open and return an AOF file. If the file does not exist a new one will be created.
func (*AOF) AppendMulti ¶
AppendMulti writes multiple values to the end of the file. This operation can increase performance over calling multiple Append()s and also has the benefit of transactional writes.
func (*AOF) Scan ¶
Scan iterates though all values in the file. This operation could take a long time if there lots of values, and the operation cannot be canceled part way through.
func (*AOF) SetSyncPolicy ¶
func (aof *AOF) SetSyncPolicy(policy SyncPolicy)
SetSyncPolicy set the sync policy of the file. The policy 'EverySecond' means that fsync will be called every second or so. This is fast enough, and at most you can lose one second of data if there is a disaster. The policy 'Never' means fsync is never called, the Operating System will be in charge of your data. This is the fastest and less safe method. The policy 'Always' means fsync is called after every write. This is super duper safe and very incredibly slow. EverySecond is the default.
type Reader ¶
type Reader struct {
// contains filtered or unexported fields
}
Reader is a specialized RESP Value type reader.
Example ¶
raw := "*3\r\n$3\r\nset\r\n$6\r\nleader\r\n$7\r\nCharlie\r\n" raw += "*3\r\n$3\r\nset\r\n$8\r\nfollower\r\n$6\r\nSkyler\r\n" rd := NewReader(bytes.NewBufferString(raw)) for { v, _, err := rd.ReadValue() if err == io.EOF { break } if err != nil { log.Fatal(err) } fmt.Printf("Read %s\n", v.Type()) if v.Type() == Array { for i, v := range v.Array() { fmt.Printf(" #%d %s, value: '%s'\n", i, v.Type(), v) } } }
Output: Read Array #0 BulkString, value: 'set' #1 BulkString, value: 'leader' #2 BulkString, value: 'Charlie' Read Array #0 BulkString, value: 'set' #1 BulkString, value: 'follower' #2 BulkString, value: 'Skyler'
func (*Reader) ReadMultiBulk ¶
ReadMultiBulk reads the next multi bulk Value from Reader. A multi bulk value is a RESP array that contains one or more bulk strings. For more information on RESP arrays and strings please see http://redis.io/topics/protocol.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server represents a RESP server which handles reading RESP Values.
Example ¶
// ExampleServer is a Redis clone that implements the SET and GET commands. // The server runs on port 6380. // You can interact using the Redis CLI (redis-cli) The http://redis.io/download. // Or, use the telnet by typing in "telnet localhost 6380" and type in "set key value" and "get key". // Or, use a client library such as "http://github.com/garyburd/redigo" // The "QUIT" command will close the connection. var mu sync.RWMutex kvs := make(map[string]string) s := NewServer() s.HandleFunc("set", func(conn *Conn, args []Value) bool { if len(args) != 3 { conn.WriteError(errors.New("ERR wrong number of arguments for 'set' command")) } else { mu.Lock() kvs[args[1].String()] = args[2].String() mu.Unlock() conn.WriteSimpleString("OK") } return true }) s.HandleFunc("get", func(conn *Conn, args []Value) bool { if len(args) != 2 { conn.WriteError(errors.New("ERR wrong number of arguments for 'get' command")) } else { mu.RLock() s, ok := kvs[args[1].String()] mu.RUnlock() if !ok { conn.WriteNull() } else { conn.WriteString(s) } } return true }) if err := s.ListenAndServe(":6380"); err != nil { log.Fatal(err) }
Output:
func (*Server) AcceptFunc ¶
AcceptFunc registers a function for accepting connections. Calling this function is optional and it allows for total control over reading and writing RESP Values from and to the connections. Returning false will close the connection.
func (*Server) HandleFunc ¶
HandleFunc registers the handler function for the given command. The conn parameter is a Conn type and it can be used to read and write further RESP messages from and to the connection. Returning false will close the connection.
func (*Server) ListenAndServe ¶
ListenAndServe listens on the TCP network address addr for incoming connections.
type SyncPolicy ¶
type SyncPolicy int
SyncPolicy represents a file's fsync policy.
const ( Never SyncPolicy = iota // The policy 'Never' means fsync is never called, the Operating System will be in charge of your data. This is the fastest and less safe method. EverySecond SyncPolicy = iota // The policy 'EverySecond' means that fsync will be called every second or so. This is fast enough, and at most you can lose one second of data if there is a disaster. Always SyncPolicy = iota // The policy 'Always' means fsync is called after every write. This is super duper safe and very incredibly slow. )
func (SyncPolicy) String ¶
func (policy SyncPolicy) String() string
String returns a string respesentation.
type Value ¶
type Value struct {
// contains filtered or unexported fields
}
Value represents the data of a valid RESP type.
func AnyValue ¶
func AnyValue(v interface{}) Value
AnyValue returns a RESP value from an interface. This function infers the types. Arrays are not allowed.
func BytesValue ¶
BytesValue returns a RESP bulk string. A bulk string can represent any data.
func FloatValue ¶
FloatValue returns a RESP bulk string representation of a float.
func MultiBulkValue ¶
MultiBulkValue returns a RESP array which contains one or more bulk strings. For more information on RESP arrays and strings please see http://redis.io/topics/protocol.
func SimpleStringValue ¶
SimpleStringValue returns a RESP simple string. A simple string has no new lines. The carriage return and new line characters are replaced with spaces.
func StringValue ¶
StringValue returns a RESP bulk string. A bulk string can represent any data.
func (Value) Array ¶
Array converts the Value to a an array. If Value is not an array or when it's is a RESP Null value, nil is returned.
func (Value) Bool ¶
Bool converts Value to an bool. If Value cannot be converted, false is returned.
func (Value) Bytes ¶
Bytes converts the Value to a byte array. An empty string is converted to a non-nil empty byte array. If it's a RESP Null value, nil is returned.
func (Value) Error ¶
Error converts the Value to an error. If Value is not an error, nil is returned.
func (Value) Float ¶
Float converts Value to a float64. If Value cannot be converted, Zero is returned.
func (Value) Integer ¶
Integer converts Value to an int. If Value cannot be converted, Zero is returned.
func (Value) MarshalRESP ¶
MarshalRESP returns the original serialized byte representation of Value. For more information on this format please see http://redis.io/topics/protocol.
type Writer ¶
type Writer struct {
// contains filtered or unexported fields
}
Writer is a specialized RESP Value type writer.
Example ¶
var buf bytes.Buffer wr := NewWriter(&buf) wr.WriteArray([]Value{StringValue("set"), StringValue("leader"), StringValue("Charlie")}) wr.WriteArray([]Value{StringValue("set"), StringValue("follower"), StringValue("Skyler")}) fmt.Printf("%s", strings.Replace(buf.String(), "\r\n", "\\r\\n", -1))
Output: *3\r\n$3\r\nset\r\n$6\r\nleader\r\n$7\r\nCharlie\r\n*3\r\n$3\r\nset\r\n$8\r\nfollower\r\n$6\r\nSkyler\r\n
func (*Writer) WriteArray ¶
WriteArray writes a RESP array.
func (*Writer) WriteBytes ¶
WriteBytes writes a RESP bulk string. A bulk string can represent any data.
func (*Writer) WriteError ¶
WriteError writes a RESP error.
func (*Writer) WriteInteger ¶
WriteInteger writes a RESP integer.
func (*Writer) WriteMultiBulk ¶
WriteMultiBulk writes a RESP array which contains one or more bulk strings. For more information on RESP arrays and strings please see http://redis.io/topics/protocol.
func (*Writer) WriteSimpleString ¶
WriteSimpleString writes a RESP simple string. A simple string has no new lines. The carriage return and new line characters are replaced with spaces.
func (*Writer) WriteString ¶
WriteString writes a RESP bulk string. A bulk string can represent any data.
func (*Writer) WriteValue ¶
WriteValue writes a RESP Value.