gedis

package module
v0.0.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 6, 2013 License: MIT Imports: 4 Imported by: 2

README

gedis - a low-level interface in Go for Redis

gedis implements a very low-level interface to read and write using the Redis protocol.

It also provides a simple client to talk to a Redis server and a generic Redis server, which allows you to implement your own server that understands the Redis protocol.

Build Status master branch status at Travis CI

API documentation

gedis API documentation is available at the fabulous GoDoc website, in the following locations:

Examples

You can find all the examples at https://github.com/inkel/gedis-examples

Parser

In this example we'll create net.Conn to a Redis server and we'll send commands by using the parser function gedis.Write, and then read the server's response by using gedis.Read:

package main

import (
	"flag"
	"fmt"
	"github.com/inkel/gedis"
	"net"
)

var server = flag.String("s", "localhost:6379", "Address of the Redis server")

func main() {
	c, err := net.Dial("tcp", *server)
	if err != nil {
		panic(err)
	}
	defer c.Close()

	f := func(args ...interface{}) {
		cmd := args[0]

		fmt.Printf("> %s", cmd)
		for _, arg := range args[1:] {
			fmt.Printf(" %q", arg)
		}
		fmt.Println()

		// Send to command to Redis server
		_, err := gedis.Write(c, args...)
		if err != nil {
			panic(err)
		}

		// Read the reply from the server
		res, err := gedis.Read(c)
		if err != nil {
			panic(err)
		}
		fmt.Printf("< %#v\n\n", res)
	}

	f("PING")

	f("SET", "lorem", "ipsum")

	f("INCR", "counter")

	f("HMSET", "hash", "field1", "lorem", "field2", "ipsum")

	f("HGETALL", "hash")
}
Output
$ go run ./gedis.go
> PING
< "PONG"

> SET "lorem" "ipsum"
< "OK"

> INCR "counter"
< 6

> HMSET "hash" "field1" "lorem" "field2" "ipsum"
< "OK"

> HGETALL "hash"
< []interface {}{"field1", "lorem", "field2", "ipsum"}
Client

You can also use the gedis client package to create a Client object that exposes almost the same API as using a net.Conn. In the future this client might add more features.

package main

import (
	"flag"
	"fmt"
	"github.com/inkel/gedis/client"
)

var server = flag.String("s", "localhost:6379", "Address of the Redis server")

func main() {
	c, err := client.Dial("tcp", *server)
	if err != nil {
		panic(err)
		return
	}
	defer c.Close()

	f := func(args ...interface{}) {
		fmt.Printf("> %v\n", args)

		// Send to command to Redis server
		res, err := c.Send(args...)
		if err != nil {
			panic(err)
		} else {
			fmt.Printf("< %#v\n\n", res)
		}
	}

	f("PING")

	f("SET", "lorem", "ipsum")

	f("INCR", "counter")

	f("HMSET", "hash", "field1", "lorem", "field2", "ipsum")

	f("HGETALL", "hash")

	f("MULTI")
	f("GET", "counter")
	f("GET", "nonexisting")
	f("EXEC")
}
Output
$ go run ./client.go
> [PING]
< "PONG"

> [SET lorem ipsum]
< "OK"

> [INCR counter]
< 7

> [HMSET hash field1 lorem field2 ipsum]
< "OK"

> [HGETALL hash]
< []interface {}{"field1", "lorem", "field2", "ipsum"}

> [MULTI]
< "OK"

> [GET counter]
< "QUEUED"

> [GET nonexisting]
< "QUEUED"

> [EXEC]
< []interface {}{"7", interface {}(nil)}
Server

If you want to build a custom server that understands the Redis protocol, you can use the Server type defined in the gedis server namespace.

The following example implements a server that only responds to the PING command:

package main

import (
	"flag"
	"fmt"
	"github.com/inkel/gedis/server"
	"os"
	"os/signal"
)

var listen = flag.String("l", ":26379", "Address to listen for connections")

func main() {
	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt, os.Kill)

	s, err := server.NewServer("tcp", *listen)
	if err != nil {
		panic(err)
	}
	defer s.Close()

	pong := []byte("+PONG\r\n")
	earg := []byte("-ERR wrong number of arguments for 'ping' command\r\n")

	s.Handle("PING", func(c *server.Client, args [][]byte) error {
		if len(args) != 0 {
			c.Write(earg)
			return nil
		} else {
			c.Write(pong)
		}

		return nil
	})

	go s.Loop()

	// Wait for interrupt/kill
	<-c

	fmt.Println("Bye!")
}
Usage
$ go run ./server.go &
$ redis-cli -p 26379
redis 127.0.0.1:26379> ping
PONG
redis 127.0.0.1:26379> get inkel
(error) ERR Unrecognized command 'get'
redis 127.0.0.1:26379>

