Golang Context.BindJSON Examples

Golang Context.BindJSON - 30 examples found. These are the top rated real world Golang examples of github.com/gin-gonic/gin.Context.BindJSON extracted from open source projects. You can rate examples to help us improve the quality of examples.
Example #1
0
// curl -H "Content-Type: application/json" -X POST -d '{"commentableId":3,"commentableType":"post","body":"the body of a comment"}' http://localhost:9999/comments
// CommentCreate creates a comment, validates that it belongs to something commentable
func CommentCreate(c *gin.Context) {
	var comment models.Comment
	if c.BindJSON(&comment) == nil {
		comment.UserID = 1

		if comment.CommentableType == "post" {
			_, err := models.GetPost(comment.CommentableID)
			if err != nil {
				c.JSON(http.StatusNotFound, gin.H{"status": "not found"})
				return
			}
		} else if comment.CommentableType == "comment" {
			_, err := models.GetComment(comment.CommentableID)
			if err != nil {
				c.JSON(http.StatusNotFound, gin.H{"status": "not found"})
				return
			}
		} else {
			c.JSON(http.StatusBadRequest, gin.H{"status": "bad request"})
			return
		}

		// TODO: userID should come from session, commentable id/type maybe from route?
		err := models.CreateComment(comment)
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"status": "bad request"})
		} else {
			// TODO: add location header with new resource url
			c.JSON(http.StatusCreated, gin.H{"status": "created"})
		}
	} else {
		c.JSON(http.StatusBadRequest, gin.H{"status": "bad request"})
	}
}
Example #2
0
func (ss *schedulerService) CreateOrUpdateShift(c *gin.Context) {
	shift := &wiw.Shift{}

	if err := c.BindJSON(shift); err != nil {
		ss.handleError(c, err)
		return
	}
	if shift.ManagerID == 0 {
		//TODO: should use current user id
	}

	if c.Request.Method == "POST" {
		if err := ss.repository.CreateShift(shift); err != nil {
			ss.handleError(c, err)
			return
		}
	} else {
		shift.ID = uint(c.MustGet("id").(int))
		if err := ss.repository.UpdateOrCreateShift(shift); err != nil {
			ss.handleError(c, err)
			return
		}
	}
	c.JSON(http.StatusOK, gin.H{"shift": shift})
}
Example #3
0
func LoginHandler(c *gin.Context) {
	var code int
	var response gin.H

	var loginData loginForm
	c.BindJSON(&loginData)

	errors := loginData.validate()

	if len(errors) == 0 {
		user, authErrors := authOrRegisterUser(loginData)
		if authErrors["password"] != "" {
			code = 422
			response = gin.H{"success": false, "errors": authErrors}
		} else {
			code = 200
			response = gin.H{
				"success": true,
				"new":     user.RestoreCode != "",
				"auth": gin.H{
					"account": user.Email,
					"token":   createUserToken(user),
					"roles":   user.Roles,
				},
			}
		}
	} else {
		code = 422
		response = gin.H{"success": false, "errors": errors}
	}
	c.JSON(code, response)
}
Example #4
0
func pluginCreate(c *gin.Context) {
	plugin := Plugin{}
	response := gin.H{}
	defer c.JSON(http.StatusOK, response)
	if err := c.BindJSON(&plugin); err != nil {
		response["code"] = http.StatusBadRequest
		response["message"] = err.Error()
		return
	}
	cnt := 0
	mydb.Table("plugin").Where("name=?", plugin.Name).Count(&cnt)
	if cnt > 0 {
		response["code"] = http.StatusBadRequest
		response["message"] = "plugin already exists"
		return
	}
	if err := mydb.Set("gorm:save_associations", false).Save(&plugin).Error; err != nil {
		response["code"] = http.StatusInternalServerError
		response["message"] = err.Error()
		return
	}
	mydb.Model(&plugin).Association("Hosts").Replace(plugin.Hosts).Find(&plugin.Hosts)

	response["code"] = http.StatusOK
	response["message"] = "user create successful"
	response["plugin"] = plugin
}
Example #5
0
// create handling the creation of a new character
// curl -H "Content-Type: application/json" -X POST -d '{"name":"asdf"}' http://localhost:8989
func create(c *gin.Context) {

	var newName struct {
		Name string `json:"name"`
	}
	ch := NewCharacter{}

	if err := c.BindJSON(&newName); err != nil {
		c.JSON(http.StatusBadRequest, ErrorResponse{"error while binding newName:" + err.Error()})
		return
	}

	checkSum := sha1.Sum([]byte(newName.Name))
	ch.CharacterID = fmt.Sprintf("%x", checkSum)

	char := createCharacter(ch.CharacterID, newName.Name)

	log.Println("Saving character:", char)
	err := mdb.Save(char)
	if err != nil {
		c.JSON(http.StatusBadRequest, ErrorResponse{"error while saving character:" + err.Error()})
		return
	}
	c.JSON(http.StatusCreated, char)
}
Example #6
0
func changePassword(c *gin.Context) {
	request := struct {
		ID              int    `json:'id'`
		CurrentPassword string `json:"current_password"`
		NewPassword     string `json:"new_password"`
	}{}
	response := gin.H{}
	defer c.JSON(http.StatusOK, response)
	if err := c.BindJSON(&request); err != nil {
		response["code"] = http.StatusBadRequest
		response["message"] = err.Error()
		return
	}
	currentUser := GetUser(c)
	if !currentUser.IsAdmin() && currentUser.ID != request.ID {
		response["code"] = 403
		response["message"] = "You don't have permission to access."
		return
	}
	if request.CurrentPassword == request.NewPassword {
		response["code"] = http.StatusNotModified
		response["message"] = "new password equal current password"
		return
	}
	user := types.User{}
	mydb.Table("user").Where("id = ?", request.ID).Find(&user)
	if user.Password != utils.Md5(request.CurrentPassword) {
		response["code"] = http.StatusNotModified
		response["message"] = "current password is incorrect"
		return
	}
	mydb.Table("user").Where("id = ?", request.ID).Update("password", utils.Md5(request.NewPassword))
	response["code"] = http.StatusOK
	response["message"] = "change password success"
}