use same struct for both create and update operations in go lang using gin and gorm

Disclaimer: go lang noob here

I’ve my user struct as

type User struct {
	ID        uint32    `json:"id"`
	FirstName string    `json:"firstName" binding:"required"`
	LastName  string    `json:"lastName"`
	Email     string    `json:"email" binding:"required,email,uniqueModelValue=users email"`
	Active    bool      `json:"active"`
	Password  string    `json:"password,omitempty" binding:"required,gte=8"`
	UserType  string    `json:"userType" binding:"oneof=admin backoffice principal staff parent student"`
	CreatedAt time.Time `json:"createdAt"`
	UpdatedAt time.Time `json:"updatedAt"`
}

/POST /users handler

    func Create(ctx *gin.Context) {
    	user := models.User{}
    	//validate
    	if err := ctx.ShouldBind(&user); err != nil {
    		response.Error(ctx, err)
    		return
    
    	}
    	db, _ := database.GetDB()
    	db.Create(&user)
    	// removing password from the response
    	user.Password = ""
    	response.Success(ctx, user)
    }

I want to create an update handler using the same struct, is there any way I can perform using the same struct ?

Mind you, struct has required bindings on many fields firstName,email etc.
while updating, I might not pass these fields

I came up with something like

/PUT /users/ handler

    func Update(ctx *gin.Context) {
    	userID := ctx.Param("userId")
    	user := models.User{}
    	db, _ := database.GetDB()
    	if err := db.First(&user, userID).Error; err != nil {
    		response.Error(ctx, err)
    		return
    	}
    	updateUser := models.User{}
    	if err := ctx.BindJSON(&updateUser); err != nil {
    		response.Error(ctx, err)
    	}
    	//fmt.Printf("%v", updateUser)
    	db.Model(&user).Updates(updateUser)
    	response.Success(ctx, user)
    }

this is failing obviously due to required validations missing, if I try to update, let’s say, just the lastName

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.