Making a Google App Engine datastore key from a string

為{幸葍}努か 提交于 2019-12-10 17:29:57

问题


I'm passing an entities "id" as a string on a URL, for example:

..../foo/234565

I want to use the id in the following query:

//...i hace some code that gets stringId from the URL, and I verified that it works
stringId = ....
theKey, err := datastore.DecodeKey(stringId)
q := datastore.NewQuery("Foo").Filter("__key__ =", theKey)

The error I'm getting:

proto: can't skip unknown wire type 7 for datastore.Reference

Is there a simple way to convert stringId into a "Key"?


回答1:


c := appengine.NewContext(r)
//Retrieve the entity ID from the submitted form. Convert to an int64
entity_id := r.FormValue("entity_id")
entity_id_int, err := strconv.ParseInt(entity_id, 10, 64) 
if err != nil {
  fmt.Fprint(w, "Unable to parse key")
  return;
}
//We manufacture a datastore key based on the Kind and the 
//entity ID (passed to us via the HTTP request parameter.
key := datastore.NewKey(c, kind, "", entity_id_int, nil)
//Load the Entity this key represents.
//We have to state the variable first, then conduct the Get operation 
//so the datastore understands the struct representing the entity.
var entity CustomStruct
datastore.Get(c, key, &entity)


来源:https://stackoverflow.com/questions/26593806/making-a-google-app-engine-datastore-key-from-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!