-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
142 lines (121 loc) · 2.98 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
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
package main
import (
"context"
"fmt"
"log"
"net"
"net/http"
"strconv"
"time"
)
type HttpServer interface {
http.Handler
Start(address string) error
Shutdown(ctx context.Context) error
addRoute(method, path string, handler HandleFunc, ms ...Middleware)
}
type HTTPServer struct {
name string
addr string
reject bool
router
log *log.Logger
}
type ServerOption func(server *HTTPServer)
func NewHTTPServer(name, addr string, opts ...ServerOption) *HTTPServer {
s := &HTTPServer{
router: newRouter(),
name: name,
addr: addr,
log: log.Default(),
}
for _, opt := range opts {
opt(s)
}
return s
}
func (h *HTTPServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if h.reject {
w.WriteHeader(http.StatusServiceUnavailable)
_, _ = w.Write([]byte("服务已关闭"))
return
}
ctx := &Context{
Request: r,
ResponseWriter: w,
}
h.serve(ctx)
}
func (h *HTTPServer) serve(ctx *Context) {
target, ok := h.findRoute(ctx.Request.Method, ctx.Request.URL.Path)
if target.n != nil {
ctx.PathParams = target.pathParams
ctx.MatchedRoute = target.n.route
}
var root HandleFunc = func(ctx *Context) {
if !ok || target.n == nil || target.n.handler == nil {
ctx.StatusCode = 404
ctx.ResponseData = []byte("404 NOT FOUND")
return
}
target.n.handler(ctx)
}
for i := len(target.mdls) - 1; i >= 0; i-- {
root = target.mdls[i](root)
}
var m Middleware = func(next HandleFunc) HandleFunc {
return func(ctx *Context) {
next(ctx)
h.flushResponse(ctx)
}
}
root = m(root)
root(ctx)
}
func (h *HTTPServer) flushResponse(ctx *Context) {
if ctx.StatusCode > 0 {
ctx.ResponseWriter.WriteHeader(ctx.StatusCode)
}
ctx.ResponseWriter.Header().Set("Content-Length", strconv.Itoa(len(ctx.ResponseData)))
_, err := ctx.ResponseWriter.Write(ctx.ResponseData)
if err != nil {
h.log.Fatalln("回写响应失败", err)
}
}
func (h *HTTPServer) Start() error {
l, err := net.Listen("tcp", h.addr)
if err != nil {
return err
}
return http.Serve(l, h)
//return http.ListenAndServe(addr, h)
}
func (h *HTTPServer) Shutdown(ctx context.Context) error {
// sleep 模拟这个过程
fmt.Printf("%s shutdown...\n", h.name)
time.Sleep(time.Second)
fmt.Printf("%s shutdown!!!\n", h.name)
return nil
}
func (h *HTTPServer) stop(ctx context.Context) error {
log.Printf("服务器 %s 关闭中", h.name)
return h.Shutdown(ctx)
}
func (h *HTTPServer) rejectReq() {
h.reject = true
}
func (h *HTTPServer) Get(path string, handleFunc HandleFunc) {
h.addRoute(http.MethodGet, path, handleFunc)
}
func (h *HTTPServer) Post(path string, handleFunc HandleFunc) {
h.addRoute(http.MethodPost, path, handleFunc)
}
func (h *HTTPServer) Delete(path string, handleFunc HandleFunc) {
h.addRoute(http.MethodDelete, path, handleFunc)
}
func (h *HTTPServer) PUT(path string, handleFunc HandleFunc) {
h.addRoute(http.MethodPut, path, handleFunc)
}
func (h *HTTPServer) Options(path string, handleFunc HandleFunc) {
h.addRoute(http.MethodOptions, path, handleFunc)
}