Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.