How to make middleware error out and not go to next middleware/handler

93 views Asked by At

What I am trying to achieve is the following: I have my own server, with one endpoint only and every call I expect to receive should be from one source only.
This source signs their package before sending it to my server.
I want to implement this signature validation on my server for any call I receive.
Since any call should be from this expected source I do not want to validate the signature in my handler itself but I want it to be clean and at middleware level. In this way, if one day I implement a new endpoint that the known client is allowed to call, I won't have to repeat the signature validation in the new handler/route because already happening at middleware level.

The problem I am having is that I do not how to error out at middleware level, in such a way that the call doesn't proceed further to the next step in case the validation fails. What I am having so far.

in main.go

server.Router.Use(verifySignatureMiddleware) // server.Router is my Router *chi.Mux
server.Router.Post("/", dummyHandler.ServeHTTP)

then my verifySignatureMiddleware is defined as follow:

func verifySignatureMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

    bodyBytes, err := io.ReadAll(r.Body)
    if err != nil {
      // print error and make sure that code execution stops here
    }
    
    
    isValid, err = otherLogicForSignatureValidation()
    if err != nil {
        // print error and make sure that code execution stops here
    }

    if isValid == false {
        // print error and make sure that code execution stops here
    }

    next.ServeHTTP(w, r)
})

}

Thus, there are different levels at which the middleware can fail and I would like in any of those cases the handling of the http request stops and logs the error.

0

There are 0 answers