[Golang] Build A Simple Web Service part.2 — Middleware
We can put the pre-processing task like printing the log to a handler. However, it will generate much duplicate code if you use this way.
Using middleware is a choice for you.
For example, we can use the following code to measure the processing time in each handler.
It’s not a good design because it will have much duplicate code.
There aresome popular packages of the middleware like urfave/negroni and justinas/alice.
urfave/negroni
Check the description of this package from the Github. We can realize negroni can integrate with net/http very well.
Negroni is an idiomatic approach to web middleware in Go. It is tiny, non-intrusive, and encourages use of
net/http
Handlers.
That’s see how to use it.
Install package
Open the terminal and type the following command.
go get github.com/urfave/negroni