The gin framework in Go language [GET/POST] request parameters to receive and pass values (5)

The get and post in Gin refer to different methods in HTTP requests. When the client initiates an HTTP GET request to the server, the server will return the corresponding resources to the client; when the client initiates an HTTP POST request to the server, the server will process the data sent by the client as part of the request.

 

Gin is a web framework written in Go language, which supports HTTP GET and HTTP Post requests. Typically, HTTP GET is used to request data or resources, while HTTP POST is used to submit data to the server, such as a web form.

In Gin, we can use the GET method to declare a handler for an HTTP Get request, such as the following code:

package main

import (
    "github.com/gin-gonic/gin"
)

func main() {
    r := gin.Default()

    r.GET("/hello", func(c *gin.Context) {
        c.String(200, "Hello, Gin!")
    })

    r.Run() // 启动服务器
}

In the above example, we declare a handler for the HTTP Get request, and its routing path is "/hello". When the client sends a GET request for "/hello" to the server, this handler will be executed.

The Get request here is a case without parameters. In actual business, there may be diverse requests. Therefore, let us add here that there is another GET request similar to (localhost:8080/login?username= "xiaomi"&password="123456") When accessing a url link like this, how do you get the value in the routing?

That is, how does the server receive the parameters on the URL link?

In Gin, you can use the Param or Query method to get the query parameters in the URL. The Param method can get the path parameters, and the Query method can get the query parameters.

For example:

package main

import (
    "github.com/gin-gonic/gin"
)

func main() {
    r := gin.Default()

    // /book/123  动态路由
    r.GET("/book/:id", func(c *gin.Context) {
        id := c.Param("id")
        c.String(200, "Book ID is "+id)
    })

    // /search?query=gin  路由携带参数
    r.GET("/search", func(c *gin.Context) {
        query := c.Query("query")
        c.String(200, "Search query is "+query)
    })

    r.Run()
}

In the above example, we use the Param method to obtain the path parameter, specify the parameter name through ":id" , use c.Param("id") in the processor function to obtain the parameter value , and finally return it to the client. We also use the Query method to obtain the query parameters, use "c.Query("query")" to obtain the parameter value named "query" , and finally return it to the client. 

What we need to note here is that the first letters of the Param() and Query() methods are all capital letters . At the same time, these two methods are

[ c *gin.Context ] Built-in method of c object.

In addition, we can also use the POST method to declare a handler for HTTP Post requests, such as the following code:

package main

import (
    "github.com/gin-gonic/gin"
)

func main() {
    r := gin.Default()

    r.POST("/login", func(c *gin.Context) {
        username := c.PostForm("username")
        password := c.PostForm("password")

        // 进行用户验证操作

        c.String(200, "登录成功!")
    })

    r.Run() // 启动服务器
}

In the above example, we declare a handler for HTTP Post requests, and its routing path is "/login". When the client sends a POST request for "/login" to the server, this handler will be executed. In the processor, we can obtain the form data submitted by the client through the c.PostForm method and process it accordingly.

Supplementary explanation, when the post request simulates a login or registration request, it is the data of the structure. We need to obtain the request parameters from the request c.request.body and return it to the client (regardless of whether it is successful or not). Such status must be handled in the same way to be consistent with the actual development environment). The following cases:

package main

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

// 定义一个 userinfo 表单结构体对象
type UserInfo struct {
	UserName string `json:"username" form:"username"`
	Password string `json:"password" form:"password"`
	Age      string `json:"age" form:"age"`
}

