Gin middleware implementation process and usage details
I. Background
When we use the Gin framework for Web development, we almost always encounter the login blocking scenario. For example, some interfaces must be accessed after login, according to the login user's information and permissions, get their own data, on the contrary, no login is directly denied access. So how do we do these login intercepts? Students who have done Java spring development or other framework development know that this scenario is generally set up a login interceptor, the global unity in the interceptor login permission verification processing, meet the login conditions, release the request to the business function, otherwise deny access. In this way, it is convenient for us to do unified management, and there is no need for each business function to repeat a set of the same interception logic.
In Gin, middleware and business processing functions are of the same type, both of which are functions. The function signature is func(c * gins.context){}, and the Egine object of gin puts these functions func(c * gins.context){} into a slice array and executes them in order by default. As long as your function func(c * gin.context){}, we can use this function as a middleware function for Gin.
The service functions are the last element of the handlers slice array, so in front of the service functions we can add a number of functions, which we call middleware functions.
We can call c.Next() to execute the next middleware function/subsequent function, or we can call c.abeort () to terminate the subsequent middleware execution.
Using c.Next(), looking at the source code we see this structure:
C.ext () simply moves this handlers[array of function chains] one element down, which is to execute a call to the next middleware function.
The *Context received by each function can end the response to the HTTP request at any time, and can also obtain the HTTP request parameters, thus achieving the role of middleware intercept processing.
Ii. Execution flow chart
1. General flow chart
If the Abort(), Next() functions are not called, the execution is done in the order used by the middleware.
2. Use Abort()
Call Abort() to terminate subsequent middleware execution and respond directly to HTTP content. Default Abort(), the response status code is 200, and there is no payload response content. In addition to Abort(), there are several functions based on Abort() that allow us to change the response status code such as 403, content, and so on.
Source test code:
package main import ( "fmt" "github.com/gin-gonic/gin" "net/http" ) func A(c *gin.Context) { fmt.Println("A1") c.Abort() } func B(c *gin.Context) {fmt.Println("B1")} func main() {c := gin.Default() // Using two middleware functions, execute A,B c.se (A, B) c.et ("/hello", func(c *gin.Context) {fmt.Println(" service function ") C.son (http.StatusOK, gin.H{"message": "hello world", }) }) c.Run() }
Run result: Abort() is encountered when running A middleware, and subsequent middleware or business functions will not be executed
3. Use of Next();
Source test code:
package main import ( "fmt" "github.com/gin-gonic/gin" "net/http" ) func A(c *gin.Context) { fmt.Println("A1") c.Next() fmt.Println("A1-end")} func B(c *gin.Context) {fmt.Println("B1")} func main() {c := gin.Default() // Using two middleware functions, Execute A,B c.se (A, B) c.et ("/hello", func(c *gin.Context) {fmt.Println(" business function ") c.son (http.StatusOK,) in the order defined gin.H{ "message": "hello world", }) }) c.Run() }
Running result:
First run to A middleware, A calls c.Next() then continue to call the next middleware, so first print A1, to B1, and finally to the business function, output "business function ". Finally, after the execution of the business function, return to the B middleware of the previous layer. After the B middleware is executed, return to A. At this time, c.Next() in A has been all executed, and finally output A1-end, and finally respond to the HTTP request.
So if you want to do the final response interception, then the first middleware needs to add the final response logic after c.Next() in the way of c.Next(). For example, you can change the status code, or add headers, or delete headers, and so on.
The above is Gin middleware implementation process and usage detailed content, more information about Gin middleware implementation please pay attention to other related articles Script Home!
Related article
-
How to deploy and guard golang applications using systemd
systemd is a popular daemon manager that can easily manage the start, stop, restart and other operations of the service, so that our applications always stay online, this article describes how to use systemd to deploy and guard golang applications, interested friends take a look at it2023-10-10 -
golang chan delivers detailed performance overhead for data
This article mainly introduces in detail the overhead generated by chan in Golang when receiving and sending data because of "replication", the example code in the article explains in detail, interested partners can understand2024-01-01 -
This article understands the use of conditional statements in Go language
This article mainly introduces the use of five commonly used conditional statements in the Go language. This article gives you a very detailed introduction, which has certain reference value for your study or work. Friends in need can refer to it2022-04-04 -
Go type safe HTTP request example details
This article mainly introduces the Go type of safe HTTP request example detailed explanation, friends in need can use for reference, I hope to be helpful, I wish you a lot of progress, early promotion and pay rise2022-06-06 -
Go monolithic service development Best practices summary
This article mainly introduces the go monomer service development best practices, through this article to share with you in detail how to use Go-Zero to quickly develop a monomer service with multiple modules, need friends can refer to2022-04-04 -
A comprehensive introduction to the generics of Go 1.18's new features
This article tries to make Go's generics easier to understand for people who have not been exposed to generic programming, so the writing can be a little verbose. But trust me, after reading this article you will have a very thorough understanding of Go generics2023-03-03 -
Golang Cron timed task implementation example
This article mainly introduces the implementation of the Golang Cron timing task example, the article through the example code introduction is very detailed, for everyone's study or work has a certain reference learning value, the need of friends below with the small series to learn together2020-05-05 -
Go http client connection pool is not multiplexed
This article mainly introduces the Go http client connection pool does not reuse the problem, the article through the example code introduction is very detailed, for everyone's study or work has a certain reference learning value, the need of friends below with the small series to learn it2021-01-01 -
Analysis of parallel assignment in golang
This article mainly introduces the relevant information about the parallel assignment in golang. The article introduces it in great detail through the example code. It has certain reference value for everyone to learn or use golang2018-08-08 -
go compress and decompress zip file source code example
This article mainly introduces the go compression and decompression zip file source code example, there is a need for friends can use for reference, I hope to be helpful, I wish you a lot of progress, early promotion and pay rise2022-07-07
Latest comments