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.
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?
How to use middleware
We look at every gin
method will tone Default
, there is a method variable engine
, which Use
the Logger
and Recovery
two functions, these two functions is the gin
framework 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 Use
method on the line chanting, the problem is now in addition to these two middleware can go to Use
who? 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.
First official look before they write Logger
and Recovery
how 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 HandlerFunc
type, 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 main
function in Use
it.
func main() {
r := gin.Default()
r.Use(PingYe())
r.Run()
}
The project up and running, access localhsot:8080
look at the awesome success of rendering data.
Is it too simple? This muddle? I can hit ten ah! ?
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 Next
method. 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, "平也最帅")
}
}
Abort
Of course, in addition to providing Next
methods, 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, Abort
it is that the way we're looking for. Take the above example, the 平也最帅
call to the next line of Abort
the method, Where
the 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()
}
}
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.
Let alone implement an interface to add middleware, so come to define two interfaces know
and 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 Use
method 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.
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 base64
encoding, both spliced colon. However, geese, gin
framework BaseAuth
middleware 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 BasicAuth
method parameters, because the basic authentication requires username and password for it, so we can take advantage of gin.Accounts
convenient configurations that you need to verify the account password, gin.Accounts
it 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.MustGet
methods, 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 cookie
name.
// 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.