0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ShouldBindJSONの内部処理

Posted at

func SubmitUserDetail(c *gin.Context) {
    UserDetail := &models.UserDetail{}
    if err := c.ShouldBindJSON(UserDetail); err != nil { 
        c.JSON(http.StatusBadRequest, gin.H{"message": "不正なリクエストです"})
        return
    }
    if err := models.RegisterUserDetail(db, UserDetail); err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"err": "ユーザー情報登録できませんでした"})
        return
    }

    c.JSON(http.StatusOK, gin.H{"message": "登録が成功しました"})
}

このコードだが、

gin.Context) {
    var   UserDetail UserDetail

これでもバインド出来る。
これだとUserDetailに初期値nilが入るため構造体にバインド出来ないように思えるが、
ShouldBindJSONは引数がnilの場合、メモリ上に新たに構造体オブジェクトを作成しバインドするのだ。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?