Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use Middleware

Shulou Source: shulou.com Published: 2022-06-03 05:37:05 10月03日 Update

This article mainly explains "how to use middleware". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's ideas to study and learn "how to use middleware".

Middle ware

Use the scene:

Auth authority authentication cross-domain other transactions that need to be processed before business processing

Let's continue with the last phase of the project.

Check the catalogue.

➜go-gin-test tree-L 3

.

├── go.mod

├── go.sum

├── hello

├── mian.go

└── routerex

└── router.go

Create a new mid directory under the routerex directory and a new mid.go file under the mid directory

First of all, we define a middleware. Its function is to verify whether the request is legal after the request arrives at the service, but before the business is processed.

Edit mid.go

Package mid

Import (

"github.com/gin-gonic/gin"

)

Func midAuth (c * gin.Context) {

/ / obtain the requested ip address

Ip: = c.ClientIP ()

/ / if the source of the request address is incorrect, prevent the request from continuing

If ip! = "baidu.com" {

Println ("incorrect ip address") c.Abort () return

}

/ / process the request

C.Next ()

}

Edit router.go

Package routerex

Import (

"example.com/m/v2/routerex/mid"

"github.com/gin-gonic/gin"

)

Func InitRouter (g * gin.Engine) {

G1: = g.Group ("G1")

/ / Middleware

G1.Use (mid.MidAuth)

G1.GET ("/ hello1", func (c * gin.Context) {

C.JSON (200, gin.H {

"msg": "Hello G1"

})

})

G2: = g.Group ("G2")

G2.GET ("/ hello2", func (c * gin.Context) {

C.JSON (200, gin.H {

"msg": "Hello G2"

})

})

}

Execute go build-o hello to compile to an executable file

➜go-gin-test go build-o hello

➜go-gin-test ls

Go.mod go.sum hello mian.go

Execute. / hello to get our service running

Open a browser to access http://localhost:8080/g1/hello1

Image.png [GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.

[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.

-using env: export GIN_MODE=release

-using code: gin.SetMode (gin.ReleaseMode)

[GIN-debug] GET / g1/hello1-- > example.com/m/v2/routerex.InitRouter.func1 (4 handlers)

[GIN-debug] GET / g2/hello2-- > example.com/m/v2/routerex.InitRouter.func2 (3 handlers)

[GIN-debug] Environment variable PORT is undefined. Using port: 8080 by default

[GIN-debug] Listening and serving HTTP on: 8080

Incorrect ip address

[GIN] 2021-04-06-17:00:38 | 200 | 61.658 μ s |:: 1 | GET "/ g1/hello1"

You can see that there is no output on our browser.

But in the background log, we saw that the ip address we printed in the code was incorrect.

Through this way of thinking, we can achieve the requirements of many business or scenarios.

The following code is a general cross-domain middleware

Func midCors (c * gin.Context) {

C.Header ("Access-Control-Allow-Origin", c.Request.Header.Get ("Origin"))

C.Header ("Access-Control-Allow-Headers", "*")

C.Header ("Access-Control-Allow-Methods", "*")

C.Header ("Access-Control-Allow-Credentials", "true")

/ / release all OPTIONS methods

If c.Request.Method = = "OPTIONS" {

C.AbortWithStatus (http.StatusNoContent)

}

/ / process the request

C.Next ()

} how POST and GET get the value Parameters in path (url path parameter) name: = c.Param ("name") Querystring parameters// this word has a default value

Firstname: = c.DefaultQuery ("firstname", "Guest") Multipart/Urlencoded Form (form) / / No default value

Message: = c.PostForm ("message")

/ / have default value

Nick: = c.DefaultPostForm ("nick", "anonymous") Map as querystring or postform parameters (Map or form) ids: = c.QueryMap ("ids")

Names: = c.PostFormMap ("names") file (file type) form, _: = c.MultipartForm ()

Files: = form.File ["upload []"] JSON// structure

J: = J {}

C.BindJSON (j)

Of course, in addition to the common ways mentioned above, gin also provides a richer way to get parameters.

Thank you for your reading, the above is the content of "how to use middleware", after the study of this article, I believe you have a deeper understanding of how to use middleware, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Tags: Middleware address directory processing files methods learning code content parameters scenarios that is ideas are in browsers forms services browsing verification legal Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia Shulou Technology Docker Shulou Tech Info Huawei