/
middlewares.go
126 lines (111 loc) · 2.57 KB
/
middlewares.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
package handlers
import (
"context"
"crypto/md5"
"encoding/hex"
"fmt"
"net/http"
"time"
"github.com/gookit/rux"
)
// FavIcon uri for favicon.ico
const FavIcon = "/favicon.ico"
// IgnoreFavIcon middleware
func IgnoreFavIcon() rux.HandlerFunc {
return func(c *rux.Context) {
if c.URL().Path == FavIcon {
c.AbortThen().NoContent()
return
}
}
}
// GenRequestID for the request
func GenRequestID() rux.HandlerFunc {
return func(c *rux.Context) {
reqID := genMd5(fmt.Sprintf("rux-%d", time.Now().Nanosecond()))
// add reqID to context
c.Set("reqID", reqID)
}
}
// HTTPBasicAuth for the request
// Usage:
//
// r.GET("/auth", func(c *rux.Context) {
// c.WriteString("hello")
// }, HTTPBasicAuth(map[string]string{"testuser": "123"}))
//
func HTTPBasicAuth(accounts map[string]string) rux.HandlerFunc {
return func(c *rux.Context) {
user, pwd, ok := c.Req.BasicAuth()
if !ok {
c.SetHeader("WWW-Authenticate", `Basic realm="THE REALM"`)
c.AbortWithStatus(401, "Unauthorized")
return
}
if len(accounts) > 0 {
srcPwd, ok := accounts[user]
if !ok || srcPwd != pwd {
c.AbortWithStatus(403)
}
}
c.Set("username", user)
c.Set("password", pwd)
}
}
// PanicsHandler middleware
func PanicsHandler() rux.HandlerFunc {
// if debug {
// debug.PrintStack()
// }
return func(c *rux.Context) {
defer func() {
if err := recover(); err != nil {
c.Resp.WriteHeader(500)
}
}()
c.Next()
}
}
// Timeout is a middleware for handle logic.
// the method is refer from "github.com/go-chi/chi/middleware"
//
// It's required that you select the ctx.Done() channel to check for the signal
// if the context has reached its deadline and return, otherwise the timeout
// signal will be just ignored.
//
// ie. a route/handler may look like:
//
// r.GET("/long", func(c *rux.Context) {
// ctx := c.Req.Context()
// processTime := time.Duration(rand.Intn(4)+1) * time.Second
//
// select {
// case <-ctx.Done():
// return
//
// case <-time.After(processTime):
// // The above channel simulates some hard work.
// }
//
// c.WriteBytes([]byte("done"))
// })
func Timeout(timeout time.Duration) rux.HandlerFunc {
return func(c *rux.Context) {
ctx, cancel := context.WithTimeout(c.Req.Context(), timeout)
defer func() {
cancel()
if ctx.Err() == context.DeadlineExceeded {
c.Resp.WriteHeader(http.StatusGatewayTimeout)
}
}()
// override Request
c.Req = c.Req.WithContext(ctx)
c.Next()
}
}
// genMd5 生成32位md5字串
func genMd5(s string) string {
h := md5.New()
h.Write([]byte(s))
return hex.EncodeToString(h.Sum(nil))
}