Pada bab ini kita akan membuat middleware. Kasus yang digunakan adalah handling auth.
Buat file baru libraries/api/middleware.go
packageapi// Middleware is a function designed to run some code before and/or after// another Handler. It is designed to remove boilerplate or other concerns not// direct to any given Handler.typeMiddlewarefunc(Handler)Handler// wrapMiddleware creates a new handler by wrapping middleware around a final// handler. The middlewares' Handlers will be executed by requests in the order// they are provided.funcwrapMiddleware(mw[]Middleware,handlerHandler)Handler{// Loop backwards through the middleware invoking each one. Replace the// handler with the new wrapped handler. Looping backwards ensures that the// first middleware of the slice is the first to be executed by requests.fori:=len(mw)-1;i>=0;i--{h:=mw[i]ifh!=nil{handler=h(handler)}}returnhandler}
list semua middleware yang diperlukan pada routing/route.go
Tambahkan field middleware di type App libraries/api/app.go
Buat middleware untuk handling authorization ( middlewares/auth.go )