package main import ( "flag" "fmt" "log" "net" "os" "os/signal" leveldb "github.com/jmhodges/levigo" ) func main() { var port int var host string var cacheSize int flag.IntVar(&port, "port", 6379, "port to bind") flag.StringVar(&host, "host", "", "host to bind") flag.IntVar(&cacheSize, "cache", 32, "cache size in MB") flag.Parse() args := flag.Args() if len(args) < 1 { log.Fatal("Missing path to world") } cache := leveldb.NewLRUCache(cacheSize * 1024 * 1024) defer cache.Close() opts := leveldb.NewOptions() opts.SetCache(cache) opts.SetCreateIfMissing(true) var err error var db *leveldb.DB if db, err = leveldb.Open(args[0], opts); err != nil { log.Fatal(err) } defer db.Close() var listener net.Listener listener, err = net.Listen("tcp", fmt.Sprintf("%s:%d", host, port)) if err != nil { log.Fatal(err) } defer listener.Close() log.Printf("Server started at %s", listener.Addr()) connChan := make(chan net.Conn) defer close(connChan) sigChan := make(chan os.Signal, 1) signal.Notify(sigChan, os.Interrupt, os.Kill) go func() { for { conn, err := listener.Accept() if err != nil { log.Fatal(err) } log.Printf("Client accepted from: %s", conn.RemoteAddr()) connChan <- conn } }() for { select { case conn := <-connChan: go NewConnection(conn, db).Run() case <-sigChan: log.Println("Shutting down") return } } }