Created
February 16, 2019 10:14
-
-
Save knadh/e943f40840ad5d0bacafd7123ec986fa to your computer and use it in GitHub Desktop.
Go function for generation Redis raw protocol for importing with redis-cli --pipe
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 ( | |
"fmt" | |
"bytes" | |
"strconv" | |
) | |
// toRedisProto converts a Redis command, represented by a slice of | |
// bytes, where each element of the slice represents a chunk of the | |
// Redis command separated by space, into buf. | |
// eg: SET key val = ["SET", "mykey", "1234"] | |
// The Redis protocol for the above command is as follows: | |
// *3\r\n | |
// $3\r\n | |
// SET\r\n | |
// $5\r\n | |
// mykey\r\n | |
// $4\r\n | |
// 1234\r\n | |
// | |
// The first number followed by the * is len(cmd) | |
// The rest are parts of cmd each preceded by $ len(part). | |
func toRedisProto(buf *bytes.Buffer, cmd ...[]byte) { | |
var ( | |
bCLRF = []byte("\r\n") | |
bStar = []byte("*") | |
bDollar = []byte("$") | |
) | |
buf.Write(bStar) | |
buf.Write([]byte(strconv.Itoa(len(cmd)))) | |
buf.Write(bCLRF) | |
for _, c := range cmd { | |
buf.Write(bDollar) | |
buf.Write([]byte(strconv.Itoa(len(c)))) | |
buf.Write(bCLRF) | |
buf.Write(c) | |
buf.Write(bCLRF) | |
} | |
} | |
func main() { | |
buf := &bytes.Buffer{} | |
toRedisProto(buf, | |
[]byte("HMSET"), []byte("my_map"), | |
[]byte("my_key"), []byte("val 1"), | |
[]byte("my_key"), []byte("val 2")) | |
fmt.Println(buf.String()) | |
// Prints: This can be fed into redis-cli --pipe | |
// *6 | |
// $5 | |
// HMSET | |
// $6 | |
// my_map | |
// $6 | |
// my_key | |
// $5 | |
// val 1 | |
// $6 | |
// my_key | |
// $5 | |
// val 2 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment