-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.go
64 lines (52 loc) · 1.16 KB
/
server.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package td
import (
"net/http"
"github.com/swxctx/xlog"
"github.com/swxctx/malatd/httprouter"
)
// Server
type Server struct {
// 路由组
Router
// 服务配置
srvConfig *SrvConfig
// api路由
router *httprouter.Router
}
// NewServer
func NewServer(srvCfg *SrvConfig, plugins ...Plugin) *Server {
// server config is nil
if srvCfg == nil {
srvCfg = NewSrvConfig()
}
// :8080 -> 0.0.0.0:8080
if len(srvCfg.Address) <= 0 {
srvCfg.Address = "0.0.0.0:8080"
}
// 请求日志
plugins = append(plugins, runLogPlugin)
// new server
srv := &Server{
Router: Router{
Plugins: plugins,
root: true,
basePath: "/",
},
router: httprouter.New(),
srvConfig: srvCfg,
}
srv.Router.server = srv
srv.router.NotFound = http.HandlerFunc(renderNotFound)
xlog.Infof("[SERVER] New server, Address: %s", srvCfg.Address)
return srv
}
// ListenAndServe fast http listen
func (srv *Server) Run() error {
xlog.Infof("[SERVER] %s Server Run", srv.srvConfig.Address)
// start listen
if err := http.ListenAndServe(srv.srvConfig.Address, srv.router); err != nil {
xlog.Errorf("[SERVER] Server Listen err: %v", err)
return err
}
return nil
}