[Golang] Build A Simple Web Service part.2 — Middleware

Jen-Hsuan Hsieh (Sean)
A Layman
Published in
8 min readJan 7, 2019

--

Copy right@A layman

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/httpHandlers.

That’s see how to use it.

Install package

Open the terminal and type the following command.

go get github.com/urfave/negroni

--

--

Jen-Hsuan Hsieh (Sean)
A Layman

Frontend Developer🚀 Angular • React • Nest • Electron • Micro-frontend • Monorepo Architecture • https://daily-learning.herokuapp.com/