通过通过GET参数传递的键获取实体

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

Get an entity by a key passed via GET parameter

问题

我有

  1. http://localhost:8080/?key=ahFkZXZ-ZGV2LWVkdW5hdGlvbnIOCxIIVXNlckluZm8YLAw

我想问一下如何:

  1. 解码并将“key”转换为*datastore.Key
  2. 并使用它来获取一个实体。

谢谢你的帮助!

英文:

I have

  1. http://localhost:8080/?key=ahFkZXZ-ZGV2LWVkdW5hdGlvbnIOCxIIVXNlckluZm8YLAw

I would like to ask on how to:

  1. Decode and convert the "key" to a *datastore.Key
  2. And use it to get an entity.

Thanks for your help!

答案1

得分: 6

首先:你应该考虑一下你需要哪些包。由于你试图从URL中读取一个GET值,你可能需要net/http中的一个函数。
特别是:FormValue(key string)返回GETPOST参数。

其次:现在打开appengine/datastore文档,并找到以下功能:

现在这是一个非常简单的事情:

  1. func home(w http.Response, r *http.Request) {
  2. c := appengine.NewContext(r)
  3. // 从URL中获取键
  4. keyURL := r.FormValue("key")
  5. // 解码键
  6. key, err := datastore.DecodeKey(keyURL)
  7. if err != nil { // 无法解码键
  8. // 进行一些错误处理
  9. http.Error(w, err.Error(), http.StatusInternalServerError)
  10. return
  11. }
  12. // 获取键并将其加载到"data"中
  13. var data Data
  14. err = datastore.Get(c, key, data)
  15. if err != nil { // 无法找到实体
  16. // 进行一些错误处理
  17. http.Error(w, err.Error(), http.StatusInternalServerError)
  18. return
  19. }
  20. }
英文:

First: You should think about which packages you need this case. Since you're trying to read a GET value from a URL you need probably a function from net/http.
In particular: FormValue(key string) returns GET and POST parameters.

Second: Now open the appengine/datastore documentation and find functions which do the following:

Now it's a really easy thing:

  1. func home(w http.Response, r *http.Request) {
  2. c := appengine.NewContext(r)
  3. // Get the key from the URL
  4. keyURL := r.FormValue("key")
  5. // Decode the key
  6. key, err := datastore.DecodeKey(keyURL)
  7. if err != nil { // Couldn't decode the key
  8. // Do some error handling
  9. http.Error(w, err.Error(), http.StatusInternalServerError)
  10. return
  11. }
  12. // Get the key and load it into "data"
  13. var data Data
  14. err = datastore.Get(c, key, data)
  15. if err != nil { // Couldn't find the entity
  16. // Do some error handling
  17. http.Error(w, err.Error(), http.StatusInternalServerError)
  18. return
  19. }
  20. }

huangapple
  • 本文由 发表于 2013年1月5日 18:43:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/14170985.html
匿名

发表评论

匿名网友

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

确定