4

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"?

3
  • Side comment: the datastore query looks odd: you can just use datastore.Get() on a key. Commented Oct 27, 2014 at 18:38
  • Where did the ID originate? Did it come from a call to cloud.google.com/appengine/docs/go/datastore/…? Commented Oct 27, 2014 at 18:39
  • 1
    To be very clear: datastore.DecodeKey() only works on the values produced by Key.Encode(). It appears from the content you've shown us so far that you've just plugged in a string value containing the entity name, a slash, and an ID with the hope that it would decode. But it shouldn't, according to the documentation: datastore.DecodeKey() expects a specific serialization format that's exclusive to Key.Encode(). Commented Oct 27, 2014 at 18:53

1 Answer 1

3
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)
Sign up to request clarification or add additional context in comments.

3 Comments

You should also explain in this answer why what you tried earlier didn't work; otherwise, there is no context as to why this approach works while the original approach broke.
I don't know why what I was trying did not work, but I think you answered it in your comments above, which I really appreciate! You were right, I was only using a simple string, not a value produced by Key.Encode()
Yup, that's what I suspected. I'm glad you solved your problem! If you can incorporate that understanding into your answer, it would make the answer significantly better. It will help others from making the same mistake. If you don't have time, let us know, and someone can edit in the explanatory text in your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.