我最近在使用 AppEngine,遇到了以下代码的问题,其中写入数据存储的唯一值似乎是日期。我花了一段时间思考这个问题,发现只需将结构中的第一个字符大写即可修复它!
我想知道是否有其他人遇到过这个问题并知道为什么我无法在数据存储的 Golang 结构中使用小写成员名称?我认为这可能是 Google AppEngine 处理结构写入方式的一个错误。
这是问题代码:
package main
import (
"fmt"
"net/http"
"time"
"appengine"
"appengine/datastore"
)
/* This is the problem struct */
type storeVal struct {
firstName string //FirstName works
lastName string //LastName works
email string //Email works
password string //Password works
Date time.Time
}
func init() {
http.HandleFunc("/", handle)
http.ListenAndServe(":8080", nil)
}
func handle(w http.ResponseWriter, r *http.Request) {
c := appengine.NewContext(r)
/* Write values to DataStore */
e1 := storeVal{
firstName: "Bob", //FirstName works
lastName: "Smith", //lastName works
email: "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="92f0fdf0bce1fffbe6fad2e6f7e1e6bcf1fdff" rel="noreferrer noopener nofollow">[email protected]</a>", //Email works
password: "password!", //Password works
Date: time.Now(),
}
key := datastore.NewIncompleteKey(c, "storeVal", nil)
_, err := datastore.Put(c, key, &e1)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fmt.Fprintf(w, "successfully added {firstName: '%s', lastName: '%s', email: '%s', password: '%s'}", e1.firstName, e1.lastName, e1.email, e1.password)
/* Read values back in. */
q := datastore.NewQuery("storeVal").
Filter("firstName =", "Bob").
Filter("lastName =", "Smith").
Order("-Date")
var storeVals []storeVal
_, err2 := q.GetAll(c, &storeVals)
if err2 != nil {
http.Error(w, err2.Error(), http.StatusInternalServerError)
return
}
if (len(storeVals) == 0) {
fmt.Printf("No results.");
return
}
e2 := storeVals[0]
fmt.Fprintf(w, "successfully grabbed {firstName: '%s', lastName: '%s', email: '%s', password: '%s', uaprem: '%s'}", e2.firstName, e2.lastName, e2.email, e2.password)
}
最佳答案
这与Go如何处理“公共(public)”和“私有(private)”概念有关。
要导出,您确实需要大写的字段名称。 This可以帮助解释...它与 JSON 相关,但它适用于此处,因为这两种情况都需要从结构中导出数据。
这来自Eager blog post on Go and JSON ,我发现这很有帮助:
The Field Name
As you might know, Go requires all exported fields to start with a capitalized letter. It’s not common to use that style in JSON however. We use the tag to let the parser know where to actually look for the value.
You can see an example of that in the example above, but as a refresher this is what it looks like:
type MyStruct struct { SomeField string `json:"some_field"` }
关于google-app-engine - GoLang App Engine 结构名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31896278/