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

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

Get an entity by a key passed via GET parameter

问题

我有

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

我想问一下如何:

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

谢谢你的帮助!

英文:

I have

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文档,并找到以下功能:

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

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:

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
    }
}

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:

确定