-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
91 lines (76 loc) · 1.7 KB
/
server.go
File metadata and controls
91 lines (76 loc) · 1.7 KB
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package web
import (
"log"
"net/http"
)
type Server interface {
http.Handler
Start(addr string)
addRoute(method string, path string, handler HandlerFunc)
}
type HandlerFunc func(ctx *Context)
type HttpServer struct {
router
ms []Middleware
}
func NewHttpServer() *HttpServer {
return &HttpServer{
router: newRouter(),
}
}
func (s *HttpServer) Use(ms ...Middleware) {
if s.ms == nil {
s.ms = ms
return
}
s.ms = append(s.ms, ms...)
}
func (s *HttpServer) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
ctx := &Context{
Req: request,
Resp: writer,
}
// 路由注册的处理,在 middleware 后执行
root := s.serve
for i := len(s.ms) - 1; i >= 0; i-- {
root = s.ms[i](root)
}
var m Middleware = func(next HandlerFunc) HandlerFunc {
return func(ctx *Context) {
next(ctx)
s.flashResp(ctx)
}
}
// 将回写数据放到最后执行
root = m(root)
root(ctx)
}
func (s *HttpServer) serve(ctx *Context) {
mi, ok := s.findRoute(ctx.Req.Method, ctx.Req.URL.Path)
if !ok {
ctx.Resp.WriteHeader(http.StatusNotFound)
ctx.Resp.Write([]byte("未定义路由"))
return
}
ctx.PathParams = mi.pathParams
ctx.MatchedRoute = mi.n.route
mi.n.handle(ctx)
}
func (s *HttpServer) Get(path string, handler HandlerFunc) {
s.addRoute(http.MethodGet, path, handler)
}
func (s *HttpServer) Post(path string, handler HandlerFunc) {
s.addRoute(http.MethodPost, path, handler)
}
func (s *HttpServer) Start(addr string) {
http.ListenAndServe(addr, s)
}
func (s *HttpServer) flashResp(ctx *Context) {
if ctx.RespStatusCode > 0 {
ctx.Resp.WriteHeader(ctx.RespStatusCode)
}
_, err := ctx.Resp.Write(ctx.RespData)
if err != nil {
log.Fatalln("回写响应失败", err)
}
}