0

This might just be because of my inexperience, but I've taken over a webserver solution written in Go and I have some issues.

The routing is set up in such a way that each "top" route is mounted to the router with router.Mount() with a handler attached to each mounted route. Example:

router.Mount("/group", (handler.NewGroupHandler(groupSrv, render)).Router())

So, within this mounted route I want to add a middleware to get a specific URL parameter. I've tried around, and followed this guide https://medium.com/@szablowska.patrycja/chi-and-missing-urlparam-in-middleware-9435c48a063b which seems to have worked for other. However, this haven't worked for me, which I now suspect is because of the approach with mounting.

The idea of the middleware is quite simple, just check the URL param against some requirements. I could of course do this manually in every path, but a middleware would be better both for readability and future development. How the middleware is written:

func GroupMiddleware() func(next http.Handler) http.Handler {
    return func(next http.Handler) http.Handler {
        fn := func(w http.ResponseWriter, r *http.Request) {
            groupIDStr := chi.URLParam(r, "group_id")
            if checkAgainstGroupID {
                // Do something, raise error
            } else {
                next.ServeHTTP(w, r)
            }
        }

        return http.HandlerFunc(fn)
    }
}

And then applied like this:

r.With(subhandler.GroupMiddleware).Route("/{group_id}", func(r chi.Router) {
    r.Get("/", h.get)
})

Which obviously doesn't work. Any help would be appreciated because I can't believe that mounting routes makes it impossible to add middleware to subgroups.

Edit: This worked perfectly, it was just me that didn't register that I called an unaffected route. So in case someone else should end up with this same question, know that this actually is a valid approach.

Terris
  • 25
  • 8
  • 1
    I suspect that the issue is the order of execution (```GroupMiddleware``` is run before the Route extracts ```{group_id}```). Try moving the call to the middleware within the closure (i.e. ```r.Use(GroupMiddleware)``` just above ```r.Get...```) – Brits Jan 28 '20 at 09:04
  • Thank you for the comment @Brits. It made me look at it another time, and wouldn't you know? My original code worked perfectly, it was just me that stupidly enough sat last evening and tried calling a part of the group-route that weren't included in the middleware. – Terris Jan 28 '20 at 13:14

0 Answers0