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


Golang Context.Bind方法代碼示例

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


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

示例1: UpdateTodo

func (tr *TodoResource) UpdateTodo(c *gin.Context) {
	id, err := tr.getId(c)
	if err != nil {
		c.JSON(400, api.NewError("problem decoding id sent"))
		return
	}

	var todo api.Todo

	if !c.Bind(&todo) {
		c.JSON(400, api.NewError("problem decoding body"))
		return
	}
	todo.Id = int32(id)

	var existing api.Todo

	if tr.db.First(&existing, id).RecordNotFound() {
		c.JSON(404, api.NewError("not found"))
	} else {
		tr.db.Save(&todo)
		c.JSON(200, todo)
	}

}
開發者ID:tsingson,項目名稱:todos-backend,代碼行數:25,代碼來源:todo_resource.go

示例2: GetLoginToken

func GetLoginToken(c *gin.Context) {
	remote := remote.FromContext(c)

	in := &tokenPayload{}
	err := c.Bind(in)
	if err != nil {
		c.AbortWithError(http.StatusBadRequest, err)
		return
	}

	login, err := remote.Auth(in.Access, in.Refresh)
	if err != nil {
		c.AbortWithError(http.StatusUnauthorized, err)
		return
	}

	user, err := store.GetUserLogin(c, login)
	if err != nil {
		c.AbortWithError(http.StatusNotFound, err)
		return
	}

	exp := time.Now().Add(time.Hour * 72).Unix()
	token := token.New(token.SessToken, user.Login)
	tokenstr, err := token.SignExpires(user.Hash, exp)
	if err != nil {
		c.AbortWithError(http.StatusInternalServerError, err)
		return
	}

	c.IndentedJSON(http.StatusOK, &tokenPayload{
		Access:  tokenstr,
		Expires: exp - time.Now().Unix(),
	})
}
開發者ID:allenbhuiyan,項目名稱:drone,代碼行數:35,代碼來源:login.go

示例3: loginHandler

func loginHandler(c *gin.Context) {
	var (
		login LoginData
	)
	// bind POST data to struct
	err := c.Bind(&login)
	if err != nil {
		c.JSON(401, "Invalid Credentials Provided")
	} else {
		// return 401 if empty
		if login.Username == "" || login.Password == "" {
			c.JSON(401, "Invalid Credentials Provided")
			return
		}

		// get user from database and fill our struct
		dbUserObject, err := validateUser(login.Username, login.Password)
		if err != nil {
			// return 401 if incorect user or password
			c.JSON(401, "Invalid Credentials")
			return
		}
		// generate token
		token := genToken(dbUserObject)

		// return token to user
		c.JSON(200, token)
		return
	}

	// return 400 if any other error is encountered
	c.JSON(400, "Error encountered")
}
開發者ID:stefanjarina,項目名稱:bookmarks-gin,代碼行數:33,代碼來源:auth.go

示例4: saveCurrentChannelEndPoint

func saveCurrentChannelEndPoint(c *gin.Context) {
	var json = &struct {
		ID   int    `json:"ID"`
		Type string `json:"Type"`
	}{}

	if c.Bind(json) != nil {
		c.JSON(http.StatusBadRequest, gin.H{"ERR": "WRONG_INPUT"})
		return
	}

	userID64, _ := c.Get("userID")
	userID := userID64.(int)

	cc := &CurrentChannel{
		Type: json.Type,
		ID:   json.ID,
	}

	if peer, ok := peers.get(userID); ok {
		maxMsgId, _ := maxMsgIDofRoom(json.ID)
		cc.LastMsgID = maxMsgId
		peer.ccUpdate(cc)
	}

	if _, err := saveCurrentChannel(userID, cc); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"ERR": "INTERNAL_SERVER_ERROR",
		})
	} else {

		c.JSON(http.StatusOK, gin.H{"SUC": "OK"})
	}
}
開發者ID:zhanghjster,項目名稱:ChatChat,代碼行數:34,代碼來源:http.go

