溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

如何在gin框架中利用結構體來獲取參數

發布時間:2021-10-12 10:55:02 來源:億速云 閱讀:441 作者:iii 欄目:編程語言

這篇文章主要介紹“如何在gin框架中利用結構體來獲取參數”,在日常操作中,相信很多人在如何在gin框架中利用結構體來獲取參數問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”如何在gin框架中利用結構體來獲取參數”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!

我們在寫http請求的時候都會遇到后端的Handler是如何來接受請求的參數,我們在請求的時候有表單請求,ajax請求(參數是json),如下:

http://localhost:8080/bind?name=tim&age=1

在gin框架中我們是怎么利用結構體來獲取參數呢?   其實很簡單我們直接看代碼

engine.GET("/bind", handler.BindHandler)


package handler

import (
	"fmt"
	"github.com/gin-gonic/gin"
)

// 定義結構體
type Member struct {
	Name string `form:"name"`
	Age  int    `form:"age"`
}

func BindHandler(c *gin.Context) {
	m := &Member{}
	c.Bind(m)
	fmt.Println(m)
	c.JSON(200, gin.H{
		"code": "ok",
	})
}

就是利用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)
}

Bind的注釋可以看出如何綁定和綁定的格式和Content-Type有很大的關系,從源碼可以看出有很多類型格式的數據都都可以進行綁定

// BindJSON is a shortcut for c.MustBindWith(obj, binding.JSON).
func (c *Context) BindJSON(obj interface{}) error {
	return c.MustBindWith(obj, binding.JSON)
}

// BindXML is a shortcut for c.MustBindWith(obj, binding.BindXML).
func (c *Context) BindXML(obj interface{}) error {
	return c.MustBindWith(obj, binding.XML)
}

// BindQuery is a shortcut for c.MustBindWith(obj, binding.Query).
func (c *Context) BindQuery(obj interface{}) error {
	return c.MustBindWith(obj, binding.Query)
}

// BindYAML is a shortcut for c.MustBindWith(obj, binding.YAML).
func (c *Context) BindYAML(obj interface{}) error {
	return c.MustBindWith(obj, binding.YAML)
}

// BindHeader is a shortcut for c.MustBindWith(obj, binding.Header).
func (c *Context) BindHeader(obj interface{}) error {
	return c.MustBindWith(obj, binding.Header)
}

// 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
}

到此,關于“如何在gin框架中利用結構體來獲取參數”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續學習更多相關知識,請繼續關注億速云網站,小編會繼續努力為大家帶來更多實用的文章!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女