-2

Basically, I want to write one middleware which closes transaction object is created while a request. I am using gorilla mux package. I am familiar with python-Django middlewares and it gives proper handling of error or response. but not able to find anything similar with golang

Niel_patel
  • 74
  • 8

1 Answers1

-1

In Go lang you can create a middle-ware too, below I've written the process to create handler as validateMiddleware then called it when TestEndpoint API requested.

func main() {
    router := mux.NewRouter()

    router.HandleFunc("/test", ValidateMiddleware(TestEndpoint)).Methods("GET")
    log.Fatal(http.ListenAndServe(":12345", router))
}

And now you can create your validateMiddleware handler as:

    func ValidateMiddleware(next http.HandlerFunc) http.HandlerFunc {
        return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
            authorizationHeader := req.Header.Get("authorization")
                    if authorizationHeader != "" {
                        // if true, then request for next handler.
                        next(w, req)
                    } else {
                        json.NewEncoder(w).Encode(Exception{Message: "Invalid authorization token"})
                        return
                    }
        })
    }

And finally create original requested handler TestEndpoint

func TestEndpoint(w http.ResponseWriter, req *http.Request) {
    fmt.Println("Hello Go middleware!!!")
}
saddam
  • 809
  • 8
  • 23
  • 1
    I am starting a transaction in the handler and want to close it in middleware whether it throws an error from the handler or returns response. – Niel_patel Oct 15 '18 at 13:27
  • As you can see the response in `else` part, if authorization failed in `validateMiddleware` handler, so you can also return like this. And don't forget to mention `return` keyword if you don't want to execute further code after throws an error. – saddam Oct 15 '18 at 13:31
  • I think the code you shared will call before the actual handler but I want to write it in a way that it will be called after handler's response or error it throws. – Niel_patel Oct 15 '18 at 13:38
  • you want to manage errors throwing by your code? then why you need a `middleware`? why don't you use `error` handle process like: `if err != nil { //something to response }` – saddam Oct 15 '18 at 13:44
  • I want to close the SQL transaction which started in the handler. because I am writing repetitive code everywhere, and if I found a way to write a middleware which closed after any response from a handler. i am looking for error because if it throws an error then i want to roll back the transaction else i will commit it on success. – Niel_patel Oct 15 '18 at 13:47
  • `func closeTxnMiddleware(next http.HandlerFunc) http.HandlerFunc { return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { if w.response_code == 200 || 201 { if err = txo.Commit(); err == nil { return false } } else { txo.Rollback(); } }) }` i am looking for something like this – Niel_patel Oct 15 '18 at 13:52
  • may be this [link](https://stackoverflow.com/questions/42871194/how-can-i-combine-go-middleware-pattern-with-error-returning-request-handlers) would be helpful for you. – saddam Oct 15 '18 at 13:59