无法在 google 应用引擎数据存储中插入动态属性

Unable to insert dynamic properties in go on the google app engine datastore

我正在努力从这个 post

无法将数据插入数据存储,它只是在创建 ID

import (
    "log"
    "net/http"
    "time"

    "github.com/julienschmidt/httprouter"
    "google.golang.org/appengine"
    "google.golang.org/appengine/datastore"
)

type DynEnt map[string]interface{}

func (d *DynEnt) Load(props []datastore.Property) error {
    // Note: you might want to clear current values from the map or create a new map
    for _, p := range props {
        (*d)[p.Name] = p.Value
    }
    return nil
}

func (d *DynEnt) Save() (props []datastore.Property, err error) {
    for k, v := range *d {
        props = append(props, datastore.Property{Name: k, Value: v})
    }
    return nil, nil
}

//GetAccountHandler is to
func GetAccountHandler(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {

    c := appengine.NewContext(r)

    d := DynEnt{"email": "me@myhost.com", "time": time.Now()}
    log.Println("d=>", d)
    log.Println("&d=>", &d)
    k := datastore.NewIncompleteKey(c, "DynEntity", nil)
    key, err := datastore.Put(c, k, &d)
    log.Fatalf("%v %v", key, err)

}

有错字,Save()末尾的return值是copy/paste错误(来自频道版)。正确的版本是:

func (d *DynEnt) Save() (props []datastore.Property, err error) {
    for k, v := range *d {
        props = append(props, datastore.Property{Name: k, Value: v})
    }
    return
}

请注意,return 后没有指定任何值,因为使用了命名结果参数。指定 nil, nil 不会 return 在 Save().

内构建的切片

您还可以在处理程序的末尾调用 log.Fatalf(),这会终止您的应用程序。请尝试 log.Printf()