Skip to content

Instantly share code, notes, and snippets.

@andrewwatson
Created April 26, 2016 19:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewwatson/228bc1b1d3f803670a7dc69ed7655013 to your computer and use it in GitHub Desktop.
Save andrewwatson/228bc1b1d3f803670a7dc69ed7655013 to your computer and use it in GitHub Desktop.
Google App Engine Datastore Adaptor
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