Gin framework Series 03: a change in posture understand middleware

What is Middleware

Middleware, English translation middleware, as the name suggests, in the middle of the object, then who in the middle of it? Originally, the client can request directly to the server interface.

file

Now, butt in the middleware, it can intercept request before it reaches the interface, to do some special treatment, such as logging, fault handling. This is today to tell middleware, then it Gin framework is how to use it?

file

How to use middleware

We look at every ginmethod will tone Default, there is a method variable engine, which Usethe Loggerand Recoverytwo functions, these two functions is the ginframework of logs and troubleshooting middleware.

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

It is very clear, the use of middleware is to call the Usemethod on the line chanting, the problem is now in addition to these two middleware can go to Usewho? Not as good as we first write a middleware it, it is easier to understand.

Write a middleware

Write Shane, do pay attention to product MVP, Nazan write a simple loop, the output intercept the request 平也最帅log, the product can be delivered.

file

First official look before they write Loggerand Recoveryhow to write, like painted gourd dipper.

func Logger() HandlerFunc {
	return LoggerWithConfig(LoggerConfig{})
}

func Recovery() HandlerFunc {
	return RecoveryWithWriter(DefaultErrorWriter)
}

It turned out that both functions return a HandlerFunctype, then we imitate write a function just fine.

func PingYe() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.String(200, "平也最帅")
	}
}

Very simple, finished, and can mainfunction in Useit.

func main() {
	r := gin.Default()
	r.Use(PingYe())
	r.Run()
}

The project up and running, access localhsot:8080look at the awesome success of rendering data.

file

Is it too simple? This muddle? I can hit ten ah! ?

file

It seems I'm going to learn all his life to you.

Further reading

Next

If we define two middleware, a flat is also the most handsome, the other is where the most handsome.

func PingYe() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.String(200, "平也最帅")
	}
}

func Where() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.String(200, "在全宇宙")
	}
}

In the order they were registered to frame them, this time we guess it will first output 平也最帅re-export 在全宇宙, right? Yes, yes indeed.

func main() {
	r := gin.Default()
	r.Use(PingYe(), Where())
	r.Run()
}

But if I do not change the order of registration under the premise of how exchange about the order, the first output 在全宇宙and then output 平也最帅it? It uses the famous Nextmethod. Its role is to perform the following middleware, execution finished and then come back to continue with the next logical. I remember it was called middleware oh ~

func PingYe() gin.HandlerFunc {
  return func(c *gin.Context) {
    c.Next()
    c.String(200, "平也最帅")
  }
}

file

Abort

Of course, in addition to providing Nextmethods, but in theory, should have a right to interrupt the operation, after all, to get authorization verification middleware to do so, after verification fails still hope to block the request. So, Abortit is that the way we're looking for. Take the above example, the 平也最帅call to the next line of Abortthe method, Wherethe middleware is no longer in force, so the flat is also only a mere handsome.

func PingYe() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.String(200, "平也最帅")
		c.Abort()
	}
}

file

Local middleware

I just talked middleware will take effect on all routes, some do not need to add middleware routing scenario will not be able to adapt. So, we need to have the ability to be able to add middleware as a local.

file

Let alone implement an interface to add middleware, so come to define two interfaces knowand unknown, representing the level of understanding and also do not know the two scenes, Recognizing after that level is the most handsome of the whole universe, so to tie the middle pieces, do not know even if the. Implementation is very simple, to the back of the routing parameters plus middleware hard enough.

r.GET("know", PingYe(), Where())
r.GET("unknown", func(c *gin.Context) {
  c.String(200, "???")
})

In addition to adding middleware for an interface, you can also add a set of interfaces, call the same Usemethod can be.

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")
  })
}

HTTP Basic Authentication

Basic Authentication, also known as BasicAuth, add a basic authentication interface, and you will provide a user name and password when you access interface.

file

For the browser user, for the user experience will automatically pop-up login box, and in other scenes are not, then enter the account password where is it? In fact, it is transmitted through the header information, the header information there is a fixed format to represent the basic authentication.

Authorization: Basic <凭证>

Document moiety is a username and password combination of base64encoding, both spliced colon. However, geese, ginframework BaseAuthmiddleware already prepared everything, it can be just a few lines of code will be able to resolve basic authentication information.

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, user+"已登录成功")
	})
	r.Run()
}

The part of the code example some students may not understand, such as BasicAuthmethod parameters, because the basic authentication requires username and password for it, so we can take advantage of gin.Accountsconvenient configurations that you need to verify the account password, gin.Accountsit is a map type, key behalf of the user name, password values represent, of course, you can set more than one key-value pair, set your own based on your preferences.

Code also appeared c.MustGetmethods, the role of this method is that we must get to a parameter, did not get any panic, to take what is it? That is gin.AuthUserKey, the official explanation is basic authentication credentials in the user's cookiename.

// AuthUserKey is the cookie name for user credential in basic auth.
const AuthUserKey = "user"

Go examples of open source language library project " golang-examples " Welcome star ~

https://github.com/pingyeaa/golang-examples

Thank you for watching, if that article to help you, welcome attention to the public number "level is also" focusing Go language and technical principles. follow me

Guess you like

Origin www.cnblogs.com/pingyeaa/p/12667536.html