當前位置: 首頁>>代碼示例>>Golang>>正文


Golang Context.BindJSON方法代碼示例

本文整理匯總了Golang中github.com/gin-gonic/gin.Context.BindJSON方法的典型用法代碼示例。如果您正苦於以下問題:Golang Context.BindJSON方法的具體用法?Golang Context.BindJSON怎麽用?Golang Context.BindJSON使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在github.com/gin-gonic/gin.Context的用法示例。


在下文中一共展示了Context.BindJSON方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: create

// 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)
}
開發者ID:Skarlso,項目名稱:goprogressquest,代碼行數:27,代碼來源:create.go

示例2: CommentCreate

// 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"})
	}
}
開發者ID:shwing,項目名稱:moledro,代碼行數:36,代碼來源:comment.go

示例3: LoginHandler

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)
}
開發者ID:2bizi,項目名稱:goapicore,代碼行數:32,代碼來源:login.go

示例4: CreateOrUpdateShift

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})
}
開發者ID:ezeql,項目名稱:wiw-scheduler-api,代碼行數:25,代碼來源:main.go

示例5: pluginCreate

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
}
開發者ID:avldya,項目名稱:OWL-v3,代碼行數:27,代碼來源:plugins.go

示例6: changePassword

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"
}
開發者ID:avldya,項目名稱:OWL-v3,代碼行數:35,代碼來源:users.go

示例7: groupCreate

func groupCreate(c *gin.Context) {
	group := Group{}
	response := gin.H{}
	defer c.JSON(http.StatusOK, response)
	if err := c.BindJSON(&group); err != nil {
		response["code"] = http.StatusBadRequest
		response["message"] = err.Error()
		return
	}
	cnt := 0
	mydb.Table("group").Where("name=?", group.Name).Count(&cnt)
	if cnt > 0 {
		response["code"] = http.StatusBadRequest
		response["message"] = "group already exists"
		return
	}
	if err := mydb.Set("gorm:save_associations", false).Save(&group).Error; err != nil {
		response["code"] = http.StatusInternalServerError
		response["message"] = err.Error()
		return
	}
	mydb.Model(&group).Association("Hosts").Replace(group.Hosts).Find(&group.Hosts)

	response["code"] = http.StatusOK
	response["message"] = "group create successful"
	response["group"] = group
}
開發者ID:TalkingData,項目名稱:OWL-v3,代碼行數:27,代碼來源:groups.go

示例8: UpdateConfig

func UpdateConfig(c *gin.Context) {
	confWriteMux.Lock()
	defer confWriteMux.Unlock()

	data := &updateConfigData{}
	if err := c.BindJSON(data); err != nil {
		Error(c, BAD_POST_DATA, err.Error())
		return
	}

	if err := verifyUpdateConfigData(data); err != nil {
		Error(c, BAD_REQUEST, err.Error())
		return
	}

	oldConfig := memConfRawConfigs[data.Key]
	if oldConfig.K == data.K && oldConfig.V == data.V && oldConfig.VType == data.VType && oldConfig.Des == data.Des && oldConfig.Status == data.Status {
		Success(c, nil)
		return
	}

	config, err := updateConfigWithUpdateData(data, getOpUserKey(c))
	if err != nil {
		Error(c, SERVER_ERROR, err)
		return
	}

	failedNodes := syncData2SlaveIfNeed(config, getOpUserKey(c))
	if len(failedNodes) > 0 {
		Success(c, map[string]interface{}{"failed_nodes": failedNodes})
	} else {
		Success(c, nil)
	}
}
開發者ID:Instafig,項目名稱:Instafig,代碼行數:34,代碼來源:op_api.go

示例9: InitUser

func InitUser(c *gin.Context) {
	confWriteMux.Lock()
	defer confWriteMux.Unlock()

	if len(memConfUsers) > 0 {
		Error(c, BAD_REQUEST, "users already exists")
		return
	}

	data := &newUserData{}
	if err := c.BindJSON(data); err != nil {
		Error(c, BAD_POST_DATA, err.Error())
		return
	}

	if err := verifyNewUserData(data); err != nil {
		Error(c, BAD_REQUEST, err.Error())
		return
	}

	key := utils.GenerateKey()
	user, err := newUserWithNewUserData(data, key, key)
	if err != nil {
		Error(c, SERVER_ERROR, err.Error())
		return
	}

	failedNodes := syncData2SlaveIfNeed(user, key)
	setUserKeyCookie(c, user.Key, user.PassCode)
	if len(failedNodes) > 0 {
		Success(c, map[string]interface{}{"failed_nodes": failedNodes})
	} else {
		Success(c, nil)
	}
}
開發者ID:Instafig,項目名稱:Instafig,代碼行數:35,代碼來源:op_api.go

示例10: Login

func Login(c *gin.Context) {
	var data struct {
		Name     string `json:"name" binding:"required"`
		PassCode string `json:"pass_code" binding:"required"`
	}
	if err := c.BindJSON(&data); err != nil {
		Error(c, BAD_POST_DATA, err.Error())
		return
	}

	memConfMux.RLock()
	user := memConfUsersByName[data.Name]
	memConfMux.RUnlock()

	if user == nil {
		Error(c, USER_NOT_EXIST)
		return
	}
	if user.PassCode != encryptUserPassCode(data.PassCode) {
		Error(c, PASS_CODE_ERROR)
		return
	}

	if user.Status == models.USER_STATUS_INACTIVE {
		Error(c, USER_INACTIVE)
		return
	}

	setUserKeyCookie(c, user.Key, user.PassCode)
	Success(c, nil)
}
開發者ID:Instafig,項目名稱:Instafig,代碼行數:31,代碼來源:op_api.go

