-
-
Notifications
You must be signed in to change notification settings - Fork 96
/
middleware.go
94 lines (86 loc) · 2.64 KB
/
middleware.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
package TigoWeb
import (
"errors"
"github.com/gorilla/mux"
"github.com/karldoenitz/Tigo/logger"
"net/http"
"time"
)
// middleware http中间件
type middleware func(next http.HandlerFunc) http.HandlerFunc
// Middleware Tigo的中间件类型,函数返回值true表示http请求继续处理,false表示请求结束,不再往下处理
type Middleware func(*http.ResponseWriter, *http.Request) bool
// chainMiddleware 是http中间件生成器
func chainMiddleware(mw ...middleware) middleware {
return func(final http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
last := final
for i := len(mw) - 1; i >= 0; i-- {
last = mw[i](last)
}
last(w, r)
}
}
}
func convertHandleFuncMV(v Middleware) middleware {
return func(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// 此处需要判断请求是否继续交给下一个中间件处理
if isGoOn := v(&w, r); isGoOn {
next.ServeHTTP(w, r)
}
}
}
}
func convertHandleMV(v Middleware) mux.MiddlewareFunc {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// 此处需要判断请求是否继续交给下一个中间件处理
if isGoOn := v(&w, r); isGoOn {
next.ServeHTTP(w, r)
}
})
}
}
// InternalServerErrorMiddleware 用来处理控制层出现的异常的中间件
func InternalServerErrorMiddleware(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var err error
defer func() {
r := recover()
if r != nil {
switch t := r.(type) {
case string:
err = errors.New(t)
case error:
err = t
default:
err = errors.New("unknown error")
}
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}()
next.ServeHTTP(w, r)
}
}
// HttpContextLogMiddleware 记录一个http请求响应时间的中间件
func HttpContextLogMiddleware(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
startTime := time.Now()
requestMethod := r.Method
url := r.RequestURI
httpResponseWriter := HttpResponseWriter{w, http.StatusOK}
defer func() {
status := httpResponseWriter.GetStatus()
duration := time.Now().Sub(startTime).Seconds() * 1e3
switch status {
case http.StatusInternalServerError:
logger.Error.Printf("%s | %fms | %s %s", logger.StatusColor(status), duration, requestMethod, url)
break
default:
logger.Info.Printf("%s | %fms | %s %s", logger.StatusColor(status), duration, requestMethod, url)
}
}()
next.ServeHTTP(&httpResponseWriter, r)
}
}