ledisdb/ledis/app.go

67 lines
794 B
Go
Raw Normal View History

2014-05-09 10:49:22 +04:00
package ledis
2014-05-02 13:08:20 +04:00
import (
"net"
"strings"
)
type App struct {
cfg *Config
listener net.Listener
db *DB
2014-05-08 06:54:33 +04:00
closed bool
2014-05-02 13:08:20 +04:00
}
func NewApp(cfg *Config) (*App, error) {
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
}
app.db, err = OpenDBWithConfig(&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()
app.db.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
}
newClient(conn, app.db)
2014-05-02 13:08:20 +04:00
}
}