英文:
Get an entity by a key passed via GET parameter
问题
我有
http://localhost:8080/?key=ahFkZXZ-ZGV2LWVkdW5hdGlvbnIOCxIIVXNlckluZm8YLAw
我想问一下如何:
- 解码并将“key”转换为
*datastore.Key
- 并使用它来获取一个实体。
谢谢你的帮助!
英文:
I have
http://localhost:8080/?key=ahFkZXZ-ZGV2LWVkdW5hdGlvbnIOCxIIVXNlckluZm8YLAw
I would like to ask on how to:
- Decode and convert the "key" to a
*datastore.Key
- And use it to get an entity.
Thanks for your help!
答案1
得分: 6
首先:你应该考虑一下你需要哪些包。由于你试图从URL中读取一个GET
值,你可能需要net/http
中的一个函数。
特别是:FormValue(key string)
返回GET
和POST
参数。
其次:现在打开appengine/datastore
文档,并找到以下功能:
- 将
string
解码为*datastore.Key
(DecodeKey(encoded string)) - 从数据存储中获取指定的键(Get(c appengine.Context, key *Key, dst interface{}))
现在这是一个非常简单的事情:
func home(w http.Response, r *http.Request) {
c := appengine.NewContext(r)
// 从URL中获取键
keyURL := r.FormValue("key")
// 解码键
key, err := datastore.DecodeKey(keyURL)
if err != nil { // 无法解码键
// 进行一些错误处理
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// 获取键并将其加载到"data"中
var data Data
err = datastore.Get(c, key, data)
if err != nil { // 无法找到实体
// 进行一些错误处理
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
英文:
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:
- Decode a
string
to a*datastore.Key
(DecodeKey(encoded string)) - Get a specified key from the datastore (Get(c appengine.Context, key *Key, dst interface{}))
Now it's a really easy thing:
func home(w http.Response, r *http.Request) {
c := appengine.NewContext(r)
// Get the key from the URL
keyURL := r.FormValue("key")
// Decode the key
key, err := datastore.DecodeKey(keyURL)
if err != nil { // Couldn't decode the key
// Do some error handling
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Get the key and load it into "data"
var data Data
err = datastore.Get(c, key, data)
if err != nil { // Couldn't find the entity
// Do some error handling
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论