2

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?

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.