本文整理汇总了Golang中github.com/ant0ine/go-json-rest/rest.Request.DecodeJsonPayload方法的典型用法代码示例。如果您正苦于以下问题:Golang Request.DecodeJsonPayload方法的具体用法?Golang Request.DecodeJsonPayload怎么用?Golang Request.DecodeJsonPayload使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类github.com/ant0ine/go-json-rest/rest.Request
的用法示例。
在下文中一共展示了Request.DecodeJsonPayload方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: HandleOwnIdentitiesPost
func HandleOwnIdentitiesPost(w rest.ResponseWriter, r *rest.Request) {
fmt.Println("POST /identities")
var identity Identity = Identity{}
err := r.DecodeJsonPayload(&identity)
if err != nil {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(422) // unprocessable entity
w.WriteJson("nop")
} else {
if identity.Hostname == "" {
clientError(w, "Missing hostname")
return
}
identity, err = FetchIdentity(identity.GetURI())
fmt.Println("ER", err)
if err != nil {
clientError(w, "Could not retrieve identity")
return
}
_, err = db.C("identities").UpsertId(identity.ID, &identity)
if err != nil {
fmt.Println(err)
internal(w, "Could not upsert identity")
return
}
w.WriteJson(identity)
}
}
示例2: StopPgpool
func StopPgpool(w rest.ResponseWriter, r *rest.Request) {
logit.Info.Println("StopPgpool called")
response := StopPgpoolResponse{}
req := StopPgpoolRequest{}
err := r.DecodeJsonPayload(&req)
if err != nil {
logit.Error.Println(err.Error())
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
var cmd *exec.Cmd
cmd = exec.Command("stop-pgpool.sh", req.Path)
var out bytes.Buffer
var stderr bytes.Buffer
cmd.Stdout = &out
cmd.Stderr = &stderr
err = cmd.Run()
if err != nil {
logit.Error.Println(err.Error())
rest.Error(w, err.Error(), 400)
return
}
response.Output = out.String()
response.Status = "OK"
w.WriteJson(&response)
}
示例3: PostUser
func (api *Api) PostUser(w rest.ResponseWriter, r *rest.Request) {
user := User{}
err := r.DecodeJsonPayload(&user)
if err != nil {
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
lastInsertId, err := api.DB.Query("INSERT INTO " + TABLENAME + "(" + COLNAME + ") OUTPUT Inserted.ID VALUES('" + user.Name + "')")
if err != nil {
fmt.Println(err)
return
}
if lastInsertId.Next() {
var id int
if err := lastInsertId.Scan(&id); err != nil {
log.Fatal(err)
}
user.Id = id
} else {
rest.NotFound(w, r)
return
}
if err := lastInsertId.Err(); err != nil {
log.Fatal(err)
}
w.WriteJson(&user)
}
示例4: Translate
func Translate(w rest.ResponseWriter, r *rest.Request) {
request := &RequestObject{}
r.DecodeJsonPayload(request)
c := translator.Translate(request.Text, request.Lang)
w.WriteJson(c)
}
示例5: loginUser
func loginUser(w rest.ResponseWriter, r *rest.Request, db neutrino.DbService) {
var u bson.M
if err := r.DecodeJsonPayload(&u); err != nil {
RestError(w, err)
return
}
existingUser, err := db.FindId(u["email"].(string), nil)
if err != nil {
RestError(w, err)
return
}
err = bcrypt.CompareHashAndPassword(existingUser["password"].([]byte), []byte(u["password"].(string)))
if err != nil {
RestError(w, err)
return
}
token := jwt.New(jwt.GetSigningMethod("HS256"))
token.Claims["user"] = u["email"].(string)
token.Claims["expiration"] = time.Now().Add(time.Minute + 60).Unix()
tokenStr, err := token.SignedString([]byte(""))
if err != nil {
RestError(w, err)
return
}
w.WriteJson(map[string]string{"token": tokenStr})
}
示例6: PostCreateGame
func (api *ChessApi) PostCreateGame(res rest.ResponseWriter, req *rest.Request) {
user := getUser(req)
type createBody struct {
Color game.Color `json:"Color"`
}
body := new(createBody)
err := req.DecodeJsonPayload(body)
if err != nil || body.Color == "" {
idx := rand.Perm(2)[0]
body.Color = []game.Color{game.White, game.Black}[idx]
}
ok, msg := api.Commands.ExecCommand(
commands.CreateGame, user.Uuid, map[string]interface{}{
"color": body.Color,
},
)
if ok {
res.WriteHeader(http.StatusAccepted)
res.WriteJson("ok")
} else {
res.WriteHeader(http.StatusBadRequest)
res.WriteJson(map[string]string{"error": msg})
}
}
示例7: DockerStop
func DockerStop(w rest.ResponseWriter, r *rest.Request) {
logit.Info.Println("DockerStop called")
req := DockerStopRequest{}
err := r.DecodeJsonPayload(&req)
if err != nil {
logit.Error.Println(err.Error())
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
docker, err3 := dockerapi.NewClient("unix://var/run/docker.sock")
if err3 != nil {
logit.Error.Println("can't get connection to docker socket")
rest.Error(w, err3.Error(), http.StatusInternalServerError)
return
}
err3 = docker.StopContainer(req.ContainerName, 10)
if err3 != nil {
logit.Error.Println("can't stop container " + req.ContainerName)
rest.Error(w, err3.Error(), http.StatusInternalServerError)
return
}
var response DockerStopResponse
response.Output = "success"
w.WriteJson(&response)
}
示例8: PutApplication
// PutApplication ...
func PutApplication(w rest.ResponseWriter, r *rest.Request) {
accountID, applicationName, err := applicationParams(r)
if err != nil {
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
rc := &Application{}
if err := r.DecodeJsonPayload(rc); err != nil {
if err != rest.ErrJsonPayloadEmpty {
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
b := GetBase(r)
application, err := b.NewApplication(accountID, applicationName)
if err != nil {
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
_, err = b.NewQueue(accountID, applicationName, "default", nil, 0)
if err != nil {
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteJson(NewApplicationFromModel(application))
}
示例9: handleReload
func (srv *Server) handleReload(res rest.ResponseWriter, req *rest.Request) {
if srv.ReloadDisabled {
srv.logger.Printf("client was denied reload\n")
rest.Error(res, "reload disabled", 400)
return
}
srv.logger.Printf("client requested reload\n")
var err error
if req.ContentLength > 0 {
data := make(map[string]interface{})
if err = req.DecodeJsonPayload(&data); err != nil {
srv.logger.Printf("client provided invalid context\n")
rest.Error(res, err.Error(), 400)
return
}
err = srv.hooks.Reload(data)
} else {
err = srv.hooks.Reload(nil)
}
if err == nil {
res.WriteJson(&success{"reloaded service"})
} else {
rest.Error(res, err.Error(), 500)
}
}
示例10: PostSaveDoc
// PostSaveDoc uses save to save a document
func PostSaveDoc(w rest.ResponseWriter, r *rest.Request) {
id := r.PathParam("id")
collection := r.PathParam("collection")
_, ok := r.Env["JWT_PAYLOAD"]
// Make sure that the user is allowed to save this
if ok {
// Now we know that auth is enabled so
_, ok := r.Env["JWT_PAYLOAD"].(map[string]interface{})["backend"]
if !ok {
// FIXME: Add call to access control service
rest.Error(w, "Only backend services can call this service", http.StatusInternalServerError)
return
}
}
var doc map[string]interface{}
err := r.DecodeJsonPayload(&doc)
if err != nil {
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if id != "undefined" {
doc["_id"] = id
}
info, err := save.Save(collection, doc)
if err != nil {
log.Println(err)
rest.Error(w, "Could not save", http.StatusInternalServerError)
return
}
w.WriteJson(info)
}
示例11: PostMsg
func (mqmsg MqMsg) PostMsg(w rest.ResponseWriter, r *rest.Request) {
//msg := message.NewMsg()
mqid, err := strconv.Atoi(r.PathParam("mqid"))
if err != nil {
log.Log("info", err.Error(), nil)
}
mq, ok := DefaultMM[mqid]
if ok {
mqmsg.Msg.MQid = mqid
mqmsg.Msg.Generator = mq.Owner
mqmsg.Msg.MsgId = Counter
Counter++
r.DecodeJsonPayload(mqmsg.Msg)
fmt.Println(mqmsg.Msg.Value)
//fmt.Println("post msg")
mq.Lock()
mq.AddMsg(*mqmsg.Msg)
mq.Unlock()
//w.WriteJson(mqmsg.Msg)
w.WriteJson(map[string]string{"1016": "post success"})
} else {
w.WriteJson(map[string]string{"1010": "mq not running"})
}
}
示例12: CreateUser
func (api *Api) CreateUser(w rest.ResponseWriter, r *rest.Request) {
user := common.User{}
r.DecodeJsonPayload(&user)
for _, name := range api.Config.ProhibitedNames {
if user.Name == name {
rest.Error(w, "Invalid user name", 400)
return
}
}
if strings.TrimSpace(user.Name) == "" {
rest.Error(w, "Username is empty", 400)
return
}
if len(strings.TrimSpace(user.Password)) <= api.Config.PasswordMinLength {
rest.Error(w, "Password is too short", 400)
return
}
if api.DB.Where("name = ?", user.Name).First(&user).RecordNotFound() {
user.Id = 0
hash := api.GetPasswordHash(user.Name, user.Password)
user.Password = hex.EncodeToString(hash)
api.DB.Save(&user)
user.Password = ""
w.WriteJson(user)
return
}
rest.Error(w, "User with the same name already exists", 400)
}
示例13: PostContact
// PostContact add new contact
func (a *Api) PostContact(w rest.ResponseWriter, r *rest.Request) {
log.Println("POST")
contact := Contact{Weight: 20}
err := r.DecodeJsonPayload(&contact)
if err != nil {
log.Println(err)
rest.Error(w, "Data error", http.StatusInternalServerError)
return
}
// Start a transaction
tx := a.Db.Begin()
_, err = tx.Save(&contact)
if err != nil {
log.Println(err)
rest.Error(w, "Failed", http.StatusInternalServerError)
return
}
// Commit changes
err = tx.Commit()
if err != nil {
log.Println(err)
rest.Error(w, "Failed", http.StatusInternalServerError)
return
}
w.WriteJson(&contact)
}
示例14: Register
// Register Route
// @route Post /register
func Register(w rest.ResponseWriter, r *rest.Request) {
account := registerPayload{}
if err := r.DecodeJsonPayload(&account); err != nil {
rest.Error(w, err.Error(), http.StatusBadRequest)
return
}
log.Printf("register: %v", account.Email)
user, err := model.Register(account.Email, account.Password)
if err != nil {
if err.Error() == "account conflict" {
rest.Error(w, "Account is already registered", http.StatusConflict)
return
}
if err.Error() == "passwords must be 8 characters or greater" {
rest.Error(w, "Passwords must be 8 characters or greater", http.StatusBadRequest)
return
}
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
token, err := model.GrantToken(account.Email)
if err != nil {
rest.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
w.WriteJson(registerResponse{
Email: user.Email,
Token: token,
})
}
示例15: StatusUpdate
// StatusUpdate called by backup jobs as they execute
func StatusUpdate(w rest.ResponseWriter, r *rest.Request) {
request := TaskStatus{}
err := r.DecodeJsonPayload(&request)
if err != nil {
logit.Error.Println(err.Error())
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
var dbConn *sql.DB
dbConn, err = util.GetConnection(CLUSTERADMIN_DB)
if err != nil {
logit.Error.Println(err.Error())
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer dbConn.Close()
//logit.Info.Println("StatusUpdate called")
err = UpdateStatus(dbConn, &request)
if err != nil {
logit.Error.Println(err.Error())
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
response := StatusUpdateResponse{}
response.Output = "ok"
w.WriteJson(&response)
}