...
1 package middleware
2
3 import (
4 "fmt"
5 "net/http"
6
7 "github.com/go-chi/chi"
8 )
9
10
11
12
13 func StripSlashes(next http.Handler) http.Handler {
14 fn := func(w http.ResponseWriter, r *http.Request) {
15 var path string
16 rctx := chi.RouteContext(r.Context())
17 if rctx.RoutePath != "" {
18 path = rctx.RoutePath
19 } else {
20 path = r.URL.Path
21 }
22 if len(path) > 1 && path[len(path)-1] == '/' {
23 rctx.RoutePath = path[:len(path)-1]
24 }
25 next.ServeHTTP(w, r)
26 }
27 return http.HandlerFunc(fn)
28 }
29
30
31
32
33
34
35 func RedirectSlashes(next http.Handler) http.Handler {
36 fn := func(w http.ResponseWriter, r *http.Request) {
37 var path string
38 rctx := chi.RouteContext(r.Context())
39 if rctx.RoutePath != "" {
40 path = rctx.RoutePath
41 } else {
42 path = r.URL.Path
43 }
44 if len(path) > 1 && path[len(path)-1] == '/' {
45 if r.URL.RawQuery != "" {
46 path = fmt.Sprintf("%s?%s", path[:len(path)-1], r.URL.RawQuery)
47 } else {
48 path = path[:len(path)-1]
49 }
50 http.Redirect(w, r, path, 301)
51 return
52 }
53 next.ServeHTTP(w, r)
54 }
55 return http.HandlerFunc(fn)
56 }
57
View as plain text