github.com/hellobchain/third_party@v0.0.0-20230331131523-deb0478a2e52/go-chi/chi/middleware/strip.go (about)

     1  package middleware
     2  
     3  import (
     4  	"github.com/hellobchain/newcryptosm/http"
     5  
     6  	"github.com/hellobchain/third_party/go-chi/chi"
     7  )
     8  
     9  // StripSlashes is a middleware that will match request paths with a trailing
    10  // slash, strip it from the path and continue routing through the mux, if a route
    11  // matches, then it will serve the handler.
    12  func StripSlashes(next http.Handler) http.Handler {
    13  	fn := func(w http.ResponseWriter, r *http.Request) {
    14  		var path string
    15  		rctx := chi.RouteContext(r.Context())
    16  		if rctx.RoutePath != "" {
    17  			path = rctx.RoutePath
    18  		} else {
    19  			path = r.URL.Path
    20  		}
    21  		if len(path) > 1 && path[len(path)-1] == '/' {
    22  			rctx.RoutePath = path[:len(path)-1]
    23  		}
    24  		next.ServeHTTP(w, r)
    25  	}
    26  	return http.HandlerFunc(fn)
    27  }
    28  
    29  // RedirectSlashes is a middleware that will match request paths with a trailing
    30  // slash and redirect to the same path, less the trailing slash.
    31  func RedirectSlashes(next http.Handler) http.Handler {
    32  	fn := func(w http.ResponseWriter, r *http.Request) {
    33  		var path string
    34  		rctx := chi.RouteContext(r.Context())
    35  		if rctx.RoutePath != "" {
    36  			path = rctx.RoutePath
    37  		} else {
    38  			path = r.URL.Path
    39  		}
    40  		if len(path) > 1 && path[len(path)-1] == '/' {
    41  			path = path[:len(path)-1]
    42  			http.Redirect(w, r, path, 301)
    43  			return
    44  		}
    45  		next.ServeHTTP(w, r)
    46  	}
    47  	return http.HandlerFunc(fn)
    48  }