浅谈Gin框架中bind的使用
来源:脚本之家
时间:2022-12-29 17:32:01 179浏览 收藏
对于一个Golang开发者来说,牢固扎实的基础是十分重要的,golang学习网就来带大家一点点的掌握基础知识点。今天本篇文章带大家了解《浅谈Gin框架中bind的使用》,主要介绍了Gin框架bind,希望对大家的知识积累有所帮助,快点收藏起来吧,否则需要时就找不到了!
概述
Gin框架中,有bind函数可以非常方便的将url的查询参数query parameter、http的Header,body中提交上来的数据格式,如form,json,xml等,绑定到go中的结构体中去,这期间Binding做了啥事情,这么多个Bindding函数,我们该如何选择,一起通过源码来解开其中神秘的面纱吧。
Binding接口
type Binding interface { Name() string Bind(*http.Request, interface{}) error }
Binding是一个接口,在源码中,有10个实现了Binding的结构体,以及3个接口
context.Bind
// Bind checks the Content-Type to select a binding engine automatically, // Depending the "Content-Type" header different bindings are used: // "application/json" --> JSON binding // "application/xml" --> XML binding // otherwise --> returns an error. // It parses the request's body as JSON if Content-Type == "application/json" using JSON or XML as a JSON input. // It decodes the json payload into the struct specified as a pointer. // It writes a 400 error and sets Content-Type header "text/plain" in the response if input is not valid. func (c *Context) Bind(obj interface{}) error { b := binding.Default(c.Request.Method, c.ContentType()) return c.MustBindWith(obj, b) }
cnotext.MustBindWith
// MustBindWith binds the passed struct pointer using the specified binding engine. // It will abort the request with HTTP 400 if any error occurs. // See the binding package. func (c *Context) MustBindWith(obj interface{}, b binding.Binding) error { if err := c.ShouldBindWith(obj, b); err != nil { c.AbortWithError(http.StatusBadRequest, err).SetType(ErrorTypeBind) // nolint: errcheck return err } return nil }
从注解和源码可以看出,MustBindWith最终也是调用了SouldBindWith,并且对ShouldBindWith的结果进行了判断,如果有错误,则以http 400的状态码进行退出。
ShouldBindWith
// ShouldBindWith binds the passed struct pointer using the specified binding engine. // See the binding package. func (c *Context) ShouldBindWith(obj interface{}, b binding.Binding) error { return b.Bind(c.Request, obj) }
这个方法是所有其他绑定方法的一个基础,基本上所有的绑定方法都需要用到这个方法来对数据结构进行一个绑定
以上为主要的bingding的过程,其他派生出来的如BindJSON、ShouldBindJSON等,为具体的数据类型的快捷方式而已,只是帮我们把具体的bingding的数据类型提前给封装了起来而已,如Json格式的bingding函数
context.BindJSON
// BindJSON is a shortcut for c.MustBindWith(obj, binding.JSON). func (c *Context) BindJSON(obj interface{}) error { return c.MustBindWith(obj, binding.JSON) }
context.BindJSON从源码上分析,可以看到,仅仅比Bind方法少了一句
b := binding.Default(c.Request.Method, c.ContentType())
这一句是为了判断当前的请求方法和contentType,来给context.MustBindWith传的一个具体的bingding类型。
Json的实现的Binding接口如下
func (jsonBinding) Bind(req *http.Request, obj interface{}) error { if req == nil || req.Body == nil { return fmt.Errorf("invalid request") } return decodeJSON(req.Body, obj) }
jsonBinding结构体实现了Binding接口的Bind方法,将请求过来的Body数据进行解码,绑定到obj里面去
context.ShouldBindJSON
// ShouldBindJSON is a shortcut for c.ShouldBindWith(obj, binding.JSON). func (c *Context) ShouldBindJSON(obj interface{}) error { return c.ShouldBindWith(obj, binding.JSON) }
从源码的注解来看,ShouldBindJSON其实就是ShouldBindWith(obj, binding.JSON)的快捷方式,简单来说,就是在ShouldBindWith(obj, binding.JSON)上面固定了参数,当我们明确规定,body提交的参数内容为json时,简化了我们的调用和增强了代码的可读性。
context.ShouldBindUri()
// ShouldBindUri binds the passed struct pointer using the specified binding engine. func (c *Context) ShouldBindUri(obj interface{}) error { m := make(map[string][]string) for _, v := range c.Params { m[v.Key] = []string{v.Value} } return binding.Uri.BindUri(m, obj) }
从url绑定采用的方法跟header和body的方式不一样,不需要传入一个实现Binding接口的结构体类型
context.ShouldBindUri()
// BindUri binds the passed struct pointer using binding.Uri. // It will abort the request with HTTP 400 if any error occurs. func (c *Context) BindUri(obj interface{}) error { if err := c.ShouldBindUri(obj); err != nil { c.AbortWithError(http.StatusBadRequest, err).SetType(ErrorTypeBind) // nolint: errcheck return err } return nil }
BindUri也是对ShouldBindUri的一个封装,多了一个对ShouldBindUri结果的一个判断 代码实例
代码如下
package main import ( "github.com/gin-gonic/gin" "net/http" ) type queryHeader struct { Myheader string `header:"myheader"` Mydemo string `header:"mydemo"` } type queryBody struct { Name string `json:"name"` Age int `json:"age"` Sex int `json:"sex"` } type queryParameter struct { Year int `form:"year"` Month int `form:"month"` } type queryUri struct { Id int `uri:"id"` Name string `uri:"name"` } func bindUri(context *gin.Context){ var q queryUri err:= context.ShouldBindUri(&q) if err != nil { context.JSON(http.StatusBadRequest,gin.H{ "result":err.Error(), }) return } context.JSON(http.StatusOK,gin.H{ "result":"绑定成功", "uri": q, }) } func bindQuery(context *gin.Context){ var q queryParameter err:= context.ShouldBindQuery(&q) if err != nil { context.JSON(http.StatusBadRequest,gin.H{ "result":err.Error(), }) return } context.JSON(http.StatusOK,gin.H{ "result":"绑定成功", "query": q, }) } func bindBody(context *gin.Context){ var q queryBody err:= context.ShouldBindJSON(&q) if err != nil { context.JSON(http.StatusBadRequest,gin.H{ "result":err.Error(), }) return } context.JSON(http.StatusOK,gin.H{ "result":"绑定成功", "body": q, }) } func bindhead(context *gin.Context){ var q queryHeader err := context.ShouldBindHeader(&q) if err != nil { context.JSON(http.StatusBadRequest,gin.H{ "result":err.Error(), }) return } context.JSON(http.StatusOK,gin.H{ "result":"绑定成功", "header": q, }) } func main(){ srv := gin.Default() srv.GET("/binding/header",bindhead) srv.GET("/binding/body",bindBody) srv.GET("/binding/query",bindQuery) srv.GET("/binding/:id/:name",bindUri) srv.Run(":9999") }
运行结果
绑定Header数据
绑定QueryParameter数据
绑定Body Json数据
绑定Uri数据
总结
- 使用gin框架中的bind方法,可以很容易对http请求过来的数据传递到我们的结构体指针去,方便我们代码编程。
- 当参数比较简单,不需要结构体来进行封装时候,此时还需采用context的其他方法来获取对应的值
- gin在bind的时候,未对结构体的数据进行有效性检查,如果对数据有强要求时,需要自己对结构体的数据内容进行判断
- 建议在实践过程中,使用shouldBind
函数
好了,本文到此结束,带大家了解了《浅谈Gin框架中bind的使用》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!
-
505 收藏
-
502 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
201 收藏
-
102 收藏
-
467 收藏
-
469 收藏
-
148 收藏
-
250 收藏
-
350 收藏
-
206 收藏
-
467 收藏
-
501 收藏
-
216 收藏
-
284 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 508次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 497次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 484次学习
-
- 自信的石头
- 这篇技术贴太及时了,很详细,赞 👍👍,已收藏,关注大佬了!希望大佬能多写Golang相关的文章。
- 2023-06-10 02:11:35
-
- 糟糕的服饰
- 这篇博文出现的刚刚好,细节满满,很有用,收藏了,关注博主了!希望博主能多写Golang相关的文章。
- 2023-01-23 10:19:16
-
- 朴实的小丸子
- 真优秀,一直没懂这个问题,但其实工作中常常有遇到...不过今天到这,帮助很大,总算是懂了,感谢博主分享技术文章!
- 2023-01-22 01:01:28
-
- 心灵美的方盒
- 这篇技术贴太及时了,好细啊,很有用,码住,关注博主了!希望博主能多写Golang相关的文章。
- 2023-01-16 16:13:56
-
- 腼腆的月饼
- 太全面了,已收藏,感谢师傅的这篇博文,我会继续支持!
- 2023-01-15 17:59:49
-
- 完美的时光
- 很好,一直没懂这个问题,但其实工作中常常有遇到...不过今天到这,帮助很大,总算是懂了,感谢作者大大分享文章内容!
- 2023-01-05 00:00:41
-
- 天真的故事
- 这篇技术贴真及时,楼主加油!
- 2023-01-03 14:42:24
-
- 喜悦的果汁
- 太细致了,mark,感谢大佬的这篇文章内容,我会继续支持!
- 2023-01-01 13:12:56