本文整理匯總了Golang中github.com/mholt/binding.Bind函數的典型用法代碼示例。如果您正苦於以下問題:Golang Bind函數的具體用法?Golang Bind怎麽用?Golang Bind使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了Bind函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: stubosEdit
// stubosEdit is shared between the create and update handler, since they share most of the logic.
func (h *DBHandler) stubosEdit(rw http.ResponseWriter, req *http.Request, id uint) {
stuboForm := new(StuboForm)
log.WithFields(log.Fields{
"id": id,
"url_path": req.URL.Path,
}).Info("Entering stubosEdti")
// validate form
if err := binding.Bind(req, stuboForm); err.Handle(rw) {
fmt.Println(err.Error())
return
}
// assing form variables to stubo struct
stubo := Stubo{Name: stuboForm.Name, Version: stuboForm.Version, Hostname: stuboForm.Hostname,
Port: stuboForm.Port, Protocol: stuboForm.Protocol}
h.db.Create(&stubo)
log.WithFields(log.Fields{
"id": id,
"url_path": req.URL.Path,
}).Info("Stubo added")
// TODO: should add some messages to user about successful creation
h.stuboShowHandler(rw, req)
}
示例2: RegisterUser
//RegisterUser ...
func (client *ClientController) RegisterUser(res http.ResponseWriter, req *http.Request) {
//Extract the models from the request
render := render.New(render.Options{})
registeredType := new(services.RegisteredUser)
errs := binding.Bind(req, registeredType)
userlogic.ServiceList = client.ServiceList
userlogic.Logger = client.Logger
if errs.Handle(res) {
client.Logger.Crit(errs.Error())
render.JSON(res, 422, errs.Error())
return
}
bindingErr := registeredType.Validate(req, errs)
if bindingErr != nil {
client.Logger.Crit(bindingErr.Error())
render.JSON(res, 422, bindingErr.Error())
return
}
person, user, err := userlogic.RegisterUser(registeredType.Person, registeredType.User)
if err != nil {
client.Logger.Error(err.Error())
panic(err)
}
render.JSON(res, 200, map[string]interface{}{"Person": person, "User": user})
}
示例3: UpdateUser
// UpdateUser updates selected fields of a user provided by an id mux parameter.
func UpdateUser(server *app.App) func(w http.ResponseWriter, req *http.Request) {
return func(w http.ResponseWriter, req *http.Request) {
vars := mux.Vars(req)
id := vars["id"]
user := &models.User{ID: id}
if ok, err := server.DB.Exists(user); err != nil || !ok {
server.Render.JSON(w, http.StatusNotFound, nil)
return
}
updateReq := &models.UserUpdateRequest{}
if err := binding.Bind(req, updateReq); err.Handle(w) {
return
}
hash, err := bcrypt.GenerateFromPassword([]byte(updateReq.Password), 12)
if err != nil {
server.Render.JSON(w, http.StatusInternalServerError, map[string]string{"error": "there was an error updating the user"})
log.Println(err)
return
}
if err := server.DB.Update(user, map[string]interface{}{"Hash": string(hash)}); err != nil {
server.Render.JSON(w, http.StatusInternalServerError, map[string]string{"error": "there was an error updating the user"})
log.Println(err)
return
}
user.Hash = ""
server.Render.JSON(w, http.StatusOK, user)
}
}
示例4: AddNewAddressToUser
//AddNewAddressToUser ... Add address to a user profile
func (client *ClientController) AddNewAddressToUser(res http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
render := render.New(render.Options{})
address := models.Addresses{}
errs := binding.Bind(req, &address)
userlogic.ServiceList = client.ServiceList
userlogic.Logger = client.Logger
userlogic.AuthorizationToken = req.Header.Get("Authorization")
if errs.Handle(res) {
client.Logger.Crit(errs.Error())
render.JSON(res, 422, errs.Error())
return
}
bindingErr := address.Validate(req, errs)
if bindingErr != nil {
client.Logger.Crit(bindingErr.Error())
render.JSON(res, 422, bindingErr.Error())
return
}
savedEntity, bSave, err := userlogic.AddNewAddressToUser(address)
if !bSave && err != nil {
client.Logger.Error(err.Error())
panic(err)
}
render.JSON(res, 200, savedEntity)
}
示例5: CreateUser
// CreateUser is a http handler function to creation a new user.
func CreateUser(server *app.App) func(w http.ResponseWriter, req *http.Request) {
return func(w http.ResponseWriter, req *http.Request) {
userReq := &models.UserRequest{}
if err := binding.Bind(req, userReq); err.Handle(w) {
return
}
existing, err := models.FindUserByEmail(server.DB, userReq.Email)
if err != nil {
server.Render.JSON(w, http.StatusInternalServerError, map[string]string{"error": "there was an error saving the user to the database"})
log.Println(err)
return
}
if existing.ID != "" {
server.Render.JSON(w, http.StatusBadRequest, map[string]string{"error": "user email must be unique across the application"})
return
}
user, err := models.NewUser(userReq.Email, []byte(userReq.Password))
if err != nil {
server.Render.JSON(w, http.StatusInternalServerError, map[string]string{"error": "there was an error saving the user to the database"})
log.Println(err)
return
}
if err := server.DB.Save(user); err != nil {
server.Render.JSON(w, http.StatusInternalServerError, map[string]string{"error": "there was an error saving the user to the database"})
log.Println(err)
return
}
user.Hash = ""
server.Render.JSON(w, http.StatusCreated, user)
}
}
示例6: createRoom
func createRoom(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {
// binding 패키지를 사용하여 room 생성 요청 정보를 Room 타입의 값으로 변환
r := new(Room)
errs := binding.Bind(req, r)
if errs.Handle(w) {
return
}
// 몽고DB 세션 생성
session := mongoSession.Copy()
// 몽고DB 세션을 닫는 코드를 defer로 등록
defer session.Close()
// 몽고DB 아이디 생성
r.ID = bson.NewObjectId()
// room 정보 저장을 위한 몽고DB 컬렉션 객체 생성
c := session.DB("test").C("rooms")
// rooms 컬렉션에 room 정보 저장
if err := c.Insert(r); err != nil {
// 오류 발생시 500 에러 리턴
renderer.JSON(w, http.StatusInternalServerError, err)
return
}
// 처리 결과 리턴
renderer.JSON(w, http.StatusCreated, r)
}
示例7: CreateGood
// CreateGood ... create new merchant
func (mer MerchantController) CreateGood(res http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
r := render.New(render.Options{})
good := new(models.Goods)
errs := binding.Bind(req, good)
if errs.Handle(res) {
r.JSON(res, 422, errs.Error())
return
}
bindingErr := good.Validate(req, errs)
if bindingErr != nil {
r.JSON(res, 422, bindingErr.Error())
return
}
// save to database
p := models.Goods{mer.BaseModel, good.MerchantID, good.PercentDiscount, good.AvailFrom, good.AvailTo, good.Promo, good.UnitPrice, good.GoodServices, good.GoodserviceID,
good.GoodCategoryID, good.GoodHist}
err := mer.DataStore.SaveDatabaseObject(&p)
if err != nil {
panic(err)
}
// render response
r.JSON(res, 200, p)
}
示例8: CreateCountry
// CreateCountry ... create new country
func (c CommonController) CreateCountry(res http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
r := render.New(render.Options{})
country := new(models.Country)
errs := binding.Bind(req, country)
if errs.Handle(res) {
r.JSON(res, 422, errs.Error())
return
}
bindingErr := country.Validate(req, errs)
if bindingErr != nil {
r.JSON(res, 422, bindingErr.Error())
return
}
// save to database
p := models.Country{c.BaseModel, country.ISOCode, country.Name, country.RegionStates, country.Language, country.LanguageID}
err := c.DataStore.SaveDatabaseObject(&p)
if err != nil {
fmt.Println(err.Error())
panic(err)
} else {
r.JSON(res, 200, p)
}
// render response
}
示例9: Generate
func (h *H) Generate(w http.ResponseWriter, req *http.Request) {
opts := &generateReq{}
if errs := binding.Bind(req, opts); errs.Handle(w) {
return
}
vopts := []string{}
for _, o := range opts.Options {
vopts = append(vopts, fmt.Sprintf("%s=%s", o.Key, o.Value))
}
var paths string
err := h.C.Call("generate", vopts, &paths)
if err != nil {
h.JSON400(w, errors.New("could not parse the response from veil, likely no options or an invalid payload"))
return
}
if paths == "" {
h.JSON400(w, errors.New("no payload was generated"))
return
}
fullDir := path.Dir(paths)
rootDir := path.Base(fullDir)
f := path.Base(paths)
httpath := path.Join(rootDir, f)
h.JSON(w, map[string]string{"result": httpath})
}
示例10: CreateCustomer
// CreateCustomer ... Add new customer
func (acct AccountController) CreateCustomer(res http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
r := render.New(render.Options{})
customer := new(models.Customer)
errs := binding.Bind(req, customer)
if errs.Handle(res) {
r.JSON(res, 422, errs.Error())
return
}
bindingErr := customer.Validate(req, errs)
if bindingErr != nil {
r.JSON(res, 422, bindingErr.Error())
return
}
p := models.Customer{acct.BaseModel, customer.Person, customer.PersonID, customer.CompanyEntites, customer.CompanyEntitesID, customer.CustomerType, customer.CustomerTypeID}
//p := models.User{acct.BaseModel, user.Realm, user.Username, user.Password, user.Credential, user.Challenges, user.Email, user.Emailverified, user.Verificationtoken,
// user.LogInCummulative, user.FailedAttemptedLogin, uuid.New(), user.PersonID, user.PhoneNum, user.VerifiedPhoneNum}
err := acct.DataStore.SaveDatabaseObject(&p)
if err != nil {
panic(err)
}
// render response
r.JSON(res, 200, p)
}
示例11: CreateLanguage
// CreateLanguage ... create new language
func (c CommonController) CreateLanguage(res http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
r := render.New(render.Options{})
language := new(models.Language)
errs := binding.Bind(req, language)
if errs.Handle(res) {
r.JSON(res, 422, errs.Error())
return
}
bindingErr := language.Validate(req, errs)
if bindingErr != nil {
r.JSON(res, 422, bindingErr.Error())
return
}
// save to database
p := models.Language{c.BaseModel, language.ISOCode, language.Name}
err := c.DataStore.SaveDatabaseObject(&p)
if err != nil {
panic(err)
}
// render response
r.JSON(res, 200, p)
}
示例12: CreateContact
// CreateContact ... add new contact to a person
func (c PersonController) CreateContact(res http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
r := render.New(render.Options{})
contact := new(models.Contacts)
errs := binding.Bind(req, contact)
if errs.Handle(res) {
r.JSON(res, 422, errs.Error())
return
}
bindingErr := contact.Validate(req, errs)
if bindingErr != nil {
r.JSON(res, 422, bindingErr.Error())
return
}
p := models.Contacts{
BaseModel: c.BaseModel,
PhoneNo: contact.PhoneNo,
PhoneNo2: contact.PhoneNo2,
PhoneNo3: contact.PhoneNo3,
Email: contact.Email,
Website: contact.Website,
FacebookID: contact.FacebookID,
PersonID: contact.PersonID,
CompanyEntitiesID: contact.CompanyEntitiesID}
err := c.DataStore.SaveDatabaseObject(&p)
if err != nil {
panic(err)
}
// render response
r.JSON(res, 200, p)
}
示例13: CreateAddress
// CreateAddress ... add new address to a person
func (c PersonController) CreateAddress(res http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
r := render.New(render.Options{})
address := new(models.Addresses)
errs := binding.Bind(req, address)
bs, _ := ioutil.ReadAll(req.Body)
if errs.Handle(res) {
c.Logger.Error(fmt.Sprintf("%s, %s", errs.Error(), string(bs)))
r.JSON(res, 422, errs.Error())
return
}
bindingErr := address.Validate(req, errs)
if bindingErr != nil {
r.JSON(res, 422, bindingErr.Error())
return
}
p := &models.Addresses{
BaseModel: c.BaseModel,
AddressType: address.AddressType,
HouseNo: address.HouseNo,
Street: address.Street,
Area: address.Area,
TownsID: address.TownsID,
RegionStateID: address.RegionStateID,
CountryID: address.CountryID,
PersonID: address.PersonID,
CompanyEntitiesID: address.CompanyEntitiesID}
err := c.DataStore.SaveDatabaseObject(p)
if err != nil {
panic(err)
}
c.Logger.Info(fmt.Sprintf("%v", &p))
r.JSON(res, 200, p)
}
示例14: pushHandler
// pushHandler 推送一個任務到隊列中
func pushHandler(w http.ResponseWriter, r *http.Request) {
httpTask := new(HttpTask)
errs := binding.Bind(r, httpTask)
if errs.Len() > 0 {
Response{W: w}.JSON("1704", "參數錯誤", errs)
return
}
job := Job{Job: "[email protected]", Data: httpTask}
jobStr, err := json.Marshal(job)
if err != nil {
Response{W: w}.JSON("1705", err.Error(), nil)
return
}
id, err := tube.Put(jobStr, 0, 0, 0)
if err != nil {
Response{W: w}.JSON("1706", err.Error(), nil)
return
}
Response{W: w}.JSON("0", "success", map[string]interface{}{
"id": id,
"job": job,
})
return
}
示例15: CreatePersonIDType
// CreatePersonIDType ... add new contact to a person
func (c PersonController) CreatePersonIDType(res http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
r := render.New(render.Options{})
personIDType := new(models.PersonIDType)
errs := binding.Bind(req, personIDType)
idTypes := models.IDType{}
if errs.Handle(res) {
r.JSON(res, 422, errs.Error())
return
}
bindingErr := personIDType.Validate(req, errs)
if bindingErr != nil {
r.JSON(res, 422, bindingErr.Error())
return
}
p := models.PersonIDType{
BaseModel: c.BaseModel,
PersonID: personIDType.PersonID,
IDType: personIDType.IDType,
IDNumber: personIDType.IDNumber,
DateIssued: personIDType.DateIssued,
ExpiryDate: personIDType.ExpiryDate,
ScannedPicture: personIDType.ScannedPicture,
IDTypes: idTypes}
err := c.DataStore.SaveDatabaseObject(&p)
if err != nil {
panic(err)
}
r.JSON(res, 200, p)
}