54 lines
566 B
Go
54 lines
566 B
Go
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
"strings"
|
|
)
|
|
|
|
func NormalizePath(
|
|
next http.Handler,
|
|
) http.Handler {
|
|
|
|
return http.HandlerFunc(
|
|
func(
|
|
w http.ResponseWriter,
|
|
r *http.Request,
|
|
) {
|
|
|
|
p := r.URL.Path
|
|
|
|
if p != "/" {
|
|
|
|
for strings.HasSuffix(
|
|
p,
|
|
"/",
|
|
) {
|
|
|
|
p = strings.TrimSuffix(
|
|
p,
|
|
"/",
|
|
)
|
|
}
|
|
|
|
if p == "" {
|
|
p = "/"
|
|
}
|
|
|
|
if p != r.URL.Path {
|
|
|
|
http.Redirect(
|
|
w,
|
|
r,
|
|
p,
|
|
http.StatusMovedPermanently,
|
|
)
|
|
|
|
return
|
|
}
|
|
}
|
|
|
|
next.ServeHTTP(w, r)
|
|
},
|
|
)
|
|
}
|