Skip to content

Commit d19eafd

Browse files
fix: encoded urn not matched properly to routes (#21)
* fix: encoded urn not matched properly to routes * feat(router): log if url cannot be decoded
1 parent 317e8c8 commit d19eafd

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

api/middlewares.go

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package api
2+
3+
import (
4+
"net/http"
5+
"net/url"
6+
7+
"github.com/gorilla/mux"
8+
"github.com/sirupsen/logrus"
9+
)
10+
11+
func decodeURLMiddleware(logger logrus.FieldLogger) mux.MiddlewareFunc {
12+
return func(h http.Handler) http.Handler {
13+
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
14+
newVars := map[string]string{}
15+
for key, val := range mux.Vars(r) {
16+
decodedVal, err := url.QueryUnescape(val)
17+
if err != nil {
18+
logger.Warnf("error decoding url %s", val)
19+
decodedVal = val
20+
}
21+
22+
newVars[key] = decodedVal
23+
}
24+
25+
r = mux.SetURLVars(r, newVars)
26+
h.ServeHTTP(rw, r)
27+
})
28+
}
29+
}

api/routes.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,14 @@ type Config struct {
1818
}
1919

2020
func RegisterRoutes(router *mux.Router, config Config) {
21+
// By default mux will decode url and then match the decoded url against the route
22+
// we reverse the steps by telling mux to use encoded path to match the url
23+
// then we manually decode via custom middleware (decodeURLMiddleware).
24+
//
25+
// This is to allow urn that has "/" to be matched correctly to the route
26+
router.UseEncodedPath()
27+
router.Use(decodeURLMiddleware(config.Logger))
28+
2129
typeHandler := handlers.NewTypeHandler(
2230
config.Logger.WithField("reporter", "type-handler"),
2331
config.TypeRepository,

0 commit comments

Comments
 (0)