func main() {
	// 定义一个路由引擎对象
	router := gin.Default()

	// 加载 渲染模板 全局
	router.LoadHTMLGlob("*templates/**/*")

	// 路由 get请求后 返回数据到模板渲染
	router.GET("/", func(c *gin.Context) {
		// c.JSON(200, gin.H{
		// 	"message": "Hello, world!",
		// })
		c.HTML(http.StatusOK, "login/index.html", gin.H{
			"title":   "登录页面",
			"content": "这是一个",
		})
	})

	// get请求 c.Query()方法获取url【/login?usename="小红"&password="123123"】 上的参数值:
	router.GET("/login", func(c *gin.Context) {
		username := c.Query("username")
		password := c.Query("password")
		// c.DefaultQuery()方法可以设定默认值,触发的条件是如果获取不到url上这个age参数的值,就返回约定的默认值18
		age := c.DefaultQuery("age", "18") // 18 is default value for login form auth form auth

		// 获取到url传入的参数跳转到 新的页面 首页 渲染到、default/index.html
		c.HTML(http.StatusOK, "default/index.html", gin.H{
			"name":     username,
			"password": password,
			"age":      age,
		})
	})

	// GET / 动态路由链接  /logout/1233 其中的1233是这个url上的动态变量值,默认取值就是uid
	router.GET("/logout/:uid", func(c *gin.Context) {
		uid := c.Param("uid") // 获取动态路由url链接上的变量值 /logout/1233 这里的值为1233
		status := "登出成功"
		// c.String(http.StatusOK, "uid=%v 状态=%v", uid, status)
		c.JSON(http.StatusOK, gin.H{
			"status": status,
			"uid":    uid,
		})
	})

	// 赋值结构体
	router.GET("/register", func(ctx *gin.Context) {
		// ctx.String(http.StatusOK,"成功!!")
		ctx.HTML(http.StatusOK, "register/index.html", gin.H{})

	})
	router.POST("/doAdd", func(ctx *gin.Context) {
		// post请求通过 c.PostForm()方法获取表单数据
		// username := ctx.PostForm("username")
		// password := ctx.PostForm("password")
		// age := ctx.DefaultPostForm("age", "20")
		// ctx.JSON(http.StatusOK, gin.H{
		// 	"username": username,
		// 	"password": password,
		// 	"age":      age,
		// })

		// post请求 通过  ctx.ShouldBind(&userInfo) 方法  结构体赋值
		userInfo := &UserInfo{}
		if err := ctx.ShouldBind(&userInfo); err == nil {
			ctx.JSON(http.StatusOK, gin.H{
				"userInfn": userInfo,
			})
		} else {
			ctx.JSON(http.StatusBadRequest, gin.H{
				"error": err.Error(),
			})
		}
	})

	router.Run(":8080")
}

Among them, the html page default, login, register folder, etc. only show the image file structure;

{
   
   {define "register/index.html"}}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>注册页面</title>
</head>
    <h1>{
   
   {"注册页面"}}</h1>
    <form action="/doAdd" method="post">
        用户名 <input type="text" name="username" id="username">
        密码 <input type="text" name="password" id="password">
        年龄  <input type="text" name="age" id="age">
        <input type="submit" value="提交">
    </form>
</body>
</html>
{
   
   {end}}

We can use  ShouldBind methods to bind the data in the request to the structure object. Assuming that our request body is data in JSON format, we can bind it to the structure object. The steps are as follows:

1. Define the structure

type User struct {
    Name     string `json:"name"`
    Age      int    `json:"age"`
    Password string `json:"password"`
}

2.  ShouldBind How to use

func handlePostRequest(c *gin.Context) {
    var user User
    if err := c.ShouldBind(&user); err != nil {
        c.AbortWithError(http.StatusBadRequest, err)
        return
    }
    c.JSON(http.StatusOK, gin.H{
        "name":     user.Name,
        "age":      user.Age,
        "password": user.Password,
    })
}

In the above example, a structure is defined  Userto represent the data format in the request body. Then use  ShouldBind the method to bind the request body data to  User the object and determine whether the binding fails.

ShouldBind The method can automatically perform different types of binding according to different Content-Types, and supports four data types: JSON, XML, and Form. It should be noted that  Bind unlike using methods, if the using  ShouldBind method fails, an exception will not be thrown, but an error object will be returned. If you need to throw an exception, you can use  the ShouldBindJSON or  ShouldBindXML method.

In addition, you can use  ShouldBindUri methods to bind the data in the URL to the structure object. This method is  ShouldBind used similarly to method. for example:

func handleGetRequest(c *gin.Context) {
    var user User
    if err := c.ShouldBindUri(&user); err != nil {
        c.AbortWithError(http.StatusBadRequest, err)
        return
    }
    c.JSON(http.StatusOK, gin.H{
        "name": user.Name,
        "age":  user.Age,
    })
}

In the above example, we use  ShouldBindUri a method to bind the data in the URL into  User an object, and then return  User part of the data in the object to the client.

Here is the final HTML code for simple registration. You can go to the resource to download it.

The above are the basic steps for using the Gin framework to perform post and get requests. By learning these basic knowledge, you can further learn how to use advanced functions such as routing jumps to meet more practical needs. 

Guess you like

Origin blog.csdn.net/A_LWIEUI_Learn/article/details/131221914