Skip to content

Instantly share code, notes, and snippets.

@karalabe
Last active March 31, 2021 21:23
Show Gist options
  • Save karalabe/725ff60c50b1f1295186 to your computer and use it in GitHub Desktop.
Save karalabe/725ff60c50b1f1295186 to your computer and use it in GitHub Desktop.
Simplified cloud context creation
// Contains the App Engine specific cloud utility implementations.
// +build appengine
package cloud
import (
"net/http"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"appengine"
"appengine/urlfetch"
)
// Authentication context specific to Google App Engine.
type AuthContext appengine.Context
// NewClient creates an authenticated App Engine HTTP client to access Google
// services.
func NewClient(ctx AuthContext, scopes ...string) *http.Client {
return &http.Client{
Transport: &oauth2.Transport{
Source: google.AppEngineTokenSource(appengine.Context(ctx), scopes...),
Base: &urlfetch.Transport{
Context: appengine.Context(ctx),
},
},
}
}
// Contains the standalone specific cloud utility implementations.
// +build !appengine
package cloud
import (
"net/http"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"golang.org/x/oauth2/jwt"
)
// Authentication context specific to service accounts.
type AuthContext struct {
Email string // Email address of the service account (i.e. "xxx@developer.gserviceaccount.com")
PrivateKey []byte // The contents of your RSA private key or your PEM file (i.e. []byte("-----BEGIN RSA PRIVATE KEY-----..."))
}
// NewClient creates a service-account authenticated HTTP client to access Google
// services.
func NewClient(ctx AuthContext, scopes ...string) *http.Client {
auth := &jwt.Config{
Email: ctx.Email,
PrivateKey: ctx.PrivateKey,
Scopes: scopes,
TokenURL: google.JWTTokenURL,
}
return auth.Client(oauth2.NoContext)
}
// Package cloud contains some utility functions for the gcloud-golang project.
package cloud
import (
"golang.org/x/net/context"
"google.golang.org/cloud"
)
// NewContext returns a new context that uses the provided authentication context
// to create an authorized HTTP client to access the Google Cloud APIs.
//
// You can obtain the project ID from the Google Developers Console,
// https://console.developers.google.com.
func NewContext(projID string, ctx AuthContext, scopes ...string) context.Context {
return cloud.NewContext(projID, NewClient(ctx, scopes...))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment