What is the correct solution to pass 2 objects to the handlers

132 Views Asked by At

Hi there is a need to pass a json object to check authentication in each request

for this purpose i am using gorilla package

func middlewareFirstAuthCheck(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Println("middlewareFirstAuthCheck - Before Handler")


next.ServeHTTP(w, r)

})
}

func StandartHandler(w http.ResponseWriter, r *http.Request) {


}

in standard handler i accept json object, and in middlewareFirstAuthCheck i accept different json object

middlewareFirstAuthCheck is executed first

there is an understanding of what needs to be done, but how to implement it correctly?

1

There are 1 best solutions below

5
Lucio De Simone On

Keep in mind that the code running inside this function is not safe for a mux server:

func middlewareFirstAuthCheck(next http.Handler) http.Handler {
    // don't manage something related to request if you have a mux server
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        log.Println("middlewareFirstAuthCheck - Before Handler")
        // you could get the r.Body or r.Headers here to get the user authenticated
        next.ServeHTTP(w, r)
    })
}

Ideally if you wanna handle permissions you should be setting them on the middleware depending the scope of your endpoint. Something like:

// please don't mind the terrible function/variable names
router.Get("/url", authMiddlewareForScope(s.handleTask(), "scope:to:handle:task"))

If you want this roles to be configurable by your application you will need a more elegant solution.

Please let me know if