Created
August 24, 2016 07:17
-
-
Save FZambia/9b2e668fbc1f475e79cdd1177f06c8e6 to your computer and use it in GitHub Desktop.
Centrifugo Redis proto support
This file contains hidden or 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 libcentrifugo | |
| import ( | |
| "encoding/json" | |
| "strings" | |
| "github.com/FZambia/go-logger" | |
| "github.com/tidwall/redcon" | |
| ) | |
| var addr = ":6380" | |
| type connMeta struct { | |
| inPipe bool | |
| pipeCounter int | |
| } | |
| func (app *Application) startRedisServer() error { | |
| logger.INFO.Printf("Started Redis protocol compatible API server at %s", ":6380") | |
| conns := map[redcon.Conn]*connMeta{} | |
| err := redcon.ListenAndServe(":6380", | |
| func(conn redcon.Conn, commands [][]string) { | |
| c := conns[conn] | |
| for _, args := range commands { | |
| switch strings.ToLower(args[0]) { | |
| default: | |
| conn.WriteError("ERR unknown command '" + args[0] + "'") | |
| case "ping": | |
| conn.WriteString("PONG") | |
| case "quit": | |
| conn.WriteString("OK") | |
| conn.Close() | |
| case "multi": | |
| conn.WriteString("OK") | |
| c.inPipe = true | |
| case "exec": | |
| conn.WriteArray(c.pipeCounter) | |
| for i := 0; i < c.pipeCounter; i++ { | |
| conn.WriteString("OK") | |
| } | |
| c.inPipe = false | |
| c.pipeCounter = 0 | |
| case "set": | |
| if len(args) != 3 { | |
| conn.WriteError("ERR wrong number of arguments for '" + args[0] + "' command") | |
| continue | |
| } | |
| if !c.inPipe { | |
| conn.WriteString("OK") | |
| } else { | |
| conn.WriteString("QUEUED") | |
| c.pipeCounter += 1 | |
| } | |
| cmd := apiCommand{ | |
| Method: args[1], | |
| Params: json.RawMessage([]byte(args[2])), | |
| } | |
| _, err := app.apiCmd(cmd) | |
| if err != nil { | |
| logger.ERROR.Println(err) | |
| } | |
| case "get": | |
| if len(args) != 2 { | |
| conn.WriteError("ERR wrong number of arguments for '" + args[0] + "' command") | |
| continue | |
| } | |
| conn.WriteNull() | |
| } | |
| } | |
| }, | |
| func(conn redcon.Conn) bool { | |
| conns[conn] = &connMeta{} | |
| logger.INFO.Printf("Accept connection to Redis compatible API server: %s", conn.RemoteAddr()) | |
| return true | |
| }, | |
| func(conn redcon.Conn, err error) { | |
| delete(conns, conn) | |
| logger.INFO.Printf("Connection to Redis compatible API server closed: %s, err: %v", conn.RemoteAddr(), err) | |
| }, | |
| ) | |
| if err != nil { | |
| logger.FATAL.Fatal(err) | |
| } | |
| return nil | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment