Created
April 26, 2016 19:56
-
-
Save andrewwatson/228bc1b1d3f803670a7dc69ed7655013 to your computer and use it in GitHub Desktop.
Google App Engine Datastore Adaptor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package storage | |
import ( | |
"io/ioutil" | |
"golang.org/x/net/context" | |
"golang.org/x/oauth2/google" | |
"google.golang.org/cloud" | |
"google.golang.org/cloud/datastore" | |
) | |
var () | |
// Adaptor is a structure that adapts | |
type Adaptor struct { | |
jsonKeyPath string | |
projectID string | |
client *datastore.Client | |
} | |
// CreateAdaptor returns a datastore client built with the right authorization | |
func CreateAdaptor(jsonKeyFile, projectID string) (*Adaptor, error) { | |
jsonKey, err := ioutil.ReadFile(jsonKeyFile) | |
if err != nil { | |
// log.Fatal(err) | |
return nil, err | |
} | |
conf, err := google.JWTConfigFromJSON( | |
jsonKey, | |
datastore.ScopeDatastore, | |
) | |
if err != nil { | |
// log.Fatal(err) | |
return nil, err | |
} | |
ctx := context.Background() | |
client, err := datastore.NewClient(ctx, projectID, cloud.WithTokenSource(conf.TokenSource(ctx))) | |
if err != nil { | |
// log.Fatal(err) | |
return nil, err | |
} | |
adaptor := Adaptor{ | |
jsonKeyFile, | |
projectID, | |
client, | |
} | |
// Use the client (see other examples). | |
return &adaptor, nil | |
} | |
// LogEntry logs entries using a valid client | |
func (a *Adaptor) LogEntry(entry string) error { | |
ctx := context.Background() | |
logEntry := struct { | |
log string | |
}{ | |
entry, | |
} | |
key := datastore.NewIncompleteKey(ctx, "LogEntry", nil) | |
_, putErr := a.client.Put(ctx, key, &logEntry) | |
if putErr != nil { | |
return putErr | |
} | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment