ginは、リクエスト本文をさまざまな構造にバインドします

ginは、リクエスト本文をさまざまな構造にバインドします

リクエスト本文をバインドする従来の方法が使用されc.Request.Body、複数回呼び出すことはできません

type formA struct {
  Foo string `json:"foo" xml:"foo" binding:"required"`
}

type formB struct {
  Bar string `json:"bar" xml:"bar" binding:"required"`
}

func SomeHandler(c *gin.Context) {
  objA := formA{}
  objB := formB{}
  // This c.ShouldBind consumes c.Request.Body and it cannot be reused.
  if errA := c.ShouldBind(&objA); errA == nil {
    c.String(http.StatusOK, `the body should be formA`)
  // Always an error is occurred by this because c.Request.Body is EOF now.
  } else if errB := c.ShouldBind(&objB); errB == nil {
    c.String(http.StatusOK, `the body should be formB`)
  } else {
    ...
  }
}

同様に、あなたは使用することができますc.ShouldBindBodyWith

func SomeHandler(c *gin.Context) {
  objA := formA{}
  objB := formB{}
  // This reads c.Request.Body and stores the result into the context.
  if errA := c.ShouldBindBodyWith(&objA, binding.JSON); errA == nil {
    c.String(http.StatusOK, `the body should be formA`)
  // At this time, it reuses body stored in the context.
  } else if errB := c.ShouldBindBodyWith(&objB, binding.JSON); errB == nil {
    c.String(http.StatusOK, `the body should be formB JSON`)
  // And it can accepts other formats
  } else if errB2 := c.ShouldBindBodyWith(&objB, binding.XML); errB2 == nil {
    c.String(http.StatusOK, `the body should be formB XML`)
  } else {
    ...
  }
}
  • c.ShouldBindBodyWith バインドする前に本文をコンテキストに保存します。これはパフォーマンスにわずかな影響を与えるため、すぐに呼び出す場合は、このメソッドを使用しないでください。
  • -この機能は、これらのフォーマットでのみ利用可能です JSON、  XML、  MsgPack、  ProtoBuf他のフォーマットの場合は、Query、  Form、  FormPost、  FormMultipart、それができるc.ShouldBind()のパフォーマンスに影響を与えることなく、複数回呼び出さ

おすすめ

転載: blog.csdn.net/ma2595162349/article/details/109434995