激情久久久_欧美视频区_成人av免费_不卡视频一二三区_欧美精品在欧美一区二区少妇_欧美一区二区三区的

腳本之家,腳本語言編程技術及教程分享平臺!
分類導航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服務器之家 - 腳本之家 - Golang - 淺談Gin框架中bind的使用

淺談Gin框架中bind的使用

2022-01-22 16:25xiaojinran Golang

Gin框架中有bind函數,可以非常方便的將url的查詢參數query parameter、http的Header,body中提交上來的數據格式,本文就詳細的介紹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個接口

淺談Gin框架中bind的使用

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數據

淺談Gin框架中bind的使用

綁定QueryParameter數據

淺談Gin框架中bind的使用

綁定Body Json數據

淺談Gin框架中bind的使用

綁定Uri數據

淺談Gin框架中bind的使用

 

總結

  • 使用gin框架中的bind方法,可以很容易對http請求過來的數據傳遞到我們的結構體指針去,方便我們代碼編程。
  • 當參數比較簡單,不需要結構體來進行封裝時候,此時還需采用context的其他方法來獲取對應的值
  • gin在bind的時候,未對結構體的數據進行有效性檢查,如果對數據有強要求時,需要自己對結構體的數據內容進行判斷
  • 建議在實踐過程中,使用shouldBind<xxx>函數

到此這篇關于淺談Gin框架中bind的使用的文章就介紹到這了,更多相關Gin框架中bind內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!

原文鏈接:https://blog.csdn.net/xiaojinran/article/details/118788032

延伸 · 閱讀

精彩推薦
  • GolangGolang中Bit數組的實現方式

    Golang中Bit數組的實現方式

    這篇文章主要介紹了Golang中Bit數組的實現方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧...

    天易獨尊11682021-06-09
  • GolangGolang通脈之數據類型詳情

    Golang通脈之數據類型詳情

    這篇文章主要介紹了Golang通脈之數據類型,在編程語言中標識符就是定義的具有某種意義的詞,比如變量名、常量名、函數名等等,Go語言中標識符允許由...

    4272021-11-24
  • Golanggolang 通過ssh代理連接mysql的操作

    golang 通過ssh代理連接mysql的操作

    這篇文章主要介紹了golang 通過ssh代理連接mysql的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧...

    a165861639710342021-03-08
  • Golanggolang如何使用struct的tag屬性的詳細介紹

    golang如何使用struct的tag屬性的詳細介紹

    這篇文章主要介紹了golang如何使用struct的tag屬性的詳細介紹,從例子說起,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看...

    Go語言中文網11352020-05-21
  • Golanggolang的httpserver優雅重啟方法詳解

    golang的httpserver優雅重啟方法詳解

    這篇文章主要給大家介紹了關于golang的httpserver優雅重啟的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,...

    helight2992020-05-14
  • Golanggolang json.Marshal 特殊html字符被轉義的解決方法

    golang json.Marshal 特殊html字符被轉義的解決方法

    今天小編就為大家分享一篇golang json.Marshal 特殊html字符被轉義的解決方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧 ...

    李浩的life12792020-05-27
  • Golanggo日志系統logrus顯示文件和行號的操作

    go日志系統logrus顯示文件和行號的操作

    這篇文章主要介紹了go日志系統logrus顯示文件和行號的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧...

    SmallQinYan12302021-02-02
  • Golanggo語言制作端口掃描器

    go語言制作端口掃描器

    本文給大家分享的是使用go語言編寫的TCP端口掃描器,可以選擇IP范圍,掃描的端口,以及多線程,有需要的小伙伴可以參考下。 ...

    腳本之家3642020-04-25
主站蜘蛛池模板: 色妞视频男女视频 | 久久精品欧美视频 | 国产91亚洲精品久久久 | 91在线色| 一区二区三区四区五区中文字幕 | 亚洲人成中文字幕在线观看 | 一色屋任你操 | 成人资源在线观看 | www.mitao | 99这里有精品 | 国产91精品久久久久久久 | 国产精品久久久久久久久久10秀 | 欧美在线 | 亚洲 | 亚洲一区免费观看 | 成人情欲视频在线看免费 | 激情综合网俺也去 | 欧美亚洲综合网 | 黄色av电影在线播放 | 日本成人一二三区 | 五月激情久久 | 大奶一级片 | 亚洲综合视频在线播放 | 在线观看免费视频麻豆 | 性生活香蕉视频 | 久草在线高清 | 毛片一级视频 | 嗯哈~不行好大h双性 | 中文字幕在线网站 | 亚洲欧美日韩久久精品第一区 | 亚洲码无人客一区二区三区 | 欧美片a| 日日草夜夜操 | 成人免费看毛片 | 久久久日韩精品一区二区三区 | 国产午夜精品一区二区三区四区 | 久久精品国产99国产精品亚洲 | 亚洲av毛片在线观看 | 成人在线观看免费视频 | 国产精品999在线观看 | 黄在线免费看 | 欧洲精品久久久 |