This generic server performs quite well, though not as fast as the standard C Redis server (which is kind of obvious):

$ redis-benchmark -q -t PING_MBULK -p 26379
PING_BULK: 36630.04 requests per second

Build & test

In your $GOPATH do the following:

go get github.com/inkel/gedis
go get github.com/inkel/gedis/client
go get github.com/inkel/gedis/server

Then you can build it by executing:

go build github.com/inkel/gedis
go build github.com/inkel/gedis/client
go build github.com/inkel/gedis/server

Testing and benchmark:

go test github.com/inkel/gedis
go test github.com/inkel/gedis -bench=".*"

go test github.com/inkel/gedis/client
go test github.com/inkel/gedis/client -bench=".*"

go test github.com/inkel/gedis/server
go test github.com/inkel/gedis/server -bench=".*"

References

Why

I wanted to learn Go, so I decided to write a minimal Redis client.

Perhaps one day I might decide to do something else with it, but in the mean, the goals are merely academic.

Feel free to comment on the code and send patches if you like.

License

Copyright (c) 2013 Leandro López

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

Documentation

Overview

Copyright 2013 Leandro López (inkel)

This package implements a very low-level interface to read and write using the Redis protocol. It also provides a simple client to talk to a Redis server.

THIS IS FAR FROM BEING PRODUCTION READY.

API

