-
Notifications
You must be signed in to change notification settings - Fork 0
/
strip_wildcard.go
45 lines (36 loc) · 975 Bytes
/
strip_wildcard.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package http
import (
"net/http"
"net/url"
"strings"
)
func StripWildcardPrefix(prefix string, h http.Handler) http.Handler {
staticSegments := []int{} // Indices of static segments in the prefix
prefixSegments := strings.Split(prefix, "/")
for i, segment := range prefixSegments {
if !strings.Contains(segment, "{") || !strings.Contains(segment, "}") {
staticSegments = append(staticSegments, i)
}
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
pathSegments := strings.Split(r.URL.Path, "/")
matched := true
for _, idx := range staticSegments {
if idx >= len(pathSegments) || prefixSegments[idx] != pathSegments[idx] {
matched = false
break
}
}
if !matched {
http.NotFound(w, r)
return
}
newPath := "/" + strings.Join(pathSegments[len(prefixSegments):], "/")
r2 := new(http.Request)
*r2 = *r
r2.URL = new(url.URL)
*r2.URL = *r.URL
r2.URL.Path = newPath
h.ServeHTTP(w, r2)
})
}