Gin框架参数绑定

Gin框架参数绑定

参数绑定

为了能够更方便的获取请求相关参数,提高开发效率,我们可以基于请求的Content-Type识别请求数据类型并利用反射机制自动提取请求中QueryStringform表单JSONXML等参数到结构体中。 下面的示例代码演示了.ShouldBind()强大的功能,它能够基于请求自动提取JSONform表单QueryString类型的数据,并把值绑定到指定的结构体对象。

一、querystring方式

package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)

type UserInfo struct {
	Username string `form:"username" json:"username"`
	Password string `form:"password" json:"password"`
}

func main() {

	r := gin.Default()
	// querystring方式
	r.GET("/user", func(c *gin.Context) {
		//username := c.Query("username")
		//password := c.Query("password")
		//user := userInfo{
		//	Username: username,
		//	Password: password,
		//}
		// 数据绑定
		var userBind UserInfo // 声明变量
		
        // 通过反射获取数据
		err := c.ShouldBind(&userBind)
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{
				"error": err.Error(),
			})
		} else {
			fmt.Printf("%#v\n", userBind)
		}

		c.JSON(http.StatusOK, userBind)

	})
	r.Run(":9999")
}

image-20211117085340288

二、form-data方式

package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)

type UserInfo struct {
	Username string `form:"username" json:"username"`
	Password string `form:"password" json:"password"`
}

func main() {

	r := gin.Default()
	// form方式
	r.POST("/user", func(c *gin.Context) {

		// 数据绑定
		var userBind UserInfo // 声明变量

		err := c.ShouldBind(&userBind)
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{
				"error": err.Error(),
			})
		} else {
			fmt.Printf("%#v\n", userBind)
		}

		c.JSON(http.StatusOK, userBind)

	})
	r.Run(":9999")
}

image-20211117085920335

三、json方式

package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)

type UserInfo struct {
	Username string `form:"username" json:"username"`
	Password string `form:"password" json:"password"`
}

func main() {

	r := gin.Default()
	// json方式
	r.POST("/json", func(c *gin.Context) {

		// 数据绑定
		var userBind UserInfo // 声明变量

		err := c.ShouldBind(&userBind)
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{
				"error": err.Error(),
			})
		} else {
			fmt.Printf("%#v\n", userBind)
		}

		c.JSON(http.StatusOK, userBind)

	})
	r.Run(":9999")
}

image-20211117090036145

原文地址:https://www.cnblogs.com/randysun/p/15626628.html