2013-01-05 57 views
1

用通過GET參數傳遞的鍵獲取實體

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

我想問一下如何:

  1. 解碼並轉換成「關鍵」的*datastore.Key
  2. 並用它來獲得一個實體。

感謝您的幫助!

+0

您應該爲此問題添加更多標籤。 (Go and gae-datastore) – Testuser

+0

如果你能向我們展示你之前試過的東西,這也很好:)(這是一個簡單的問題,很容易解決) – Testuser

回答

6

第一:你應該考慮哪個包你需要這種情況。由於您正嘗試從URL中讀取GET的值,因此您可能需要使用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 
    } 
} 
+0

感謝您的幫助。很快就有人得到答案。 – sagit

+0

@ user1949730如果他們解決了您的問題,請接受答案爲「接受」。 (http://stackoverflow.com/faq#howtoask) – Testuser

+1

您應該檢查從DecodeKey返回的錯誤(呃,如果操作可能失敗,您應該總是檢查錯誤,當您解碼用戶輸入時肯定是這種情況)。 –