示例11: NewConfig

func NewConfig(c *gin.Context) {
	confWriteMux.Lock()
	defer confWriteMux.Unlock()

	data := &newConfigData{}
	if err := c.BindJSON(data); err != nil {
		Error(c, BAD_POST_DATA, err.Error())
		return
	}

	if err := verifyNewConfigData(data); err != nil {
		Error(c, BAD_REQUEST, err.Error())
		return
	}

	config, err := newConfigWithNewConfigData(data, getOpUserKey(c))
	if err != nil {
		Error(c, SERVER_ERROR, err.Error())
		return
	}

	failedNodes := syncData2SlaveIfNeed(config, getOpUserKey(c))
	if len(failedNodes) > 0 {
		Success(c, map[string]interface{}{"failed_nodes": failedNodes})
	} else {
		Success(c, nil)
	}
}
開發者ID:Instafig,項目名稱:Instafig,代碼行數:28,代碼來源:op_api.go

示例12: UpdateApp

func UpdateApp(c *gin.Context) {
	confWriteMux.Lock()
	defer confWriteMux.Unlock()

	var data struct {
		Key     string `json:"key" binding:"required"`
		Name    string `json:"name" binding:"required"`
		Type    string `json:"type" binding:"required"`
		AuxInfo string `json:"aux_info"`
	}
	if err := c.BindJSON(&data); err != nil {
		Error(c, BAD_POST_DATA, err.Error())
		return
	}

	if !models.IsValidAppType(data.Type) {
		Error(c, BAD_REQUEST, "unknown app type: "+data.Type)
		return
	}

	oldApp := memConfApps[data.Key]
	if oldApp == nil {
		Error(c, BAD_REQUEST, "app key not exists: "+data.Key)
		return
	}

	if oldApp.Name == data.Name && oldApp.AuxInfo == data.AuxInfo && oldApp.Type == data.Type {
		Success(c, nil)
		return
	}

	if oldApp.Type == models.APP_TYPE_TEMPLATE && oldApp.Type != data.Type {
		Error(c, BAD_REQUEST, "can not change template app to real app")
		return
	}

	if memConfApps[data.Key].Name != data.Name {
		for _, app := range memConfApps {
			if app.Name == data.Name {
				Error(c, BAD_REQUEST, "appname already exists: "+data.Name)
				return
			}
		}
	}

	app := *oldApp
	app.Name = data.Name
	app.AuxInfo = data.AuxInfo
	if _, err := updateApp(&app, nil, nil); err != nil {
		Error(c, SERVER_ERROR, err.Error())
		return
	}

	failedNodes := syncData2SlaveIfNeed(&app, getOpUserKey(c))
	if len(failedNodes) > 0 {
		Success(c, map[string]interface{}{"failed_nodes": failedNodes})
	} else {
		Success(c, nil)
	}
}
開發者ID:Instafig,項目名稱:Instafig,代碼行數:60,代碼來源:op_api.go

示例13: UpdateUserPassCode

func UpdateUserPassCode(c *gin.Context) {
	confWriteMux.Lock()
	defer confWriteMux.Unlock()

	var data struct {
		PassCode string `json:"pass_code" binding:"required"`
	}
	if err := c.BindJSON(&data); err != nil {
		Error(c, BAD_POST_DATA, err.Error())
		return
	}

	user := *memConfUsers[getOpUserKey(c)]
	user.PassCode = encryptUserPassCode(data.PassCode)

	if _, err := updateUser(&user, nil); err != nil {
		Error(c, SERVER_ERROR, err.Error())
		return
	}

	setUserKeyCookie(c, user.Key, user.PassCode)
	failedNodes := syncData2SlaveIfNeed(&user, getOpUserKey(c))
	if len(failedNodes) > 0 {
		Success(c, map[string]interface{}{"failed_nodes": failedNodes})
	} else {
		Success(c, nil)
	}
}
開發者ID:Instafig,項目名稱:Instafig,代碼行數:28,代碼來源:op_api.go

示例14: UpdateUser

func UpdateUser(c *gin.Context) {
	confWriteMux.Lock()
	defer confWriteMux.Unlock()

	data := &updateUserData{}
	if err := c.BindJSON(data); err != nil {
		Error(c, BAD_POST_DATA, err.Error())
		return
	}

	if err := verifyUpdateUserData(data, getOpUserKey(c)); err != nil {
		Error(c, BAD_REQUEST, err.Error())
		return
	}

	oldUser := memConfUsers[getOpUserKey(c)]
	if oldUser.AuxInfo == data.AuxInfo && oldUser.Name == data.Name {
		Success(c, nil)
		return
	}

	user, err := updateUserWithUpdateData(data, getOpUserKey(c))
	if err != nil {
		Error(c, SERVER_ERROR, err.Error())
		return
	}

	failedNodes := syncData2SlaveIfNeed(user, getOpUserKey(c))
	if len(failedNodes) > 0 {
		Success(c, map[string]interface{}{"failed_nodes": failedNodes})
	} else {
		Success(c, nil)
	}
}
開發者ID:Instafig,項目名稱:Instafig,代碼行數:34,代碼來源:op_api.go

示例15: startDirectDownload

//DownloadPacket starts the download of a packet
func (dc *DownloadsController) startDirectDownload(c *gin.Context) {
	var download models.DirectDownload
	c.BindJSON(&download)

	dc.IrcClient.AddDirectDownload(&download)
	OK(c)
}
開發者ID:kahoona77,項目名稱:emerald,代碼行數:8,代碼來源:downloads.go


注:本文中的github.com/gin-gonic/gin.Context.BindJSON方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。