LoginSignup
2
1

More than 5 years have passed since last update.

gae/go datastoreからデータをmapで簡単にサクッと取得する

Posted at

datastoreからmap[string]interface{}でサクッとデータを取りたい時に、便利なので共有します。

コードに間違いなどありましたら、指摘してください



import (
    "google.golang.org/appengine/datastore"
    "context"
)

func GetMap(ctx context.Context, key *datastore.Key) (map[string]interface{}, error) {
    res := map[string]interface{}{}
    list := &datastore.PropertyList{}
    err := datastore.Get(ctx, key, list)
    if err != nil {
        return nil, err
    }
    for _, v := range *list {
        if v.Multiple {
            switch t := res[v.Name].(type) {
            case nil:
                res[v.Name] = []interface{}{v.Value}
            case []interface{}:
                res[v.Name] = append(t, v.Value)
            }
            continue
        }
        res[v.Name] = v.Value
    }
    return res, nil
}



2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1