2017-03-12 12 views
0

を結合私はGolang GIN-gonic JSON

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

以下の構造体を持っていると私は、このJSONに投稿するとき、私は次のエンドポイント

func sendFoo(c *gin.Context) { 
     var json *foos 

     if err := c.BindJSON(&json); err != nil { 
      c.AbortWithStatus(400) 
      return 
     } 

     // Do something about json 
    } 

を持って

{"bar":"bar bar"} 

errが常にありますなし。私はバインディングを書く必要があり、それは動作しません。しかし、以下のようにエンドポイントを変更すると、

func sendFoo(c *gin.Context) { 
    var json foos //remove pointer 

    if err := c.BindJSON(&json); err != nil { 
      c.AbortWithStatus(400) 
      return 
    } 

    // Do something about json 
} 

バインディングが動作していて、エラーはゼロではありません。どうして?それはbinding.goに記載されて

+0

最初のケースで 'c.BindJSON(json)'を実行するとどうなりますか? – zerkms

+0

できません。アンマーシャリングエラーが発生します –

+0

詳細を教えてください。 2番目のケースでそうしないと、ポインタが "unmarshall error"をどのように通すのでしょうか? 'var json * foos =&foos {}'や 'json:=&foos {}'というポインタを初期化して 'json'を単に渡すとどうなりますか? – zerkms

答えて

1

、行25-32:あなたのケースでは

type StructValidator interface { 
    // ValidateStruct can receive any kind of type and it should never panic, even if the configuration is not right. 
    // If the received type is not a struct, any validation should be skipped and nil must be returned. 
    // If the received type is a struct or pointer to a struct, the validation should be performed. 
    // If the struct is not valid or the validation itself fails, a descriptive error should be returned. 
    // Otherwise nil must be returned. 
    ValidateStruct(interface{}) error 
} 

、ValidateStructは、構造体へのポインタへのポインタを受け取り、文書としてチェックは、行われません。