百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术文章 > 正文

Golang GinWeb框架4-请求参数绑定和验证

ccwgpt 2024-09-18 12:20 27 浏览 0 评论

???


???????????(Golang GinWeb???3-???????????????????/?????????)???????GinWeb???


?????????


????????????????嵽???Go??????. ?????JSON,XML,YAML?????????(??foo=bar&boo=baz)???.

Gin???go-playground/validator/v10???????????, ????tags?????????????(https://godoc.org/github.com/go-playground/validator#hdr-Baked_In_Validators_and_Tags)

???:??????????????????????α????????????,?????JSON,??????: json:"fieldname"

Gin????????(????)??????:

  • Must bind

1. ????: Bind, BindJSON, BindXML, BindQuery, BindYAML, BindHeader

2. ???: ??Щ??????????MustBindWith????. ????????????, ??????????400??????????:c.AbortWithError(400, err).SetType(ErrorTypeBind), ?????????Content-Type??text/plain; charset=utf-8.???????????????,???????????????,???????: [GIN-debug] [WARNING] Headers were already written. Wanted to override status code 400 with 422, ????????????????Щ???,???????????????ShoudBind????.

  • Should bind

1. ????: ShouldBind, ShouldBindJSON, ShouldBindXML, ShouldBindQuery, ShouldBindYAML, ShouldBindHeader

2. ???: ??Щ??????????ShouldBindWith. ????????????, ???????, ???????????????????????Щ????.

????e??????, Gin????????????Content-Type header??????????????. ??????????????????????,?????????????MustBindWith??ShouldBindWith????.

?????????????????????required????, ??????????????:binding:"required"???, ??????????????????????.

?????′????JSON:

package main
?
import (
  "github.com/gin-gonic/gin"
  "net/http"
)
?
// Binding from JSON
type Login struct {
  User string `form:"user" json:"user" xml:"user"  binding:"required"` //?????form,json,xml,binding????
  //Password string `form:"password" json:"password" xml:"password" binding:"required"`
  Password string `form:"password" json:"password" xml:"password" binding:"-"`
}
?
?func main() {
  router := gin.Default()
?
  // Example for binding JSON ({"user": "manu", "password": "123"})
  router.POST("/loginJSON", func(c *gin.Context) {
    var json Login
    if err := c.ShouldBindJSON(&json); err != nil {
      c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
      return
    }
?
    if json.User != "manu" || json.Password != "123" {
      c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
      return
    }
?
    c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
  })
?
  // Example for binding XML (
  //  <?xml version="1.0" encoding="UTF-8"?>
  //  <root>
  //    <user>user</user>
  //    <password>123</password>
  //  </root>)
  router.POST("/loginXML", func(c *gin.Context) {
    var xml Login
    if err := c.ShouldBindXML(&xml); err != nil {
      c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
      return
    }
?
    if xml.User != "manu" || xml.Password != "123" {
      c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
      return
    }
?
    c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
  })
?
  // Example for binding a HTML form (user=manu&password=123)
  router.POST("/loginForm", func(c *gin.Context) {
    var form Login
    // This will infer what binder to use depending on the content-type header.
    if err := c.ShouldBind(&form); err != nil {
      c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
      return
    }
?
    if form.User != "manu" || form.Password != "123" {
      c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
      return
    }
?
    c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
  })
?
  // Listen and serve on 0.0.0.0:8080
  router.Run(":8080")
}
?
//???????: curl -v -X POST http://localhost:8080/loginJSON -H 'content-type: application/json' -d '{ "user": "manu", "password": "123" }'

???????: ??binding:"required"??????????binding:"-", ???????β?????, ???????????????????.


??????????


??????????????????????????, ?????????ο?(https://github.com/gin-gonic/examples/blob/master/custom-validation/server.go)

package main
?
import (
  "net/http"
  "time"
?
  "github.com/gin-gonic/gin"
  "github.com/gin-gonic/gin/binding"
  "github.com/go-playground/validator/v10"
)
?
// Booking contains binded and validated data.
// Booking???ж??????????????????????????
type Booking struct {
  CheckIn  time.Time `form:"check_in" binding:"required,bookabledate" time_format:"2006-01-02"`  //??????
  CheckOut time.Time `form:"check_out" binding:"required,gtfield=CheckIn" time_format:"2006-01-02"`  //gtfield=CheckIn?????????????????????
}
?
// ?????????????
var bookableDate validator.Func = func(fl validator.FieldLevel) bool {
  date, ok := fl.Field().Interface().(time.Time)  //???÷??????????? -> ????? -> ???????(???????)
  if ok {
    today := time.Now()
    if today.After(date) {  //???????????checkIn?????????,????false,?????????????????????
      return false
    }
  }
  return true
}
?
func main() {
  route := gin.Default()
  //??binding.Validator.Engine()?????????????,?????????Validate??,?????????,?????????????????Gin???
  if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
    // - if the key already exists, the previous validation function will be replaced. ???????????????????????滻
    // - this method is not thread-safe it is intended that these all be registered prior to any validation
    // ????????????????, ?????????,?????????е?????????????
    v.RegisterValidation("bookabledate", bookableDate)
  }
?
  route.GET("/bookable", getBookable)
  route.Run(":8085")
}
?
func getBookable(c *gin.Context) {
  var b Booking
  if err := c.ShouldBindWith(&b, binding.Query); err == nil {
    c.JSON(http.StatusOK, gin.H{"message": "Booking dates are valid!"})
  } else {
    c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  }
}
?
//???????:
// ????????????????????
//$ curl "localhost:8085/bookable?check_in=2030-04-16&check_out=2030-04-17"
//{"message":"Booking dates are valid!"}
//
// ?????????????????, ??????gtfieldУ?????
//$ curl "localhost:8085/bookable?check_in=2030-03-10&check_out=2030-03-09"
//{"error":"Key: 'Booking.CheckOut' Error:Field validation for 'CheckOut' failed on the 'gtfield' tag"}
//
// ???????????????,?????????????????
//$ curl "localhost:8085/bookable?check_in=2000-03-09&check_out=2000-03-10"
//{"error":"Key: 'Booking.CheckIn' Error:Field validation for 'CheckIn' failed on the 'bookabledate' tag"}%

??????弶?????????????μ??????, v.RegisterStructValidation(UserStructLevelValidation, User{}), ??ο?struct-lvl-validation example(https://github.com/gin-gonic/examples/tree/master/struct-lvl-validations)


?ο????


Gin??????:https://github.com/gin-gonic/gin



END?????

??????????, ????, ?????!


??????


Golang GinWeb???3-???????????????????/?????????

Golang GinWeb???2-??????/????panic??????????崦????

Golang GinWeb???-????????/????????

Golang???????????洢????AmazonS3????????

Golang+Vue???Websocket???????????

GolangWeb??????????????HandlerFunc???м??Middleware

Golang????MySQL??в????????-??????

Golang?????????????????

Golang ???????????????(Data Race Detector)???????

Golang"????"MongoDB-????????("??????")

相关推荐

Python Scrapy 项目实战(python scripy)

爬虫编写流程首先明确Python爬虫代码编写的流程:先直接打开网页,找到你想要的数据,就是走一遍流程。比如这个项目我要爬取历史某一天所有比赛的赔率数据、每场比赛的比赛结果等。那么我就先打开这个网址...

为何大厂后端开发更青睐 Python 而非 Java 进行爬虫开发?

在互联网大厂的后端开发领域,爬虫技术广泛应用于数据收集、竞品分析、内容监测等诸多场景。然而,一个有趣的现象是,相较于Java,Python成为了爬虫开发的首选语言。这背后究竟隐藏着怎样的原因呢?让...

爬虫小知识,scrapy爬虫框架中爬虫名词的含义

在上一篇文章当中学记给大家展示了Scrapy爬虫框架在爬取之前的框架文件该如何设置。在上一篇文章当中,是直接以代码的形式进行描述的,在这篇文章当中学记会解释一下上一篇文章当中爬虫代码当中的一些名词...

python爬虫神器--Scrapy(python爬虫详细教程)

什么是爬虫,爬虫能用来做什么?文章中给你答案。*_*今天我们就开发一个简单的项目,来爬取一下itcast.cn中c/c++教师的职位以及名称等信息。网站链接:http://www.itcast.cn...

Gradio:从UI库到强大AI框架的蜕变

Gradio,这个曾经被简单视为PythonUI库的工具,如今已华丽转身,成为AI应用开发的强大框架。它不仅能让开发者用极少的代码构建交互式界面,更通过一系列独特功能,彻底改变了机器学习应用的开发和...

研究人员提出AI模型无损压缩框架,压缩率达70%

大模型被压缩30%性能仍与原模型一致,既能兼容GPU推理、又能减少内存和GPU开销、并且比英伟达nvCOMP解压缩快15倍。这便是美国莱斯大学博士生张天一和合作者打造的无损压缩框架...

阿里发布Qwen-Agent框架,赋能开发者构建复杂AI智能体

IT之家1月4日消息,阿里通义千问Qwen推出全新AI框架Qwen-Agent,基于现有Qwen语言模型,支持智能体执行复杂任务,并提供多种高级功能,赋能开发者构建更强大的AI...

向量数仓与大数据平台:企业数据架构的新范式

在当前的大模型时代,企业数据架构正面临着前所未有的挑战和机遇。随着大模型的不断发布和多模态模型的发展,AIGC应用的繁荣和生态配套的逐渐完备,企业需要适应这种新的数据环境,以应对行业变革。一、大模型时...

干货!大数据管理平台规划设计方案PPT

近年来,随着IT技术与大数据、机器学习、算法方向的不断发展,越来越多的企业都意识到了数据存在的价值,将数据作为自身宝贵的资产进行管理,利用大数据和机器学习能力去挖掘、识别、利用数据资产。如果缺乏有效的...

阿里巴巴十亿级并发系统设计:实现高并发场景下的稳定性和高性能

阿里巴巴的十亿级并发系统设计是其在大规模高并发场景下(如双11、双12等)保持稳定运行的核心技术框架。以下是其关键设计要点及技术实现方案:一、高可用性设计多数据中心与容灾采用多数据中心部署,通过异地容...

阿里云云原生一体化数仓—数据治理新能力解读

一、数据治理中心产品简介阿里云DataWorks:一站式大数据开发与治理平台架构大图阿里云DataWorks定位于一站式的大数据开发和治理平台,从下图可以看出,DataWorks与MaxCom...

DeepSeek R1:理解 GRPO 和多阶段训练

人工智能在DeepSeekR1的发布后取得了显著进步,这是一个挑战OpenAI的o1的开源模型,在高级推理任务中表现出色。DeepSeekR1采用了创新的组相对策略优化(GroupR...

揭秘永久免费视频会议软件平台架构

如今视频会议已经成为各个团队线上协同的必备方式之一,视频会议软件的选择直接影响团队效率与成本,觅讯会议凭借永久免费迅速出圈,本文将从技术架构、核心功能和安全体系等维度,深度解析其技术实现与应用价值,为...

DeepSeek + Kimi = 五分钟打造优质 PPT

首先,在DeepSeek中输出提示词,示例如下:为课程《提示词基础-解锁AI沟通的秘密》设计一个PPT大纲,目的是让学生:1.理解提示词的概念、作用和重要性2.掌握构建有效提示词的基本原则和技巧...

软件系统如何设计可扩展架构?方法论,Java实战代码

软件系统如何设计可扩展架构?方法论,Java实战代码,请关注,点赞,收藏。方法论那先想想方法论部分。扩展性架构的关键点通常包括分层、模块化、微服务、水平扩展、异步处理、缓存、负载均衡、分布式架构等等...

取消回复欢迎 发表评论: