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

sag*_*git 1 google-app-engine go google-cloud-datastore

我有

http://localhost:8080/?key=ahFkZXZ-ZGV2LWVkdW5hdGlvbnIOCxIIVXNlckluZm8YLAw
Run Code Online (Sandbox Code Playgroud)

我想询问如何:

  1. 解码并将"密钥"转换为 *datastore.Key
  2. 并用它来获得一个实体.

谢谢你的帮助!

Tes*_*ser 6

第一:你应该考虑一下你需要哪些软件包.因为你正试图GETURL你需要的函数中读取一个函数net/http.特别是:FormValue(key string)退货GETPOST参数.

第二:现在打开appengine/datastore文档并查找执行以下操作的函数:

现在这很简单:

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
    }
}
Run Code Online (Sandbox Code Playgroud)