Json数据解析与绑定

客户端传参,后端接收并解析到结构体

func Login(context *gin.Context) {
// 声明接收的变量
var login LoginJson
// 将request的body中的数据,自动按照json格式解析到结构体
// 等价于:context.ShouldBindWith(&login, binding.JSON)
if err := context.ShouldBindJSON(&login); err != nil {
context.JSON(http.StatusBadRequest, err.Error())
return
}
// 判断用户名密码是否正确
if login.User != "root" || login.Password != "admin" {
fmt.Println("用户名或密码错误")
context.JSON(http.StatusBadRequest, gin.H{"status": 304})
return
}
context.String(http.StatusOK, "OK")
}

表单数据解析和绑定

func Login(context *gin.Context) {
// 声明接收的变量
var login LoginJson
// Bind默认解析并绑定Form格式
// 根据请求头中的Content-Type自动推断
// binding.Form是form-data类型, binding.FormPost是x-www-form-urlencoded类型
if err := context.ShouldBindWith(&login, binding.FormPost); err != nil {
context.JSON(http.StatusBadRequest, err.Error())
return
}
// 判断用户名密码是否正确
if login.User != "root" || login.Password != "admin" {
fmt.Println("用户名或密码错误")
context.JSON(http.StatusBadRequest, gin.H{"status": 304})
return
}
context.String(http.StatusOK, "OK")
}

URI数据解析和绑定

func Login(context *gin.Context) {
// 声明接收的变量
var login LoginJson if err := context.ShouldBindUri(&login); err != nil {
context.JSON(http.StatusBadRequest, err.Error())
return
}
// 判断用户名密码是否正确
if login.User != "root" || login.Password != "admin" {
fmt.Println("用户名或密码错误")
context.JSON(http.StatusBadRequest, gin.H{"status": 304})
return
}
context.String(http.StatusOK, "OK")
}

注意:Uri请求应该写成这样: router.POST("/login/:username/:password", Login)

http://127.0.0.1:8080/login/root/admin

结构体中也可以定义相关的字段标签:

// 定义接收数据的结构体
type LoginJson struct {
User string `form:"username" json:"username" uri:"username" binding:"required"`
Password string `form:"password" json:"password" uri:"password" binding:"required"`
}

上传单个或多个文件

// 上传单个文件
func UploadFile(context *gin.Context) {
file, _ := context.FormFile("file")
// 注意此目录是相对于项目的目录,而不是当前文件的目录
context.SaveUploadedFile(file, "./app/files/" + file.Filename)
context.JSON(200, "upload file ok")
} // 上传多个文件
func UploadFiles(context *gin.Context) {
form, _ := context.MultipartForm()
files := form.File["file"]
for _, file := range files {
context.SaveUploadedFile(file, "./app/files/" + file.Filename)
}
context.JSON(200, "upload files ok")
}

gin框架中的数据解析与绑定的更多相关文章

  1. 02 . Go框架之Gin框架从入门到熟悉(数据解析和绑定,渲染,重定向,同步异步,中间件)

    数据解析和绑定 json数据解析和绑定 package main import ( "github.com/gin-gonic/gin" "net/http" ...

  2. Gin框架04:趣谈参数绑定与校验

    导读 在第二节,我们学习了Gin框架的路由定义与参数接收,今天应一位同学的要求,来讲解一下参数的绑定与校验. 为什么校验参数? 本不必抛出这个问题的,但顾及到初出茅庐的同学,这里解释一下. 假设做一个 ...

  3. 在gin框架中使用JWT

    在gin框架中使用JWT JWT全称JSON Web Token是一种跨域认证解决方案,属于一个开放的标准,它规定了一种Token实现方式,目前多用于前后端分离项目和OAuth2.0业务场景下. 什么 ...

  4. gin框架中的路由

    基本路由 gin框架中采用的路由库是基于httrouter做的 地址为:https://github.com/julienschmidt/httprouter httprouter路由库 点击查看代码 ...

  5. DRF框架中链表数据通过ModelSerializer深度查询方法汇总

    DRF框架中链表数据通过ModelSerializer深度查询方法汇总 一.准备测试和理解准备 创建类 class Test1(models.Model): id = models.IntegerFi ...

  6. golang gin框架中实现一个简单的不是特别精确的秒级限流器

    起因 看了两篇关于golang中限流器的帖子: Gin 开发实践:如何实现限流中间件 常用限流策略--漏桶与令牌桶介绍 我照着用,居然没效果-- 时间有限没有深究.这实在是一个很简单的功能,我的需求是 ...

  7. gin框架中请求路由组的使用

    1. gin框架中可以使用路由组来实现对路由的分类 package main import "github.com/gin-gonic/gin" func main() { rou ...

  8. gin框架中请求参数的绑定与多数据格式处理

    package main import ( "fmt" "github.com/gin-gonic/gin" ) // gin框架提供给开发者表单实体绑定的功能 ...

  9. gin框架中的参数验证

    结构体验证 用gin框架的数据验证,可以不用解析数据,减少if else,会简洁许多. 处理请求方法 func structValidator(context *gin.Context) { var ...

随机推荐

  1. JAVA火星坐标系、百度坐标系、84坐标系相互转换工具类

    /** * 坐标系转换工具类 */ public class PositionUtil { public static double pi = 3.1415926535897932384626; pu ...

  2. JAVA中价格金额的存储类型

    在java项目中,我们会遇到价格.金额的数据,这时候我们java中应该用BigDecimal类型,数据库用decimal类型, 长度可以自定义, 如18; 小数点我们项目中用的是2, 保留2位小数. ...

  3. 【LeetCode】Pascal's Triangle II 解题报告

    [LeetCode]Pascal's Triangle II 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/pascals-tr ...

  4. 【LeetCode】284. Peeking Iterator 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址:https://leetcode.com/problems/peeking-i ...

  5. Codeforces 876B:Divisiblity of Differences(数学)

    B. Divisiblity of Differences You are given a multiset of n integers. You should select exactly k of ...

  6. CausalVAE: Disentangled Representation Learning via Neural Structural Causal Models

    目录 概 主要内容 模型 ELBO 关于 Yang M., Liu F., Chen Z., Shen X., Hao J. and Wang J. CausalVAE: disentangled r ...

  7. [CNKI]个人论文收录

    [1]在校期间参加大创项目研究 以论文形式结题 发表时间:2018-03-25 基于VR虚拟现实技术的CBD微圈电商平台的研究 林旭; 陈丽娟 内江科技 2018-03-25 期刊 链接: 基于VR虚 ...

  8. SQL Server 数据库添加主键,唯一键,外键约束脚本

    -- 声明使用数据库use 数据库;go -- 添加主键(primary key)约束-- 基本语法-- 判断主键约束是否存在,如果存在则删除,不存在则添加if exists(select * fro ...

  9. .NET 云原生架构师训练营(责任链模式)--学习笔记

    目录 责任链模式 源码 责任链模式 职责链上的处理者负责处理请求,客户只需要将请求发送到职责链上即可,无需关心请求的处理细节和请求的传递,所以职责链将请求的发送者和请求的处理者解耦了 何时使用:在处理 ...

  10. ATA考试

    一.确定机房作为ATA考试机器的数量. (1)确定本次ATA考试本校每个机房上报了多少台机器. ATA考试机的使用总数量不包含ATA管理机器.在上报机房机器数量的时候,在      机房的总数量上减去 ...