-
Notifications
You must be signed in to change notification settings - Fork 1
/
middleware.go
75 lines (64 loc) · 1.86 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
package echotool
import (
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"github.com/popeyeio/handy"
"moul.io/http2curl"
)
const (
KeyRequestID = "x-request-id"
)
func SetRequestID(f func(c echo.Context) string) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
id, _ := HeaderString(c, KeyRequestID)
if handy.IsEmptyStr(id) && f != nil {
id = f(c)
}
c.Set(KeyRequestID, id)
return next(c)
}
}
}
func GetRequestID(c echo.Context) string {
val := c.Get(KeyRequestID)
if val != nil {
if id, ok := val.(string); ok {
return id
}
}
return handy.StrEmpty
}
// AddTraceID adds trace id to log for troubleshooting problems and so on.
func AddTraceID(f func(c echo.Context) string) HandlerFunc {
return func(c echo.Context, ec *Context) {
if f != nil {
ec.SetNamedValue(f(c))
}
}
}
// AddNotice adds kv pair to log for troubleshooting problems and so on.
func AddNotice(key, value string) HandlerFunc {
return func(c echo.Context, ec *Context) {
if !handy.IsEmptyStr(key) || !handy.IsEmptyStr(value) {
ec.SetCustomValue(key, value)
}
}
}
func PrintRequest() HandlerFunc {
return func(c echo.Context, ec *Context) {
if cmd, err := http2curl.GetCurlCommand(c.Request()); err == nil {
CtxInfoKV(ec, cmd.String())
}
}
}
func DefaultCORS() echo.MiddlewareFunc {
return middleware.CORS()
}
func UnsafeCORS() echo.MiddlewareFunc {
middleware.DefaultCORSConfig.AllowCredentials = true
middleware.DefaultCORSConfig.UnsafeWildcardOriginWithAllowCredentials = true // send origin back
middleware.DefaultCORSConfig.MaxAge = 2592000 // the result of preflight can be cached one month
middleware.DefaultCORSConfig.ExposeHeaders = []string{echo.HeaderVary} // headers can be accessed by clients
return DefaultCORS()
}