Пример #1
0
func UpdateUser(c *gin.Context) {
	id := c.Params.ByName("id")
	var user User
	err := dbmap.SelectOne(&user, "SELECT * FROM user2 WHERE id=?", id)
	if err == nil {
		var json User
		c.Bind(&json)
		user_id, _ := strconv.ParseInt(id, 0, 64)
		user := User{
			Id:        user_id,
			Firstname: json.Firstname,
			Lastname:  json.Lastname,
		}
		if user.Firstname != "" && user.Lastname != "" {
			_, err = dbmap.Update(&user)
			if err == nil {
				c.JSON(200, user)
			} else {
				checkErr(err, "Updated failed")
			}
		} else {
			c.JSON(422, gin.H{"error": "fields are empty"})
		}
	} else {
		c.JSON(404, gin.H{"error": "user not found"})
	}
	// curl -i -X PUT -H "Content-Type: application/json" -d "{ \"firstname\": \"Thea\", \"lastname\": \"Merlyn\" }" http://localhost:8080/api/v1/users/1
}
Пример #2
0
func PostUser(c *gin.Context) {
	var params User
	c.Bind(&params)

	if params.Firstname != "" && params.Lastname != "" {
		user := &User{0, params.Firstname, params.Lastname}
		err := dbmap.Insert(user)
		if err == nil {
			content := &User{
				Id:        user.Id,
				Firstname: user.Firstname,
				Lastname:  user.Lastname,
			}
			c.JSON(201, content)
		} else {
			c.JSON(422, gin.H{"error": err})
		}
	} else {
		c.JSON(422, gin.H{"error": "fields are empty"})
	}
	// curl -i -X POST -H "Content-Type: application/json" -d "{ \"firstname\": \"Thea\", \"lastname\": \"Queen\" }" http://localhost:8080/api/v1/users
}