Detailed explanation of basic gin routing of golang microservice framework

Time:2021-12-29
catalogue
  • summary
  • 1. Basic routing
  • 2. Routing parameters
    • Get all parameters of URL path
    • Get URL path single parameter
    • Gets the parameter specified in the URL
    • Gets the value of the parameter that specifies the default value

summary

Routing is to customize the URL address and execute the specified function. A good routing definition can have a good effect on SEO.

1. Basic routing

The gin framework encapsulates the HTTP library and provides HTTP request methods such as get, post, put, delete, patch, head and options.

userouter.method()To bind routes

?
1
func (group *RouterGroup) METHOD(relativePath string, handlers ...HandlerFunc) IRoutes
?
1
2
3
4
5
6
7
8
9
router := gin.Default()
router. Get ("/ get", func (c * gin. Context) {c.json (200, gin. H {"message": "get method"})})
router. Post ("/ post", func (c * gin. Context) {c.json (200, gin. H {"message": "post method"})})
router. Put ("/ put", func (c * gin. Context) {c.json (200, gin. H {"message": "put method"})})
router.DELETE("/delete", func(c *gin.Context) { c.JSON(200, gin.H{"message": "delete"}) })
router.PATCH("/patch", func(c *gin.Context) { c.JSON(200, gin.H{"message": "patch"}) })
router.HEAD("/head", func(c *gin.Context) { c.JSON(200, gin.H{"message": "head"}) })
router.OPTIONS("/options", func(c *gin.Context) { c.JSON(200, gin.H{"message": "options"}) })
router. Run (": 9999") // specify the port @ localhost: 9999

2. Routing parameters

Get all parameters of URL path

With / as the separator, each parameter takes “:” as the parameter to represent the dynamic variable, which will be automatically bound to the corresponding parameter of the route
Routing rule: [] means no matching is required

For example:

http://localhost:8080/user/ Li Si / 20 / Beijing / male“ http://localhost:8080/user/:name/:age/:address/:sex ”

In the above link, you can

Use / user /: name /: age /: Address /: sex to match Li Si, 20, Beijing and men respectively

?
1
c.Params("key")
?
1
2
3
4
5
6
// http://localhost:8080/user/ Li Si / 20 / Beijing / male
router.GET("/user/:name/:age/:address/:sex", func(c *gin.Context) {
    //Print all parameters in URL
    //"[{name Li Si} {age 20} {address Beijing} {sex male}] \ n"
    c.JSON(http.StatusOK, fmt.Sprintln(c.Params))
})

Note: however, it will not match / user / or / user

visit: http://localhost:8080/user/ Li Si / 20 / Beijing / male

result:

“[{name Li Si} {age 20} {address Beijing} {sex male}] \ n”

Get URL path single parameter

Use gin The param (key) method of the context object obtains the value of a key. The method declaration is as follows:

?
1
2
3
4
5
6
7
8
//http://localhost:8080/login/15949629528/123456
router.GET("/login/:name/:password", func(c *gin.Context) {
  c.JSON(http.StatusOK, gin.H{
    //{ name: "15949629528", password: "123456" }
    "name":     c.Param("name"),
    "password": c.Param("password"),
  })
})

visit: http://localhost:8080/login/15949629528/123456

result:

{ name: “15949629528”, password: “123456” }

Gets the parameter specified in the URL

Get and post requests

The path value in the get URL is different from the get parameter

For example:

http://localhost:8080/login?name= Zhang San & password = 123456

You can use the following method to obtain the values of the request parameters name and password.

?
1
2
//Returns the value of the key in the URL
func (c *Context) Query(key string) string
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//Get request
router.GET("/login", func(c *gin.Context) {
  //{Name: "Zhang San", password: "123456"}
  c.JSON(http.StatusOK, gin.H{
    "name":     c.Query("name"),
    "password": c.Query("password"),
  })
})
 
//Post request
router.POST("/login", func(c *gin.Context) {
    //{"name": "Zhang San", "password": "123456"}
    c.JSON(http.StatusOK, gin.H{
        "name":     c.Query("name"),
        "password": c.Query("password"),
    })
})

visit: http://localhost:8080/login?name= Zhang San & password = 123456

The output is as follows:

{Name: “Zhang San”, password: “123456”}

Gets the value of the parameter that specifies the default value

Receive} get, post requests with default values

Of course, the gin framework also thinks of this point,gin.Context.DefaultQuery()Method, which allows you to specify the received parameter name and the default value set when the parameter value is not received. The declaration is as follows:

?
1
func (c *Context) DefaultQuery(key, defaultValue string) string

The default value will take effect only if the request does not carry a key. In other cases, the default value does not take effect. Even if the value of the key in the URL is empty, the default value will not be enabled, and the obtained value is empty.

Note that this is to get the parameter value in the URL

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//Get request
router.GET("/user", func(c *gin.Context) {
  //{Name: "Zhang San", password: "123456"}
  c.JSON(http.StatusOK, gin.H{
    "Name": C. defaultquery ("name", "default Zhang San"),
    "Password": C. defaultquery ("password", "default password"),
  })
})
//Post request
router.POST("/user", func(c *gin.Context) {
//{"name": "Zhang San", "password": "default password"}
    c.JSON(http.StatusOK, gin.H{
      "Name": C. defaultquery ("name", "default Zhang San"),
      "Password": C. defaultquery ("password", "default password"),
    })
})

visit: http://localhost:8080/user?password=

The output is as follows:

{Name: “default Zhang San”, password: “default password”}

The above is the detailed explanation of the use of gin basic routing in golang microservice framework. For more information about gin basic routing, please pay attention to other related articles in developeppaper!

Recommended Today

Big data Hadoop — spark SQL + spark streaming

catalogue 1、 Spark SQL overview 2、 Sparksql version 1) Evolution of sparksql 2) Comparison between shark and sparksql 3)SparkSession 3、 RDD, dataframes and dataset 1) Relationship between the three 1)RDD 1. Core concept 2. RDD simple operation 3、RDD API 1)Transformation 2)Action 4. Actual operation 2)DataFrames 1. DSL style syntax operation 1) Dataframe creation 2. SQL […]