Skip to content

Instantly share code, notes, and snippets.

@andrewwatson
Created April 27, 2016 14:20
Show Gist options
  • Save andrewwatson/be5e82cafedb303b0b43e1a8f74f0420 to your computer and use it in GitHub Desktop.
Save andrewwatson/be5e82cafedb303b0b43e1a8f74f0420 to your computer and use it in GitHub Desktop.
Connect to Datastore from outside GAE
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
}
// HeavyPutter takes a ton of shit and puts something in datastore
func HeavyPutter(jsonKeyFile, projectID, entry string) error {
jsonKey, err := ioutil.ReadFile(jsonKeyFile)
if err != nil {
// log.Fatal(err)
return err
}
conf, err := google.JWTConfigFromJSON(
jsonKey,
datastore.ScopeDatastore,
)
if err != nil {
// log.Fatal(err)
return err
}
ctx := context.Background()
client, err := datastore.NewClient(ctx, projectID, cloud.WithTokenSource(conf.TokenSource(ctx)))
if err != nil {
// log.Fatal(err)
return err
}
logEntry := struct {
log string
}{
entry,
}
key := datastore.NewIncompleteKey(ctx, "LogEntry", nil)
_, putErr := client.Put(ctx, key, &logEntry)
if putErr != nil {
return putErr
}
return nil
}
// 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