I am writing a middleware function in golang net/http
using chi but the controller function isn't being executed (couldn't print 1 in the function).
Calling the middleware:
r.With(myMiddleware.Authware).Post("/tryon", mainController.Tryon)
package - myMiddleware
func Authware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Middleware code
})
}
package - mainController
func Tryon(w http.ResponseWriter, r *http.Request) {
// Dosent print anything
log.Println(1)
}
I read the documentation but it didn't help much
Could you please help out debug and let me know why is this happening? Also, if I want to return some data from the middleware to the controller, how do I do it?
CodePudding user response:
main.go
func main() {
r := chi.NewRouter()
r.With(middle.Authware).Post("/tryon", controller.Tryon)
http.ListenAndServe(":3000", r)
}
Invoke the controller
after passing the middleware
logic:
middleware.go
func Authware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Middleware code
next.ServeHTTP(w, r)
})
}
controller.go
func Tryon(w http.ResponseWriter, r *http.Request) {
// Doesn't print anything
log.Println(1)
}
If you really want it to be a POST
request: curl -X POST localhost:3000/tryon
P.S: go through the code example here: https://github.com/go-chi/chi