gin框架05--Multipart/Urlencoded 绑定

gin框架05--Multipart/Urlencoded 绑定

介绍

本文介绍 gin中multipart/urlencoded绑定, 用户 post 指定数据后,如符合要求则给出对应的输出。

案例

代码

package main

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

type LoginForm struct {
	User     string `form:"user" binding:"required"`
	Password string `form:"password" binding:"required"`
}

func main() {
	router := gin.Default()
	router.POST("/login", func(c *gin.Context) {
		// 你可以使用显式绑定声明绑定 multipart form:
		// c.ShouldBindWith(&form, binding.Form)
		// 或者简单地使用 ShouldBind 方法自动绑定:
		var form LoginForm
		// 在这种情况下,将自动选择合适的绑定
		if c.ShouldBind(&form) == nil {
			if form.User == "user" && form.Password == "password" {
				c.JSON(200, gin.H{"status": "you are logged in"})
			} else {
				c.JSON(401, gin.H{"status": "unauthorized"})
			}
		}
	})
	router.Run(":8080")
}

其中 form:“user” 表示前端提交form表单时User对应的key的名称为:user

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<form action="http://localhost:8080/login" method="post" enctype="application/x-www-form-urlencoded">
    用户名<input type="text" name="user"><br>
    密码<input type="password" name="password">
    <input type="submit" value="提交">
</form>
</body>
</html>

测试

$ curl -v --form user=user --form password=password http://localhost:8080/login
*   Trying 127.0.0.1:8080...
...
< 
* Connection #0 to host localhost left intact
{"status":"you are logged in"}

$ curl localhost:8080/login --form user=user --form password=password1
{"status":"unauthorized"}

web 测试:
在这里插入图片描述
在这里插入图片描述

说明

goin官方文档 Multipart/Urlencoded 绑定
gin中multipart/urlencoded绑定

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

昕光xg

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值