-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathblade.go
248 lines (210 loc) · 6.2 KB
/
blade.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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
package hblade
import (
"net"
"net/http"
"os"
"os/signal"
"sync"
"syscall"
"time"
"github.com/json-iterator/go"
"github.com/pkg/errors"
"go.uber.org/zap"
)
var Json = jsoniter.ConfigCompatibleWithStandardLibrary
type Blade struct {
router Router
middleware []Middleware
contextPool sync.Pool
noFunc func(*Context) //404
}
// New creates a new blade.
func New() *Blade {
b := &Blade{
noFunc: nil,
}
// Context pool
b.contextPool.New = func() interface{} {
return &Context{b: b}
}
return b
}
func (b *Blade) NoFunc(f func(*Context)) {
b.noFunc = f
}
// Get registers your function to be called when the given GET path has been requested.
func (b *Blade) Get(path string, handler Handler) {
b.router.Add(http.MethodGet, path, handler)
b.BindMiddleware()
}
// Post registers your function to be called when the given POST path has been requested.
func (b *Blade) Post(path string, handler Handler) {
b.router.Add(http.MethodPost, path, handler)
b.BindMiddleware()
}
// Delete registers your function to be called when the given DELETE path has been requested.
func (b *Blade) Delete(path string, handler Handler) {
b.router.Add(http.MethodDelete, path, handler)
b.BindMiddleware()
}
// Put registers your function to be called when the given PUT path has been requested.
func (b *Blade) Put(path string, handler Handler) {
b.router.Add(http.MethodPut, path, handler)
b.BindMiddleware()
}
// Patch registers your function to be called when the given PATCH path has been requested.
func (b *Blade) Patch(path string, handler Handler) {
b.router.Add(http.MethodPatch, path, handler)
b.BindMiddleware()
}
// Options registers your function to be called when the given OPTIONS path has been requested.
func (b *Blade) Options(path string, handler Handler) {
b.router.Add(http.MethodOptions, path, handler)
b.BindMiddleware()
}
// Head registers your function to be called when the given HEAD path has been requested.
func (b *Blade) Head(path string, handler Handler) {
b.router.Add(http.MethodHead, path, handler)
b.BindMiddleware()
}
// Can bind static directory
// h.Static("/static", "static/")
func (b *Blade) Static(path, bind string) {
relativePath := path + "/*file"
handler := func(c *Context) error {
return c.File(bind + c.Get("file"))
}
b.Get(relativePath, handler)
}
// Any registers your function to be called with any http method.
func (b *Blade) Any(path string, handler Handler) {
b.router.Add(http.MethodGet, path, handler)
b.router.Add(http.MethodPost, path, handler)
b.router.Add(http.MethodDelete, path, handler)
b.router.Add(http.MethodPut, path, handler)
b.router.Add(http.MethodPatch, path, handler)
b.router.Add(http.MethodOptions, path, handler)
b.router.Add(http.MethodHead, path, handler)
b.BindMiddleware()
}
// Router returns the router used by the blade.
func (b *Blade) Router() *Router {
return &b.router
}
// Run starts your application with http.
func (b *Blade) Run(address string) error {
Log.Debug("Listening and serving HTTP",
zap.String("address", address))
server := &http.Server{
Addr: address,
Handler: b,
}
if err := server.ListenAndServe(); err != nil {
return errors.Wrapf(err, "addrs: %v", address)
}
stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt, syscall.SIGTERM)
<-stop
return nil
}
// Run starts your application with https.
func (b *Blade) RunTLS(addr, certFile, keyFile string) error {
Log.Debug("Listening and serving HTTPS",
zap.String("address", addr))
server := &http.Server{
Addr: addr,
Handler: b,
}
if err := server.ListenAndServeTLS(certFile, keyFile); err != nil {
return errors.Wrapf(err, "tls: %s/%s:%s", addr, certFile, keyFile)
}
stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt, syscall.SIGTERM)
<-stop
return nil
}
// Run starts your application by given server and listener.
func (b *Blade) RunServer(server *http.Server, l net.Listener) error {
Log.Debug("Listening and serving HTTP on listener what's bind with address@",
zap.String("address", l.Addr().String()))
server.Handler = b
if err := server.Serve(l); err != nil {
return errors.Wrapf(err, "listen server: %+v/%+v", server, l)
}
stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt, syscall.SIGTERM)
<-stop
return nil
}
// Use adds middleware to your middleware chain.
func (b *Blade) Use(middlewares ...Middleware) {
b.middleware = append(b.middleware, middlewares...)
}
// newContext returns a new context from the pool.
func (b *Blade) newContext(req *http.Request, res http.ResponseWriter) *Context {
c := b.contextPool.Get().(*Context)
c.status = http.StatusOK
c.request.req = req
c.response.rw = res
c.paramCount = 0
c.modifierCount = 0
return c
}
// ServeHTTP responds to the given request.
func (b *Blade) ServeHTTP(response http.ResponseWriter, request *http.Request) {
c := b.newContext(request, response)
b.router.Lookup(request.Method, request.URL.Path, c)
if c.handler == nil {
if b.noFunc != nil {
b.noFunc(c)
} else {
response.WriteHeader(http.StatusNotFound)
}
c.Close()
return
}
c.handler(c)
c.Close()
}
// Binding middleware
func (b *Blade) BindMiddleware() {
b.router.bind(func(handler Handler) Handler {
return handler.Bind(b.middleware...)
})
}
// Whether to record request logs
func (b *Blade) EnableLogRequest() {
b.Use(func(next Handler) Handler {
return func(c *Context) error {
Log = LogWithCtr(c)
start := time.Now()
st := start.Format("2006-01-02 15:04:05")
path := c.request.Path()
query := c.request.RawQuery()
method := c.request.Method()
var b []byte
if method != "GET" && method != "OPTIONS" && method != "HEAD" {
b, _ = c.request.RawDataSetBody()
c.SetKey(BodyBytesKey, b)
}
err := next(c)
end := time.Now()
latency := end.Sub(start)
if latency > time.Minute {
latency = latency - latency%time.Second
}
Log.Info("Request record",
zap.String("time", st),
zap.Int("status", c.Status()),
zap.String("method", method),
zap.String("path", path),
zap.String("query", query),
zap.ByteString("body", b),
zap.String("ip", c.ClientIP()),
zap.String("user-agent", c.request.req.UserAgent()),
zap.Duration("latency", latency))
Log = LogReleaseCtr(c)
return err
}
})
}