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

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

ccwgpt 2024-09-18 12:20 32 浏览 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+ Appium:Android手机连接与操作详解(附源码)

在移动端自动化测试领域,Appium一直是最热门的开源工具之一。今天这篇文章,我们聚焦Android端自动化测试的完整流程,从环境配置到代码实战,一步一步带你掌握用Python控制Android...

全平台开源即时通讯IM框架MobileIMSDK开发指南,支持鸿蒙NEXT

写在前面在着手基于MobileIMSDK开发自已的即时通讯应用前,建议以Demo工程为脚手架,快速上手MobileIMSDK!Demo工程主要用于演示SDK的API调用等,它位于SDK完整下载包的如下...

移动开发(一):使用.NET MAUI开发第一个安卓APP

对于工作多年的C#程序员来说,近来想尝试开发一款安卓APP,考虑了很久最终选择使用.NETMAUI这个微软官方的框架来尝试体验开发安卓APP,毕竟是使用VisualStudio开发工具,使用起来也...

在安卓系统上开发一款软件详细的流程

安卓app软件开发流程是一个系统而复杂的过程,涉及多个阶段和环节。以下是一个典型的安卓软件开发流程概述:1.需求分析目的:了解用户需求,确定APP的目标、功能、特性和预期效果。活动:开发团队与客户进...

ArkUI-X在Android上使用Fragment开发指南

本文介绍将ArkUI框架的UIAbility跨平台部署至Android平台Fragment的使用说明,实现Android原生Fragment和ArkUI跨平台Fragment的混合开发,方便开发者灵活...

Web3开发者必须要知道的6个框架与开发工具

在Web3领域,随着去中心化应用和区块链的兴起,开发者们需要掌握适用于这一新兴技术的框架与开发工具。这些工具和框架能够提供简化开发流程、增强安全性以及提供更好的用户体验。1.Truffle:Truff...

Python开发web指南之创建你的RESTful APP

上回我们说到了:PythonFlask开发web指南:创建RESTAPI。我们知道了Flask是一个web轻量级框架,可以在上面做一些扩展,我们还用Flask创建了API,也说到了...

python的web开发框架有哪些(python主流web框架)

  python在web开发方面有着广泛的应用。鉴于各种各样的框架,对于开发者来说如何选择将成为一个问题。为此,我特此对比较常见的几种框架从性能、使用感受以及应用情况进行一个粗略的分析。  1Dja...

Qwik:革新Web开发的新框架(webview开源框架)

听说关注我的人,都实现了财富自由!你还在等什么?赶紧加入我们,一起走向人生巅峰!Qwik:革新Web开发的新框架Qwik橫空出世:一场颠覆前端格局的革命?是炒作还是未来?前端框架的更新迭代速度,如同...

Python中Web开发框架有哪些?(python主流web框架)

Python为Web开发提供了许多优秀的框架。以下是一些流行的PythonWeb框架:1.Django:一个高级的Web框架,旨在快速开发干净、实用的Web应用。Django遵...

WPF 工业自动化数据管控框架,支持热拔插 DLL与多语言实现

前言工业自动化开发中,设备数据的采集、处理与管理成为提升生产效率和实现智能制造的关键环节。为了简化开发流程、提高系统的灵活性与可维护性,StarRyEdgeFramework应运而生。该框架专注...

[汇川PLC] 汇川IFA程序框架06-建立气缸控制FB块

前言:汇川的iFA要跟西门子对标啦,这可是新的选择!就在2月14日,汇川刚发布的iFA平台,一眼就能看出来是对标西门子的全集成自动化平台博途(TIAPortal)。这个平台能在同一个...

微软发布.NET 10首个预览版:JIT编译器再进化、跨平台开发更流畅

IT之家2月26日消息,微软.NET团队昨日(2月25日)发布博文,宣布推出.NET10首个预览版更新,重点改进.NETRuntime、SDK、libraries、C#、AS...

大模型部署革命:GGUF量化+vLLM推理的极致性能调优方案

本文较长,建议点赞收藏,以免遗失。更多AI大模型应用开发学习视频及资料,尽在官网-聚客AI学院大模型应用开发微调项目实践课程学习平台一、模型微调核心概念与技术演进1.1微调的本质与优势数学表达:1....

拓扑学到底在研究什么?(拓扑学到底在研究什么问题)

拓扑是“不量尺寸的几何学”,那么它的核心内容,主要方法是什么?如果你问罗巴切夫斯基,他会说“附贴性是物体的一个特殊的属性。如果我们把这个性质掌握,而把物体其他的一切属性,不问是本质的或偶然出现的,均不...

取消回复欢迎 发表评论: