Created
September 15, 2016 16:47
-
-
Save tidwall/c9032dcdd14549c72c30188dd9cd3cc5 to your computer and use it in GitHub Desktop.
Redcon example using bytes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"log" | |
"strings" | |
"sync" | |
"github.com/tidwall/redcon" | |
) | |
var addr = ":6380" | |
func main() { | |
var mu sync.RWMutex | |
var items = make(map[string][]byte) | |
go log.Printf("started server at %s", addr) | |
err := redcon.ListenAndServeBytes(addr, | |
func(conn redcon.Conn, commands [][][]byte) { | |
for _, args := range commands { | |
switch strings.ToLower(string(args[0])) { | |
default: | |
conn.WriteError("ERR unknown command '" + string(args[0]) + "'") | |
case "hijack": | |
hconn := conn.Hijack() | |
log.Printf("connection is hijacked") | |
go func() { | |
defer hconn.Close() | |
hconn.WriteString("OK") | |
hconn.Flush() | |
}() | |
return | |
case "ping": | |
conn.WriteString("PONG") | |
case "quit": | |
conn.WriteString("OK") | |
conn.Close() | |
case "set": | |
if len(args) != 3 { | |
conn.WriteError("ERR wrong number of arguments for '" + string(args[0]) + "' command") | |
continue | |
} | |
mu.Lock() | |
items[string(args[1])] = args[2] | |
mu.Unlock() | |
conn.WriteString("OK") | |
case "get": | |
if len(args) != 2 { | |
conn.WriteError("ERR wrong number of arguments for '" + string(args[0]) + "' command") | |
continue | |
} | |
mu.RLock() | |
val, ok := items[string(args[1])] | |
mu.RUnlock() | |
if !ok { | |
conn.WriteNull() | |
} else { | |
conn.WriteBulkBytes(val) | |
} | |
case "del": | |
if len(args) != 2 { | |
conn.WriteError("ERR wrong number of arguments for '" + string(args[0]) + "' command") | |
continue | |
} | |
mu.Lock() | |
_, ok := items[string(args[1])] | |
delete(items, string(args[1])) | |
mu.Unlock() | |
if !ok { | |
conn.WriteInt(0) | |
} else { | |
conn.WriteInt(1) | |
} | |
} | |
} | |
}, | |
func(conn redcon.Conn) bool { | |
// use this function to accept or deny the connection. | |
// log.Printf("accept: %s", conn.RemoteAddr()) | |
return true | |
}, | |
func(conn redcon.Conn, err error) { | |
// this is called when the connection has been closed | |
// log.Printf("closed: %s, err: %v", conn.RemoteAddr(), err) | |
}, | |
) | |
if err != nil { | |
log.Fatal(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment