tidwall / redcon

Redis compatible server framework for Go
MIT License
2.19k stars 158 forks source link

How do you implement unix socket? #21

Closed hiqbn closed 5 years ago

hiqbn commented 5 years ago

Relating to this, https://github.com/tidwall/redcon/issues/6

how do i use unix socket? any examples?

tidwall commented 5 years ago

Use the NewServerNetwork function.

Here's a complete example that accepts the PING command on a unix socket file named socket.

package main

import (
    "fmt"
    "log"
    "os"
    "strings"

    "github.com/tidwall/redcon"
)

func main() {
    os.RemoveAll("socket")
    s := redcon.NewServerNetwork("unix", "socket",
        func(conn redcon.Conn, cmd redcon.Command) {
            switch strings.ToUpper(string(cmd.Args[0])) {
            default:
                conn.WriteError(
                    fmt.Sprintf("ERR unknown command '%s'", cmd.Args[0]))
            case "PING":
                conn.WriteString("PONG")
            }
        }, nil, nil)
    errc := make(chan error)
    go func() {
        if <-errc == nil {
            log.Printf("Server started")
        }
    }()
    log.Fatal(s.ListenServeAndSignal(errc))
}