示例5: configure

func configure(c *gin.Context) {
	var form conf.Conf
	var dat []byte
	var err error

	if err = c.Bind(&form); err == nil {
		errors := form.Validate()
		if len(errors) > 0 {
			c.JSON(http.StatusBadRequest, errors)
			return
		}
		if err = form.FillDefaults(); err != nil {
			fmt.Println("An error occured while filling default values :", err)
			c.AbortWithError(http.StatusInternalServerError, err)
			return
		}
		if dat, err = yaml.Marshal(&form); err != nil {
			fmt.Println("An error occured while marshalling the yaml data :", err)
			c.AbortWithError(http.StatusInternalServerError, err)
			return
		}
		if err = ioutil.WriteFile("conf.yml", dat, 0644); err != nil {
			fmt.Println("An error occured while writing the conf.yml file :", err)
			c.AbortWithError(http.StatusInternalServerError, err)
			return
		}
	} else {
		fmt.Println("An error occured while reading the form data :", err)
		c.JSON(http.StatusBadRequest, gin.H{})
		return
	}
	c.JSON(http.StatusCreated, gin.H{})
}
開發者ID:Depado,項目名稱:goploader,代碼行數:33,代碼來源:setup.go

示例6: AddTemplate

func AddTemplate(c *gin.Context) {
	project := c.MustGet("project").(models.Project)

	var template models.Template
	if err := c.Bind(&template); err != nil {
		return
	}

	res, err := database.Mysql.Exec("insert into project__template set ssh_key_id=?, project_id=?, inventory_id=?, repository_id=?, environment_id=?, playbook=?, arguments=?, override_args=?", template.SshKeyID, project.ID, template.InventoryID, template.RepositoryID, template.EnvironmentID, template.Playbook, template.Arguments, template.OverrideArguments)
	if err != nil {
		panic(err)
	}

	insertID, err := res.LastInsertId()
	if err != nil {
		panic(err)
	}

	template.ID = int(insertID)

	objType := "template"
	desc := "Template ID " + strconv.Itoa(template.ID) + " created"
	if err := (models.Event{
		ProjectID:   &project.ID,
		ObjectType:  &objType,
		ObjectID:    &template.ID,
		Description: &desc,
	}.Insert()); err != nil {
		panic(err)
	}

	c.JSON(201, template)
}
開發者ID:pselibas,項目名稱:semaphore,代碼行數:33,代碼來源:templates.go

示例7: apiReposCreate

// POST /api/repos
func apiReposCreate(c *gin.Context) {
	var b struct {
		Name                string `binding:"required"`
		Comment             string
		DefaultDistribution string
		DefaultComponent    string
	}

	if !c.Bind(&b) {
		return
	}

	repo := deb.NewLocalRepo(b.Name, b.Comment)
	repo.DefaultComponent = b.DefaultComponent
	repo.DefaultDistribution = b.DefaultDistribution

	collection := context.CollectionFactory().LocalRepoCollection()
	collection.Lock()
	defer collection.Unlock()

	err := context.CollectionFactory().LocalRepoCollection().Add(repo)
	if err != nil {
		c.Fail(400, err)
		return
	}

	c.JSON(201, repo)
}
開發者ID:smira,項目名稱:aptly,代碼行數:29,代碼來源:repos.go

示例8: JwtGetToken

