MCPcopy Create free account
hub / github.com/goadesign/goa / SmartRedirectSlashes

Function SmartRedirectSlashes

http/middleware/chi.go:20–59  ·  view source on GitHub ↗

SmartRedirectSlashes is a middleware that matches the request path with patterns added to the router and redirects it. If a pattern is added to the router with a trailing slash, any matches on that pattern without a trailing slash will be redirected to the version with the slash. If a pattern does

(next http.Handler)

Source from the content-addressed store, hash-verified

18// This middleware depends on chi, so it needs to be mounted on chi's router.
19// It make the router behavior similar to httptreemux.
20func SmartRedirectSlashes(next http.Handler) http.Handler {
21 fn := func(w http.ResponseWriter, r *http.Request) {
22 rctx := chi.RouteContext(r.Context())
23 if rctx != nil {
24 var path string
25 if rctx.RoutePath != "" {
26 path = rctx.RoutePath
27 } else {
28 path = r.URL.Path
29 }
30 var method string
31 if rctx.RouteMethod != "" {
32 method = rctx.RouteMethod
33 } else {
34 method = r.Method
35 }
36 if len(path) > 1 {
37 if rctx.Routes != nil {
38 if !rctx.Routes.Match(chi.NewRouteContext(), method, path) {
39 if path[len(path)-1] == '/' {
40 path = path[:len(path)-1]
41 } else {
42 path += "/"
43 }
44 if rctx.Routes.Match(chi.NewRouteContext(), method, path) {
45 if r.URL.RawQuery != "" {
46 path = fmt.Sprintf("%s?%s", path, r.URL.RawQuery)
47 }
48 redirectURL := fmt.Sprintf("//%s%s", r.Host, path)
49 http.Redirect(w, r, redirectURL, http.StatusMovedPermanently)
50 return
51 }
52 }
53 }
54 }
55 }
56 next.ServeHTTP(w, r)
57 }
58 return http.HandlerFunc(fn)
59}

Callers

nothing calls this directly

Calls 2

ContextMethod · 0.80
ServeHTTPMethod · 0.65

Tested by

no test coverage detected