Fork me on GitHub

Gin框架系列之数据绑定

一、问题引出

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

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会报错。

 

posted @   iveBoy  阅读(564)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
TOP
点击右上角即可分享
微信分享提示

目录导航