// generate jwt token and return to client
func JwtGetToken(c *gin.Context) {
	var login Login
	val := c.Bind(&login)
	if !val {
		c.JSON(200, gin.H{"code": 401, "msg": "Both name & password are required"})
		return
	}
	//	if login.Name == validUser.Name && login.Pass == validUser.Pass {
	token := jwt.New(jwt.SigningMethodHS256)
	// Headers
	token.Header["alg"] = "HS256"
	token.Header["typ"] = "JWT"

	// Claims
	token.Claims["name"] = validUser.Name
	token.Claims["mail"] = validUser.Mail
	token.Claims["exp"] = time.Now().Add(time.Hour * 72).Unix()
	tokenString, err := token.SignedString([]byte(mySigningKey))

	fmt.Println("jwt token raw: ", tokenString)

	if err != nil {
		c.JSON(200, gin.H{"code": 500, "msg": "Server error!"})
		return
	}
	c.JSON(200, gin.H{"code": 200, "msg": "OK", "jwt": tokenString})
	//	} else {
	//		c.JSON(200, gin.H{"code": 400, "msg": "Error username or password!"})
	//	}
}
開發者ID:tsingson,項目名稱:todos-backend,代碼行數:31,代碼來源:jwt-token.go

示例9: CreateTrainingJob

// Create Training Job
func (e EndpointContext) CreateTrainingJob(c *gin.Context) {

	// bind to json
	user := c.MustGet(MIDDLEWARE_KEY_USER).(User)
	db := c.MustGet(MIDDLEWARE_KEY_DB).(couch.Database)

	trainingJob := NewTrainingJob(e.Configuration)
	trainingJob.UserID = user.Id

	// bind the input struct to the JSON request
	if ok := c.Bind(trainingJob); !ok {
		errMsg := fmt.Sprintf("Invalid input")
		c.String(400, errMsg)
		return
	}

	logg.LogTo("REST", "Create new TrainingJob: %+v", trainingJob)

	// save training job in db
	trainingJob, err := trainingJob.Insert(db)
	if err != nil {
		c.String(500, err.Error())
		return
	}

	// job will get kicked off by changes listener

	// return solver object
	c.JSON(201, *trainingJob)

}
開發者ID:WideEyesTech,項目名稱:elastic-thought,代碼行數:32,代碼來源:endpoint_context.go

示例10: SignInPost

//SignInPost handles POST /signin route, authenticates user
func SignInPost(c *gin.Context) {
	session := sessions.Default(c)
	user := &models.User{}
	if err := c.Bind(user); err != nil {
		session.AddFlash("Please, fill out form correctly.")
		session.Save()
		c.Redirect(http.StatusFound, "/signin")
		return
	}

	userDB, _ := models.GetUserByEmail(user.Email)
	if userDB.ID == 0 {
		logrus.Errorf("Login error, IP: %s, Email: %s", c.ClientIP(), user.Email)
		session.AddFlash("Email or password incorrect")
		session.Save()
		c.Redirect(http.StatusFound, "/signin")
		return
	}
	if err := bcrypt.CompareHashAndPassword([]byte(userDB.Password), []byte(user.Password)); err != nil {
		logrus.Errorf("Login error, IP: %s, Email: %s", c.ClientIP(), user.Email)
		session.AddFlash("Email or password incorrect")
		session.Save()
		c.Redirect(http.StatusFound, "/signin")
		return
	}

	session.Set("UserID", userDB.ID)
	session.Save()
	c.Redirect(http.StatusFound, "/")
}
開發者ID:denisbakhtin,項目名稱:ginblog,代碼行數:31,代碼來源:auth.go

示例11: registerUser

func registerUser(c *gin.Context, d db.DbService) {
	var u JSON

	if err := c.Bind(&u); err != nil {
		RestErrorInvalidBody(c)
		return
	}

	hashedPassword, err := bcrypt.GenerateFromPassword([]byte(u["password"].(string)), 10)
	if err != nil {
		RestError(c, err)
		return
	}

	doc := JSON{
		"_id":       u["email"].(string),
		"password":  hashedPassword,
		"createdAt": time.Now(),
	}

	if err := d.Insert(doc); err != nil {
		RestError(c, err)
		return
	}

	utils.OK(c)
}
開發者ID:vishnuvr,項目名稱:neutrino-core,代碼行數:27,代碼來源:auth.go

示例12: AddUser

