google-app-engine - 在数据存储中写入请求的主体

标签 google-app-engine go

如何在数据存储中写入请求的主体?

在我的 func init() 中,我使用 gorilla mux 声明了我的路由器,因此如果我向 /add 发出 post 请求,我将需要向数据存储添加一些数据,但我才刚刚开始使用数据存储,所以我真的不知道该怎么做。

我已经声明了一个结构项

type Item Struct {
  ID int64
  Type string `json:type`
}

路由器将重定向到CItem函数

func CItem(w http.ResponseWriter, r *http.Request) { 
  var item Item
  data := json.NewDecoder(r.Body).Decode(&item)
  defer r.Body.Close()
  fmt.Fprintln(w, data)
}

但是,当我使用 paw 发出发布请求时,例如,我得到: 字面值 true 中的无效字符“y”(应为“r”)

或者使用 curl: curl -X POST -d "{\"type\":\"that\"}"http://localhost:8080/add

我该如何解决这个问题,接下来我需要做什么才能将我的数据存储在数据存储中,一个小示例会很好。

最佳答案

到目前为止,这是对您的代码的一些评论,以及一个显示如何存储实体的简单示例:

type Item Struct {
  ID int64
  Type string `json:"type"` // <-- quotes needed
}

func CItem(w http.ResponseWriter, r *http.Request) { 
   var item Item
   err := json.NewDecoder(r.Body).Decode(&item) // <-- decode returns an error, not data
   if err != nil {
        http.Error(w, err.Error(), 400)
        return
   }
   // defer r.Body.Close()  <-- no need to close request body
   fmt.Fprintln(w, item) // <-- print the decoded item

   c := appengine.NewContext(r)
   key, err := datastore.Put(c, datastore.NewIncompleteKey(c, "citem", nil), &item)
   if err != nil {
       http.Error(w, err.Error(), http.StatusInternalServerError)
       return
   }
   fmt.Fprintln(w, "key is", key)
}

关于google-app-engine - 在数据存储中写入请求的主体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26494804/

相关文章:

python - App Engine Python 身份验证自定义重定向

maven - 使用 Maven 和模块缓慢构建 Appengine

go - 我在 golang 中使用 postgres 数据库,我试图返回连接对象,但我不知道返回类型连接对象

node.js - 如何仅将受影响的 nx 服务部署到 GCP APP Engine

python - App Engine 配额中的电子邮件管理员是什么?

更新到 docker 版本 19.03.2 后,Go net.Listen() 无法绑定(bind)到 docker 服务端口

synchronization - 同步 channel ?

mongodb - 如何检查集合是否存在 MongoDB Golang

json 解码/解码在 json 中没有按预期工作

python - 谷歌应用引擎 : Give arguments to a script from URL handler?