-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhttp_handler.go
46 lines (35 loc) · 1.01 KB
/
http_handler.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
package easycall
import (
"net/http"
"github.com/starjiang/elog"
)
type HttpHandler struct {
middlewares []*HttpMiddlewareInfo
}
func NewHttpHandler(middlewares []*HttpMiddlewareInfo) *HttpHandler {
return &HttpHandler{middlewares: middlewares}
}
type HttpMiddlewareFunc func(w http.ResponseWriter, r *http.Request, next *HttpMiddlewareInfo)
type HttpMiddlewareInfo struct {
Middleware HttpMiddlewareFunc
Next *HttpMiddlewareInfo
}
func (hh *HttpHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if len(hh.middlewares) > 0 {
hh.middlewares[0].Middleware(w, r, hh.middlewares[0].Next)
} else {
elog.Error("HttpMiddleware chain is empty")
}
}
func (hh *HttpHandler) AddMiddleware(middleware HttpMiddlewareFunc) *HttpHandler {
if hh.middlewares == nil {
hh.middlewares = make([]*HttpMiddlewareInfo, 0)
}
minfo := &HttpMiddlewareInfo{middleware, nil}
mlen := len(hh.middlewares)
if mlen > 0 {
hh.middlewares[mlen-1].Next = minfo
}
hh.middlewares = append(hh.middlewares, minfo)
return hh
}