...

Source file src/github.com/go-chi/chi/middleware/strip.go

Documentation: github.com/go-chi/chi/middleware

     1  package middleware
     2  
     3  import (
     4  	"fmt"
     5  	"net/http"
     6  
     7  	"github.com/go-chi/chi"
     8  )
     9  
    10  // StripSlashes is a middleware that will match request paths with a trailing
    11  // slash, strip it from the path and continue routing through the mux, if a route
    12  // matches, then it will serve the handler.
    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  // RedirectSlashes is a middleware that will match request paths with a trailing
    31  // slash and redirect to the same path, less the trailing slash.
    32  //
    33  // NOTE: RedirectSlashes middleware is *incompatible* with http.FileServer,
    34  // see https://github.com/go-chi/chi/issues/343
    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