The article was first publishedISLAND

Middleware is an important concept in Golang, similar to interceptors in Java. Take a look at the use of middleware code through gin source code.

🎮 Middleware usage

We return to the SetupRouter method in initRouter.

router := gin.Default()
Copy the code

Our project starts with this line of code, so let’s see what this line of code does. Open the Default source code,

func Default(a) *Engine {
	debugPrintWARNINGDefault()
	engine := New()
	engine.Use(Logger(), Recovery())
	return engine
}
Copy the code

In the source code, an engine is first created, and then Logger() and Recovery() are passed in through the Use method, while Logger and Recovery are two middleware.

Logger records logs, and Recovery handles errors of 500 when painc is present

After reviewing the source code, we know how to use middleware.

📝 Customize a middleware

The middleware needs to return the gin.HandlerFunc function, so define the return function.

And the middleware has a Next function, which will form a middleware chain among the many middleware we define, and the Next function will execute the following middleware. The Next function is executed before the request, and the Next function is executed after the request.

Let’s create our own Logger log and create a new Middleware folder with Logger.go for our custom log display.

package middleware

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"time"
)

func Logger(a) gin.HandlerFunc {
	return func(context *gin.Context) {
		host := context.Request.Host
		url := context.Request.URL
		method := context.Request.Method
		fmt.Printf("%s::%s \t %s \t %s ", time.Now().Format("The 2006-01-02 15:04:05"), host, url, method)
		context.Next()
		fmt.Println(context.Writer.Status())
	}
}
Copy the code

Global middleware

Modify the SetupRouter method in initRouter to add our custom middleware.

router := gin.New()
// Add custom Logger middleware
router.Use(middleware.Logger(), gin.Recovery())
Copy the code

At this point, restart our project, access port localhost:8080, and the console will print out our new format log.

2019-07-23 18:17:58::localhost:8080 / GET 200

Of course, the Logger middleware is used globally at this point, but we can also use it for specific routes.

Local middleware

For example, if we specify that some routes can be accessed only after login, we can implement authorization management for these routes.

We write a new Auth middleware to manage, here is not specific implementation of the middleware, will be implemented later, here is just to show.

package middleware

import "github.com/gin-gonic/gin"

func Auth(a) gin.HandlerFunc {
	return func(context *gin.Context) {
		println("Authorized")
		context.Next()
	}
}
Copy the code

We add this middleware on the route of user information modification and user information display.

userRouter.GET("/profile/", middleware.Auth(), handler.UserProfile)
userRouter.POST("/update", middleware.Auth(), handler.UpdateUserProfile)
Copy the code

When we run the project again, when we visit the user details page, the console will print out the authorized log, while accessing other pages will not appear, indicating that our middleware is successfully used.

✍ summary

Through this understanding of the middleware, the basic grasp of how to write and use middleware, for the global and local two kinds of middleware also have different use methods and use scope.

👩💻 Code of this section

Github

📰 Historical articles

Gin(I):Hello Gin(II): Routing Router Gin(III): Template TMPL Gin(IV): Form submission checksum model binding Gin(V): Connection to MySQL Gin(VI): File upload Gin(VII): Use and definition of middleware Gin(8): Use of cookies

Personal public account

Recently, I have just applied for a public account. In the future, the article will be sent synchronously. Welcome your attention