forked from go-chi/chi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
strip.go
49 lines (45 loc) · 1.29 KB
/
strip.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
package middleware
import (
"net/http"
"github.com/pressly/chi"
"golang.org/x/net/context"
)
// StripSlashes is a middleware that will match request paths with a trailing
// slash, strip it from the path and continue routing through the mux, if a route
// matches, then it will serve the handler.
func StripSlashes(next chi.Handler) chi.Handler {
fn := func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
var path string
rctx := chi.RouteContext(ctx)
if rctx.RoutePath != "" {
path = rctx.RoutePath
} else {
path = r.URL.Path
}
if len(path) > 1 && path[len(path)-1] == '/' {
rctx.RoutePath = path[:len(path)-1]
}
next.ServeHTTPC(ctx, w, r)
}
return chi.HandlerFunc(fn)
}
// RedirectSlashes is a middleware that will match request paths with a trailing
// slash and redirect to the same path, less the trailing slash.
func RedirectSlashes(next chi.Handler) chi.Handler {
fn := func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
var path string
rctx := chi.RouteContext(ctx)
if rctx.RoutePath != "" {
path = rctx.RoutePath
} else {
path = r.URL.Path
}
if len(path) > 1 && path[len(path)-1] == '/' {
path = path[:len(path)-1]
http.Redirect(w, r, path, 301)
return
}
next.ServeHTTPC(ctx, w, r)
}
return chi.HandlerFunc(fn)
}