programming

08 Create Middleware Router

Understanding Middleware

HttpRouter is a library for creating an http router, it doesn’t have any other features apart from a router and this router is an implementation of the default http.Handler from Golang itself so that to create middleware we can create it ourselves as we have created in the previous Golang Web post, namely HTTP Middleware.

How to Implement

We have already tried how to implement it in the previous post. If you have never seen it, you can first read the previous post on how to create middleware on an HTTP Router. Later we will try to modify this middleware according to our needs.

First, we make it as below.

type LogMiddleware struct {
	Handler http.Handler
}

func (middleware *LogMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	fmt.Printf("Before Execute Handler %s %s\n", r.Method, r.URL)
	middleware.Handler.ServeHTTP(w, r)
	fmt.Println("After Execute Handler")
}

After that we will call this LogMiddleware on the main.go file like this.

...
...
middleware := &LogMiddleware{router}

server := http.Server{
	Handler: middleware,
	Addr:    "localhost:8080",
}
..
...

So when we run a service or program and we look at the program, for example, we access one of the endpoints.

curl --location --request POST 'http://localhost:8080/panic'

Then we look at the service log, it will be printed like this.

Before Execute Handler POST /panic
After Execute Handler

This proves that every time there is access to the router, one of the endpoints will print two sentences as above.

comments powered by Disqus