-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
middlewares.go
62 lines (59 loc) · 1.56 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
package http
import (
"net/http"
"net/url"
"strings"
)
func CreateMakeQueryCaseInsensitiveMiddleware(queryCaseInsensitive map[string]string, opts ...LogOpt) func(next http.Handler) http.Handler {
cfg := NewLogOptions()
for _, o := range opts {
o(cfg)
}
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
u, err := url.ParseRequestURI(r.RequestURI)
if err != nil {
cfg.logger.Errorf("cannot make query case insensitive: %w", err)
next.ServeHTTP(w, r)
return
}
queries := u.Query()
newQueries := make(url.Values)
for key, val := range queries {
newKey, ok := queryCaseInsensitive[strings.ToLower(key)]
if ok {
newQueries[newKey] = val
} else {
newQueries[key] = val
}
}
r.URL.RawQuery = newQueries.Encode()
r.RequestURI = u.String()
next.ServeHTTP(w, r)
})
}
}
func CreateTrailSlashSuffixMiddleware(queryCaseInsensitive map[string]string, opts ...LogOpt) func(next http.Handler) http.Handler {
cfg := NewLogOptions()
for _, o := range opts {
o(cfg)
}
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
u, err := url.ParseRequestURI(r.RequestURI)
if err != nil {
cfg.logger.Errorf("cannot trail slash suffix: %v", err)
next.ServeHTTP(w, r)
return
}
l := len(u.Path)
u.Path = strings.TrimRight(u.Path, "/")
if l > 0 && len(u.Path) == 0 {
u.Path = "/"
}
r.RequestURI = u.String()
r.URL.Path = u.Path
next.ServeHTTP(w, r)
})
}
}