dqsvnsad79721 2016-05-20 13:22
浏览 63
已采纳

使用Go从AppEngine上的Google Could Datastore读取数据

Here is a screen shot of the entities I'm trying to read.

Entities

Here is my go code:

package readfromgcd

import (
        "net/http"
        "appengine"
        "appengine/datastore"
        "fmt"
)

type person struct {
    firstname string
    lastname string
}

func init () {
    http.HandleFunc("/", readpeople)
}

func readpeople (w http.ResponseWriter, r *http.Request)  {
    c := appengine.NewContext(r)
    q := datastore.NewQuery("person")
    people := make([]person, 0, 20)
    if _, err := q.GetAll(c, &people); err !=nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
    }
    fmt.Fprint(w, "Hello world!")
}

I get the following result: datastore: cannot load field "firstName" into a "readpeople.person": no such struct field

Here is a screenshot. result

This code does not show doing anything with this data. I wanted to limit this post to the retrieval. I must be missing something simple. Where have I gone wrong? Thanks in advance for any help.

  • 写回答

1条回答 默认 最新

  • dongsu1951 2016-05-20 13:25
    关注

    Property names in your datastore do not match field names in your Go struct person. For example in your datastore person has property firstName but your struct has field firstname.

    So first thing is to make them match; or if you want to use different names in your Go struct, use struct tags to define the mappings.

    Another important thing: you have to export your type and its fields in order so that the datastore package will be able to load data into it using reflection. So you have to start your type name and its fields with uppercase letters:

    type Person struct {
        FirstName string `datastore:"firstName"`
        LastName string  `datastore:"lastName"`
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?