从字符串创建Google App Engine数据存储键的方法

huangapple go评论63阅读模式
英文:

Making a Google App Engine datastore key from a string

问题

我正在将一个实体的"id"作为字符串传递到URL中,例如:

..../foo/234565

我想在以下查询中使用这个id:

//...我有一些代码从URL中获取stringId,并且我验证了它的工作
stringId = ....
theKey, err := datastore.DecodeKey(stringId)
q := datastore.NewQuery("Foo").Filter("__key__ =", theKey)

我得到的错误是:

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

有没有一种简单的方法将stringId转换为"Key"类型?

英文:

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

得分: 3

c := appengine.NewContext(r)
//从提交的表单中获取实体ID。转换为int64
entity_id := r.FormValue("entity_id")
entity_id_int, err := strconv.ParseInt(entity_id, 10, 64)
if err != nil {
fmt.Fprint(w, "无法解析键")
return;
}
//根据Kind和实体ID(通过HTTP请求参数传递给我们)创建一个数据存储键。
key := datastore.NewKey(c, kind, "", entity_id_int, nil)
//加载此键表示的实体。
//我们必须先声明变量,然后进行Get操作,以便数据存储了解表示实体的结构。
var entity CustomStruct
datastore.Get(c, key, &entity)

英文:
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)

huangapple
  • 本文由 发表于 2014年10月28日 01:56:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/26593806.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定