Gedis currently provides two API functions for writing and reading the [Redis protocol](http://redis.io/topics/protocol). It also defines two simple interfaces: `Reader` and `Writer`

Writing commands

Gedis defines the following `Writer` interface:

type Writer interface {
        Write(p []byte) (n int, err error)
}

It is possible to send Redis commands to any object that implements that interface, i.e. [`net.Conn`](http://golang.org/pkg/net/#Conn), by using the following function:

Write(w Writer, args ...string) (n int, err error)

Reading

Gedis defines the following `Reader` interface:

type Reader interface {
        Read(b []byte) (n int, err error)
}

It is possible to read Redis replies from any object that implements that interface, i.e. net.Conn, by using the following function:

Read(r Reader) (reply interface{}, err error)

API usage example

package main

import (
	"fmt"
	"github.com/inkel/gedis"
	"net"
)

func main() {
	c, err := net.Dial("tcp", "localhost:6379")
	if err != nil {
		panic(err)
	}
	defer c.Close()

	f := func(args ...string) {
		fmt.Printf("> %s", args[0])
		for _, arg := range args[1:] {
			fmt.Printf(" %q", arg)
		}
		fmt.Println()

		// Send to command to Redis server
		_, err := gedis.Write(c, args...)
		if err != nil {
			panic(err)
		}

		// Read the reply from the server
		res, err := gedis.Read(c)
		if err != nil {
			panic(err)
		}
		fmt.Printf("< %#v\n\n", res)
	}

	f("PING")

	f("SET", "lorem", "ipsum")

	f("INCR", "counter")

	f("HMSET", "hash", "field1", "lorem", "field2", "ipsum")

	f("HGETALL", "hash")

	f("MULTI")
	f("GET", "counter")
	f("GET", "nonexisting")
	f("EXEC")
}

Client

To avoid you the hassle of having to pass the connction parameter in every call, `gedis` defines the following `Client` object:

type Client struct {}
func Dial(network, address string) (c Client, err error)
func (c *Client) Close() error
func (c *Client) Send(cmd string, args ...string) (interface{}, error)

Client usage example

package main

import (
	"fmt"
	"github.com/inkel/gedis"
)

func main() {
	c, err := gedis.Dial("tcp", "localhost:6379")
	if err != nil {
		panic(err)
	}
	defer c.Close()

	f := func(args ...string) {
		fmt.Printf("> %s", args[0])
		for _, arg := range args[1:] {
			fmt.Printf(" %q", arg)
		}
		fmt.Println()

		// Send to command to Redis server
		res, err := c.Send(args...)
		if err != nil {
			panic(err)
		}

		fmt.Printf("< %#v\n\n", res)
	}

	f("PING")

	f("SET", "lorem", "ipsum")

	f("INCR", "counter")

	f("HMSET", "hash", "field1", "lorem", "field2", "ipsum")

	f("HGETALL", "hash")

	f("MULTI")
	f("GET", "counter")
	f("GET", "nonexisting")
	f("EXEC")
}

Why

I wanted to learn Go, so I decided to write a minimal Redis client. Perhaps one day I might decide to do something else with it, but in the mean, the goals are merely academic. Feel free to comment on the code and send patches if you like.

Redis protocol

Redis uses a very simple text protocol, which is binary safe.

*<num args> CR LF
$<num bytes arg1> CR LF
<arg data> CR LF
...
$<num bytes argn> CR LF
<arg data>

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Read

func Read(r Reader) (ret interface{}, err error)

func ReadNumber added in v0.0.5

func ReadNumber(r Reader) (n int64, err error)

Reads an int64 from the Reader

func Write

func Write(w Writer, args ...interface{}) (n int, err error)

func WriteBulk

func WriteBulk(bulk string) []byte

Writes a string as a sequence of bytes to be send to a Redis instance, using the Redis Bulk format.

func WriteError

func WriteError(err error) []byte

Writes an error in the Redis protocol format

func WriteInt

func WriteInt(n int64) []byte

Writes a number in the Redis protocol format

func WriteMultiBulk

func WriteMultiBulk(args ...interface{}) []byte

Writes a sequence of strings as a sequence of bytes to be send to a Redis instance, using the Redis Multi-Bulk format.

func WriteStatus added in v0.0.5

func WriteStatus(status string) []byte

Writes a status in the Redis protocol format

Types

type ParseError added in v0.0.5

type ParseError struct {
	// contains filtered or unexported fields
}

Struct to hold parsing errors

func NewParseError added in v0.0.5

func NewParseError(err string) *ParseError

func (*ParseError) Error added in v0.0.5

func (pe *ParseError) Error() string

type Reader

type Reader interface {
	Read(b []byte) (n int, err error)
}

Interface for reading Redis commands

type Writer

type Writer interface {
	Write(p []byte) (n int, err error)
}

Interface for writing Redis commands

Notes

Bugs

  • writeMultiBulk can't write multi-bulks inside multi-bulks

Directories

Path Synopsis
gedis client - Redis client written in Go This package allows to create clients that can talk to servers by using the Redis protocol Redis protocol: http://redis.io/topics/protocol Example package main import ( "fmt" "github.com/inkel/gedis/client" ) func main() { c, err := client.Dial("tcp", "localhost:6379") if err != nil { panic(err) } defer c.Close() f := func(args ...string) { fmt.Printf("> %s", args[0]) for _, arg := range args[1:] { fmt.Printf(" %q", arg) } fmt.Println() // Send to command to Redis server res, err := c.Send(args...) if err != nil { panic(err) } fmt.Printf("< %#v\n\n", res) } f("PING") f("SET", "lorem", "ipsum") f("INCR", "counter") f("HMSET", "hash", "field1", "lorem", "field2", "ipsum") f("HGETALL", "hash") }
gedis client - Redis client written in Go This package allows to create clients that can talk to servers by using the Redis protocol Redis protocol: http://redis.io/topics/protocol Example package main import ( "fmt" "github.com/inkel/gedis/client" ) func main() { c, err := client.Dial("tcp", "localhost:6379") if err != nil { panic(err) } defer c.Close() f := func(args ...string) { fmt.Printf("> %s", args[0]) for _, arg := range args[1:] { fmt.Printf(" %q", arg) } fmt.Println() // Send to command to Redis server res, err := c.Send(args...) if err != nil { panic(err) } fmt.Printf("< %#v\n\n", res) } f("PING") f("SET", "lorem", "ipsum") f("INCR", "counter") f("HMSET", "hash", "field1", "lorem", "field2", "ipsum") f("HGETALL", "hash") }
gedis server - Generic Redis server implementation This package allows to create servers that can talk to clients by using the Redis protocol Redis protocol: http://redis.io/topics/protocol As an example, the following implements a very simple Redis server that only responds to the PING command: package main import ( "fmt" gedis "github.com/inkel/gedis/server" "os" "os/signal" ) func main() { c := make(chan os.Signal, 1) signal.Notify(c, os.Interrupt, os.Kill) s, err := gedis.NewServer("tcp", ":10003") if err != nil { panic(err) } defer s.Close() pong := []byte("+PONG\r\n") earg := []byte("-ERR wrong number of arguments for 'ping' command\r\n") s.Handle("PING", func(c *gedis.Client, args [][]byte) error { if len(args) != 0 { c.Write(earg) return nil } else { c.Write(pong) } return nil }) go s.Loop() <-c fmt.Println("Bye!") }
gedis server - Generic Redis server implementation This package allows to create servers that can talk to clients by using the Redis protocol Redis protocol: http://redis.io/topics/protocol As an example, the following implements a very simple Redis server that only responds to the PING command: package main import ( "fmt" gedis "github.com/inkel/gedis/server" "os" "os/signal" ) func main() { c := make(chan os.Signal, 1) signal.Notify(c, os.Interrupt, os.Kill) s, err := gedis.NewServer("tcp", ":10003") if err != nil { panic(err) } defer s.Close() pong := []byte("+PONG\r\n") earg := []byte("-ERR wrong number of arguments for 'ping' command\r\n") s.Handle("PING", func(c *gedis.Client, args [][]byte) error { if len(args) != 0 { c.Write(earg) return nil } else { c.Write(pong) } return nil }) go s.Loop() <-c fmt.Println("Bye!") }

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL