学无先后,达者为师

网站首页 编程语言 正文

shouldband绑定数据的方法详解

作者:夸父追梦@ 更新时间: 2022-05-06 编程语言

    //ShouldBind()强大的功能,它能够基于请求自动提 取
    //JSON、form 表单和 QueryString 类型的数据,并把值绑定到指定的结构体对象

//get ,post struct
func getpoststruct() {
	engine := gin.Default()
	//加载html模板  **--->代表目录
	engine.LoadHTMLGlob("templates/**/*")

	//###########################################################################
	//###########################################################################

	//路由的编写
	//ShouldBind()强大的功能,它能够基于请求自动提 取
	//JSON、form 表单和 QueryString 类型的数据,并把值绑定到指定的结构体对象
	type Useinfo struct {
		Username string `form:"username" json:"user"`
		Password string `form:"password" json:"password"`
	}

	//Get 传值绑定到结构体
	//http://127.0.0.1:9999/ss?username=tom&password=123456  ,调用方式
	engine.GET("/ss", func(c *gin.Context) {
		var userinfo Useinfo
		if err := c.ShouldBind(&userinfo); err == nil {
			c.JSON(http.StatusOK, userinfo)
		} else {
			c.JSON(http.StatusBadRequest, gin.H{
				"error": err.Error(),
			})
		}

	})

	//##############################
	//post传值绑定到结构体,用postman进行测试
	engine.POST("/ps", func(c *gin.Context) {
		var userinfopost Useinfo
		if err := c.ShouldBind(&userinfopost); err == nil {
			c.JSON(http.StatusOK, userinfopost)

		} else {
			c.JSON(http.StatusBadRequest, gin.H{
				"err": err.Error(),
			})
		}

	})
	//###########################################################################
	//###########################################################################
	//启动服务
	engine.Run(":9999")

}

 

主函数调用:

func main() {
	//fmt.Println("test")

	//get post同时进行的测试
	//routelab1()

	getpoststruct()
}

 启动:

用postman进行测试:

 

原文链接:https://blog.csdn.net/wtt234/article/details/124446272

栏目分类
最近更新