ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Gin框架系列之数据绑定

2022-04-17 14:02:42  阅读:176  来源: 互联网

标签:username 框架 绑定 ctx ShouldBind gin Gin password


一、问题引出

如果通过前端向后端传递数据,你可能会这样进行接收:

1、前台

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/do_index" method="post">
    用户名:<input type="text" name="username"> <br>
    密  码:<input type="password" name="password"> <br>
    <input type="submit">
</form>
</body>
</html>

显然,前台提交了一个form表单到后台。

2、后台

...
func DoIndex(ctx *gin.Context) {
    username := ctx.PostForm("username")
    password := ctx.PostForm("password")
    fmt.Printf("username:%s,pasword:%s", username, password)
    ctx.String(http.StatusOK, "submit success!")
}
...

可以看到后台通过ctx.PostForm方式逐一获取所有的参数值,那么有没有一种简单方式来解决这个问题,这就是我们所说的通过数据绑定的方式。

二、数据绑定引入

Gin提供了两种类型的绑定:

  • MustBind
  • ShouldBind

1、ShouldBind

它包含多种方法,如:ShouldBind,ShouldBindJSON,ShouldBindXML,ShouldBindQuery,ShouldBindYAML。这些方法属于ShouldBindWith的具体调用, 如果发生绑定错误,Gin 会返回错误并由开发者处理错误和请求。

ShouldBind可以绑定Form、QueryString、Json,uri

  • 前台
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/do_bind_index" method="post">
    用户名:<input type="text" name="username"> <br>
    密  码:<input type="password" name="password"> <br>
    <input type="submit">
</form>
</body>
</html>
  • 后台
package main

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

type LoginInfo struct {
    UserName string `form:"username" json:"username"`
    PassWord string `form:"password" json:"password"`
}

func BindIndex(ctx *gin.Context) {

    ctx.HTML(http.StatusOK, "bind_index.html", nil)

}

func DoBindIndex(ctx *gin.Context) {
     // 将form表单字段绑定到结构体上
    var loginInfo LoginInfo
    _ = ctx.ShouldBind(&loginInfo)
    fmt.Printf("UserName:%s,PassWord:%s", loginInfo.UserName, loginInfo.PassWord)
    ctx.String(http.StatusOK, "submit success!")
}

func main() {

    router := gin.Default()

    router.LoadHTMLGlob("template/*")

    // 数据绑定
    router.GET("/bind_index", BindIndex)
    router.POST("/do_bind_index", DoBindIndex)

    router.Run(":8080")
}

2、MustBind

可以绑定Form、QueryString、Json等,与ShouldBind的区别在于,ShouldBind没有绑定成功不报错,就是空值,MustBind会报错。

 

标签:username,框架,绑定,ctx,ShouldBind,gin,Gin,password
来源: https://www.cnblogs.com/shenjianping/p/16155585.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有