func AddUser(c *gin.Context) {
	project := c.MustGet("project").(models.Project)
	var user struct {
		UserID int  `json:"user_id" binding:"required"`
		Admin  bool `json:"admin"`
	}

	if err := c.Bind(&user); err != nil {
		return
	}

	if _, err := database.Mysql.Exec("insert into project__user set user_id=?, project_id=?, admin=?", user.UserID, project.ID, user.Admin); err != nil {
		panic(err)
	}

	objType := "user"
	desc := "User ID " + strconv.Itoa(user.UserID) + " added to team"
	if err := (models.Event{
		ProjectID:   &project.ID,
		ObjectType:  &objType,
		ObjectID:    &user.UserID,
		Description: &desc,
	}.Insert()); err != nil {
		panic(err)
	}

	c.AbortWithStatus(204)
}
開發者ID:pselibas,項目名稱:semaphore,代碼行數:28,代碼來源:users.go

示例13: Create

func (tr *TodoResource) Create(c *gin.Context) {
	// Parse the form data
	var todo Todo
	c.Bind(&todo)

	// Write to the database
	err := tr.db.Update(func(tx *bolt.Tx) error {

		b := tx.Bucket(bucket)

		if todo.Id == 0 {
			id, _ := b.NextSequence()
			todo.Id = id
			todo.Created = int32(time.Now().Unix())
		}

		return b.Put(todo.Key(), todo.Value())
	})

	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	// Respond with the results
	c.JSON(http.StatusCreated, todo)
}
開發者ID:awonak,項目名稱:todo,代碼行數:27,代碼來源:resource.go

示例14: PatchTodo

func (tr *TodoResource) PatchTodo(c *gin.Context) {
	id, err := tr.getId(c)
	if err != nil {
		c.JSON(400, api.NewError("problem decoding id sent"))
		return
	}

	// this is a hack because Gin falsely claims my unmarshalled obj is invalid.
	// recovering from the panic and using my object that already has the json body bound to it.
	var json []api.Patch
	defer func() {
		if r := recover(); r != nil {
			if json[0].Op != "replace" && json[0].Path != "/status" {
				c.JSON(400, api.NewError("PATCH support is limited and can only replace the /status path"))
				return
			}

			var todo api.Todo

			if tr.db.First(&todo, id).RecordNotFound() {
				c.JSON(404, api.NewError("not found"))
			} else {
				todo.Status = json[0].Value

				tr.db.Save(&todo)
				c.JSON(200, todo)
			}
		}
	}()
	c.Bind(&json)
}
開發者ID:tsingson,項目名稱:todos-backend,代碼行數:31,代碼來源:todo_resource.go

示例15: PostUser

func PostUser(c *gin.Context) {
	var user User
	c.Bind(&user)

	if user.Firstname != "" && user.Lastname != "" {
		db, _ := sql.Open("postgres", "user=cshutchinson dbname=godb sslmode=disable")
		// checkErr(err)
		var lastInsertId int64
		_ = db.QueryRow("INSERT INTO users(firstname,lastname, id) VALUES($1,$2, Default) returning id;", user.Firstname, user.Lastname).Scan(&lastInsertId)
		content := &User{
			Id:        lastInsertId,
			Firstname: user.Firstname,
			Lastname:  user.Lastname,
		}
		c.JSON(201, content)
		// if insert, _ := dbmap.Exec(`INSERT INTO users (firstname, lastname) VALUES (?, ?) returning id;`, user.Firstname, user.Lastname).Scan(&lastInsertId); insert != nil {
		//   user_id, err := insert.LastInsertId()
		//   if err == nil {
		//     content := &User{
		//       Id: user_id,
		//       Firstname: user.Firstname,
		//       Lastname: user.Lastname,
		//     }
		//     c.JSON(201, content)
		//   } else {
		//     checkErr(err, "Insert failed")
		//   }
		// }
	} 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
}
開發者ID:cshutchinson,項目名稱:api-server-golang,代碼行數:33,代碼來源:api.go


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