Skip to content

Commit

Permalink
fix: encoded urn not matched properly to routes (#21)
Browse files Browse the repository at this point in the history
* fix: encoded urn not matched properly to routes

* feat(router): log if url cannot be decoded
  • Loading branch information
StewartJingga authored Nov 8, 2021
1 parent 317e8c8 commit d19eafd
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
29 changes: 29 additions & 0 deletions api/middlewares.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package api

import (
"net/http"
"net/url"

"github.com/gorilla/mux"
"github.com/sirupsen/logrus"
)

func decodeURLMiddleware(logger logrus.FieldLogger) mux.MiddlewareFunc {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
newVars := map[string]string{}
for key, val := range mux.Vars(r) {
decodedVal, err := url.QueryUnescape(val)
if err != nil {
logger.Warnf("error decoding url %s", val)
decodedVal = val
}

newVars[key] = decodedVal
}

r = mux.SetURLVars(r, newVars)
h.ServeHTTP(rw, r)
})
}
}
8 changes: 8 additions & 0 deletions api/routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,14 @@ type Config struct {
}

func RegisterRoutes(router *mux.Router, config Config) {
// By default mux will decode url and then match the decoded url against the route
// we reverse the steps by telling mux to use encoded path to match the url
// then we manually decode via custom middleware (decodeURLMiddleware).
//
// This is to allow urn that has "/" to be matched correctly to the route
router.UseEncodedPath()
router.Use(decodeURLMiddleware(config.Logger))

typeHandler := handlers.NewTypeHandler(
config.Logger.WithField("reporter", "type-handler"),
config.TypeRepository,
Expand Down

0 comments on commit d19eafd

Please sign in to comment.