• 将请求体绑定到不同的结构体中


    package main
    
    import (
    	"github.com/gin-gonic/gin"
    	"github.com/gin-gonic/gin/binding"
    	"net/http"
    )
    
    type formA struct {
    	Foo string `json:"foo" xml:"foo" binding:"required"`
    }
    
    type formB struct {
    	Bar string `json:"bar" xml:"bar" binding:"required"`
    }
    
    // 绑定请求体的常规方法使用c.Request.Body,并且不能多次调用
    func SomeHandler(c *gin.Context) {
    	objA := formA{}
    	objB := formB{}
    
    	if errA := c.ShouldBind(&objA); errA == nil {
    		c.String(http.StatusOK, `the body should be formA`)
    
    	} else if errB := c.ShouldBind(&objB); errB == nil {
    		c.String(http.StatusOK, `the body should be formB`)
    	} else {
    
    	}
    }
    
    //同样,你能使用c.ShouldBindBodyWith
    func SomeHandler2(c *gin.Context) {
    	objA := formA{}
    	objB := formB{}
    
    	if errA := c.ShouldBindBodyWith(&objA, binding.JSON); errA == nil {
    		c.String(http.StatusOK, `the body should be formA`)
    
    	} else if errB := c.ShouldBindBodyWith(&objB, binding.JSON); errB == nil {
    		c.String(http.StatusOK, `the body should be formB JSON`)
    
    	} else if errB2 := c.ShouldBindBodyWith(&objB, binding.XML); errB2 == nil {
    		c.String(http.StatusOK, `the body should be formB XML`)
    	} else {
    
    	}
    }
    

      

  • 相关阅读:
    在庫購買管理(MM)
    指図ステータス
    購買発注変更、照会画面に初期表示される発注伝票はどのように決まっているのか
    金額処理
    翻訳
    mysql 与mongodb的特点与优劣
    PHP经典算法
    Linux下PHP安装redis扩展
    Linux上安装Redis教程
    PHP插入法排序
  • 原文地址:https://www.cnblogs.com/yzg-14/p/13153322.html
Copyright © 2020-2023  润新知