简体   繁体   中英

Reading data from Google Could Datastore on AppEngine with Go

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM