MCPcopy
hub / github.com/labstack/echo / ToMiddleware

Method ToMiddleware

middleware/slash.go:103–142  ·  view source on GitHub ↗

ToMiddleware converts RemoveTrailingSlashConfig to middleware or returns an error for invalid configuration

()

Source from the content-addressed store, hash-verified

101
102// ToMiddleware converts RemoveTrailingSlashConfig to middleware or returns an error for invalid configuration
103func (config RemoveTrailingSlashConfig) ToMiddleware() (echo.MiddlewareFunc, error) {
104 if config.Skipper == nil {
105 config.Skipper = DefaultSkipper
106 }
107 if config.RedirectCode != 0 && (config.RedirectCode < http.StatusMultipleChoices || config.RedirectCode > http.StatusPermanentRedirect) {
108 // this is same check as `echo.context.Redirect()` does, but we can check this before even serving the request.
109 return nil, errors.New("invalid redirect code for remove trailing slash middleware")
110 }
111
112 return func(next echo.HandlerFunc) echo.HandlerFunc {
113 return func(c *echo.Context) error {
114 if config.Skipper(c) {
115 return next(c)
116 }
117
118 req := c.Request()
119 url := req.URL
120 path := url.Path
121 qs := c.QueryString()
122 l := len(path) - 1
123 if l > 0 && strings.HasSuffix(path, "/") {
124 path = path[:l]
125 uri := path
126 if qs != "" {
127 uri += "?" + qs
128 }
129
130 // Redirect
131 if config.RedirectCode != 0 {
132 return c.Redirect(config.RedirectCode, sanitizeURI(uri))
133 }
134
135 // Forward
136 req.RequestURI = uri
137 url.Path = path
138 }
139 return next(c)
140 }
141 }, nil
142}
143
144func sanitizeURI(uri string) string {
145 // double slash `\\`, `//` or even `\/` is absolute uri for browsers and by redirecting request to that uri

Callers

nothing calls this directly

Calls 4

RequestMethod · 0.80
QueryStringMethod · 0.80
RedirectMethod · 0.80
sanitizeURIFunction · 0.70

Tested by

no test coverage detected