This page looks best with JavaScript enabled

GO Middleware - request response interceptors/filters

 ·  ☕ 1 min read  ·  ✍️ Neeraj Sidhaye · 👀... views

What is GO Middleware?

Go middleware are like filters which gets executed for performing pre and/or post processing of the request.

middleware or the filters implementation is achieved through http handler wrappers.

HttpHandler wrappers are the functions which takes http.Handler as input and returns http.Handler as output.

Defining Middleware

Here we have defined a simple log request middleware, which takes one argument and returns one argument and of the same type http.Handler

func logReq(next http.Handler) http.Handler {  

	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		
		log.Println("URL called -", r.URL ," ,before calling original handler")
		
		next.ServeHTTP(w, r) // calling original handler ( helloHandler)
		
		log.Println("After calling original handler")
	})
}

Middleware Execution

In order for this logReq middleware to execute, we will attach our original helloHandler to logReq middleware.

serveMux.Handle("/hello", logReq(helloHandler))

After this, every request on “/hello” will execute middleware ( logReq) before original application handler ( helloHandler ).

Show me the code

A simple middleware used in this post can be found here on github repo.

Share on

{Neeraj:Sidhaye}
WRITTEN BY
Neeraj Sidhaye
I Aspire to Inspire before I Expire!