Go with GAE saved an object to datastore. when getting it back, the object has empty members

荒凉一梦 提交于 2019-12-20 03:52:52

问题


I am trying to learn Go with GAE. I have created 2 handlers. One for saving an object to datastore and the other retrieve it and output to screen. The problem is that when i retrieve the UserAccount object from datastore, every values inside the object are gone.

Any help would be appreciate.

Output:

a/c count: 2 val: core.UserAccount{idString:"", deviceId:""} val: core.UserAccount{idString:"", deviceId:""}

type UserAccount struct {
    idString string
    deviceId string
}

func create_account(w http.ResponseWriter, r *http.Request) {

    c := appengine.NewContext(r)

        idstr := "ABCDEFGH"
        devId := r.FormValue("deviceId")

        newAccount := UserAccount{ idString: idstr, deviceId: devId,}

        key := datastore.NewIncompleteKey(c, "UserAccount", nil)
        _, err := datastore.Put(c, key, &newAccount)
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
    }

    fmt.Fprintf(w, "val: %#v \n", newAccount)
}

func get_info(w http.ResponseWriter, r *http.Request) {
    c := appengine.NewContext(r)

    q := datastore.NewQuery("UserAccount")
    accounts := make([]UserAccount, 0, 10)
    if _, err := q.GetAll(c, &accounts); err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    fmt.Fprintf(w, "a/c count: %v \n", len(accounts))

    for i := 0; i < len(accounts); i++ {
        fmt.Fprintf(w, "val: %#v \n", accounts[i])
    }
}

回答1:


If the datastore API uses reflection, which I presume it does, it cannot access struct fields that aren't exported, i.e. field names that do not begin with a capital letter.

Export them and it should work.



来源:https://stackoverflow.com/questions/16683495/go-with-gae-saved-an-object-to-datastore-when-getting-it-back-the-object-has-e

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!