What is middleware
Middleware, as its name suggests, is something in the middle, and who in the middle? Originally, the client could request directly to the server interface.
Middleware now has a foot in the door, intercepting requests before they reach the interface and doing special tasks such as logging and troubleshooting. This is middleware today, so how is it used in the Gin framework?
How to use middleware
Let’s take a look at the method Default that gin must call every time. There is a variable engine in the method, which uses two functions, Logger and Recovery. These two functions are the logging and fault processing middleware of GIN framework.
func Default() *Engine {
debugPrintWARNINGDefault()
engine := New()
engine.Use(Logger(), Recovery())
return engine
}Copy the code
Then it is clear that to Use middleware is to call the Use method. The question is who else can Use middleware except these two? How about we write a middleware first, so it’s easier to understand.
Write a middleware
Write what, making products is about MVP, so let’s write the simplest closed loop, intercept the request and output the most beautiful and flat log, and the product can be delivered.
Study the official Logger and Recovery before you write is how to write, is like a gourd ladle.
func Logger() HandlerFunc {
return LoggerWithConfig(LoggerConfig{})
}
func Recovery() HandlerFunc {
return RecoveryWithWriter(DefaultErrorWriter)
}Copy the code
Both of these functions return HandlerFunc, so we should write a function that mimicry HandlerFunc.
Func PingYe() gin.HandlerFunc {return func(c *gin.Context) {c.string (200, "PingYe is the best ")}}Copy the code
That’s easy. Once you’re done, you can Use it in your main function.
func main() {
r := gin.Default()
r.Use(PingYe())
r.Run()
}Copy the code
Run the project and go to localhSOt :8080.
Is it too easy? That’s a cross, right? I could hit ten more! ?
Looks like I’m handing you everything I’ve learned.
read
Next
Suppose we define two middleware, one is flat and the most handsome, the other is where the most handsome.
func PingYe() gin.HandlerFunc { return func(c *gin.Context) { c.String(200, }} func Where() HandlerFunc {return func(c *gin.Context) {c.tring (200, "in the whole universe ")}}Copy the code
Register them separately in the frame in order, at this point we guess it will output the flat and most handsome first and then the whole universe, right? Yes, it is.
func main() {
r := gin.Default()
r.Use(PingYe(), Where())
r.Run()
}Copy the code
However, if I do not change the registration order under the premise, how to switch the order, first output in the whole universe and then output flat is also the most handsome? This uses the famous Next method. What it does is execute the next piece of middleware and then come back to execute the next piece of logic. Remember to call in middleware oh ~
Func PingYe() gin.HandlerFunc {return func(c *gin.Context) {c.next () c.tring (200, "PingYe is the best ")}}Copy the code
Abort
Of course, in addition to providing the Next method, there should be an interrupt operation in theory, after all, with middleware for authorization authentication, you still want to block the request if authentication fails. So Abort is the method that we’re looking for. In the example above, after the Abort method is called on the next line, the Where middleware is no longer in effect, so the Where middleware is simply handsome.
Func PingYe() gin.HandlerFunc {return func(c *gin.Context) {c.tring (200, "PingYe ") c.aport ()}}Copy the code
Local middleware
The middleware I just described will work on all routes, and some routing scenarios that do not require middleware will not be able to adapt. Therefore, we need the ability to add middleware for local areas.
We first add middleware to an interface separately, so we have to define two interfaces know and unknown, which respectively represent the two scenarios of knowing flat and not knowing it. Considering that flat is also the most handsome in the universe only after knowing it, we need to tie middleware, and forget not knowing it. The implementation is very simple, just add middleware to the parameters behind the route as much as possible.
r.GET("know", PingYe(), Where())
r.GET("unknown", func(c *gin.Context) {
c.String(200, "???")
})Copy the code
In addition to adding middleware for an interface, you can also add middleware for a set of interfaces, again by calling the Use method.
v1 := r.Group("v1")
v1.Use(PingYe(), Where())
{
v1.GET("/know", func(c *gin.Context) {
c.String(200, "know")
})
v1.GET("/unknown", func(c *gin.Context) {
c.String(200, "unknown")
})
}Copy the code
HTTP Basic Authentication
Basic authentication, also known as BasicAuth, is an interface with basic authentication that allows you to provide a username and password when accessing the interface.
For browser users, the login box will automatically pop up for user experience, but it is not available in other scenarios. Where can I enter the account and password? In fact, it is transmitted through the header, which has a fixed format to represent the basic authentication.
Authorization: BasicCopy the code
The credential part is base64 encoding of the username and password, concatenated with colons. However, the Gin framework’s BaseAuth middleware is already in place and can parse basic authentication information in just a few lines of code.
func main() { r := gin.Default() r.Use(gin.BasicAuth(gin.Accounts{ "pingye": "123", })) r.GET("/secrets", func(c *gin.Context) { user := c.MustGet(gin.AuthUserKey).(string) c.String(200, }) r.run ()}Copy the code
Some of the codes in the example may be confusing to some students, such as the parameters in the BasicAuth method. Because basic authentication requires an account and password, we can easily configure the account password to be verified by using gin.Accounts is a map type, and the key represents the user name. The value represents the password, of course, you can set more than one key-value pair, as you like.
C. mustget (); panic (); panic (); Gin.AuthUserKey is the cookie name of the user’s credentials in basic authentication.
// AuthUserKey is the cookie name for user credential in basic auth.
const AuthUserKey = "user"Copy the code
Go library examples open source project “Golang-examples” welcome to Star ~
https://github.com/pingyeaa/golang-examplesCopy the code
Thank you for watching, if you feel the article is helpful to you, welcome to pay attention to the public account “Ping ye”, focus on Go language and technology principle.
If you find this article helpful, give me a thumbs up