如何在数据存储中写入请求的主体?
在我的 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/