How can I write the body of a request in datastore?
In my func init() I declare my router using gorilla mux, so that if I do a post request to /add
I will need to add some data to datastore, but I am just starting with datastore so I don't really know how to.
I have declared a struct item
type Item Struct {
ID int64
Type string `json:type`
}
The router will redirect to the function 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)
}
But when I do a post request using paw
for example I get: invalid character 'y' in literal true (expecting 'r')
Or using curl: curl -X POST -d "{\"type\": \"that\"}" http://localhost:8080/add
How can I fix this, and what do I need to do next to store my data in datastore a small example will be nice.
Here are some comments on your code so far and a quick example showing how to store the entity:
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)
}
So you'll have a class describing the request and another describing the NDB/DB entity. You'll have to manually map the data points from the request to the datastore object and then save it