add base http framework

This commit is contained in:
siddontang 2014-07-17 15:19:46 +08:00
parent 82711d6fa8
commit f85da1db91
5 changed files with 63 additions and 7 deletions

View File

@ -3,4 +3,5 @@
. ./dev.sh
go get -u github.com/siddontang/go-log/log
go get -u github.com/siddontang/go-websocket/websocket
go get -u github.com/siddontang/go-snappy/snappy

View File

@ -1,5 +1,6 @@
{
"addr": "127.0.0.1:6380",
"http_addr": "127.0.0.1:11181",
"data_dir": "/tmp/ledis_server",
"db": {
"data_db" : {

View File

@ -4,6 +4,7 @@ import (
"fmt"
"github.com/siddontang/ledisdb/ledis"
"net"
"net/http"
"path"
"strings"
)
@ -11,7 +12,8 @@ import (
type App struct {
cfg *Config
listener net.Listener
listener net.Listener
httpListener net.Listener
ldb *ledis.Ledis
@ -25,6 +27,14 @@ type App struct {
m *master
}
func netType(s string) string {
if strings.Contains(s, "/") {
return "unix"
} else {
return "tcp"
}
}
func NewApp(cfg *Config) (*App, error) {
if len(cfg.DataDir) == 0 {
return nil, fmt.Errorf("must set data_dir first")
@ -44,14 +54,14 @@ func NewApp(cfg *Config) (*App, error) {
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 app.listener, err = net.Listen(netType(cfg.Addr), cfg.Addr); err != nil {
return nil, err
}
if err != nil {
return nil, err
if len(cfg.HttpAddr) > 0 {
if app.httpListener, err = net.Listen(netType(cfg.HttpAddr), cfg.HttpAddr); err != nil {
return nil, err
}
}
if len(cfg.AccessLog) > 0 {
@ -86,6 +96,10 @@ func (app *App) Close() {
app.listener.Close()
if app.httpListener != nil {
app.httpListener.Close()
}
app.m.Close()
if app.access != nil {
@ -100,6 +114,8 @@ func (app *App) Run() {
app.slaveof(app.cfg.SlaveOf)
}
go app.httpServe()
for !app.closed {
conn, err := app.listener.Accept()
if err != nil {
@ -110,6 +126,20 @@ func (app *App) Run() {
}
}
func (app *App) httpServe() {
if app.httpListener == nil {
return
}
mux := http.NewServeMux()
mux.Handle("/ws", &wsHandler{app})
mux.Handle("/", &cmdHandler{app})
svr := http.Server{Handler: mux}
svr.Serve(app.httpListener)
}
func (app *App) Ledis() *ledis.Ledis {
return app.ldb
}

View File

@ -9,6 +9,8 @@ import (
type Config struct {
Addr string `json:"addr"`
HttpAddr string `json:"http_addr"`
DataDir string `json:"data_dir"`
//if you not set db path, use data_dir

22
server/httpd.go Normal file
View File

@ -0,0 +1,22 @@
package server
import (
"net/http"
//"github.com/siddontang/go-websocket/websocket"
)
type cmdHandler struct {
app *App
}
func (h *cmdHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("cmd handler"))
}
type wsHandler struct {
app *App
}
func (h *wsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("ws handler"))
}