2014-05-16 11:03:23 +04:00
|
|
|
package server
|
2014-05-02 13:08:20 +04:00
|
|
|
|
|
|
|
import (
|
2014-06-06 07:25:13 +04:00
|
|
|
"fmt"
|
2014-05-16 11:03:23 +04:00
|
|
|
"github.com/siddontang/ledisdb/ledis"
|
2014-05-02 13:08:20 +04:00
|
|
|
"net"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
|
|
|
type App struct {
|
|
|
|
cfg *Config
|
|
|
|
|
|
|
|
listener net.Listener
|
|
|
|
|
2014-05-20 04:41:24 +04:00
|
|
|
ldb *ledis.Ledis
|
2014-05-08 06:54:33 +04:00
|
|
|
|
|
|
|
closed bool
|
2014-05-02 13:08:20 +04:00
|
|
|
}
|
|
|
|
|
|
|
|
func NewApp(cfg *Config) (*App, error) {
|
2014-06-06 07:25:13 +04:00
|
|
|
if len(cfg.DataDir) == 0 {
|
|
|
|
return nil, fmt.Errorf("must set data_dir first")
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(cfg.DB.DataDir) == 0 {
|
|
|
|
cfg.DB.DataDir = cfg.DataDir
|
|
|
|
}
|
|
|
|
|
2014-05-02 13:08:20 +04:00
|
|
|
app := new(App)
|
|
|
|
|
2014-05-08 06:54:33 +04:00
|
|
|
app.closed = false
|
|
|
|
|
2014-05-02 13:08:20 +04:00
|
|
|
app.cfg = cfg
|
|
|
|
|
|
|
|
var err error
|
|
|
|
|
|
|
|
if strings.Contains(cfg.Addr, "/") {
|
|
|
|
app.listener, err = net.Listen("unix", cfg.Addr)
|
|
|
|
} else {
|
|
|
|
app.listener, err = net.Listen("tcp", cfg.Addr)
|
|
|
|
}
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2014-05-20 04:41:24 +04:00
|
|
|
app.ldb, err = ledis.OpenWithConfig(&cfg.DB)
|
2014-05-02 13:08:20 +04:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return app, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (app *App) Close() {
|
2014-05-08 06:54:33 +04:00
|
|
|
if app.closed {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2014-05-02 13:08:20 +04:00
|
|
|
app.listener.Close()
|
|
|
|
|
2014-05-20 04:41:24 +04:00
|
|
|
app.ldb.Close()
|
2014-05-08 06:54:33 +04:00
|
|
|
|
|
|
|
app.closed = true
|
2014-05-02 13:08:20 +04:00
|
|
|
}
|
|
|
|
|
|
|
|
func (app *App) Run() {
|
2014-05-08 06:54:33 +04:00
|
|
|
for !app.closed {
|
2014-05-02 13:08:20 +04:00
|
|
|
conn, err := app.listener.Accept()
|
|
|
|
if err != nil {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2014-05-20 04:41:24 +04:00
|
|
|
newClient(conn, app.ldb)
|
2014-05-02 13:08:20 +04:00
|
|
|
}
|
|
|
|
}
|