本文整理汇总了Golang中google/golang.org/cloud.NewContext函数的典型用法代码示例。如果您正苦于以下问题:Golang NewContext函数的具体用法?Golang NewContext怎么用?Golang NewContext使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewContext函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: handlePut
func handlePut(res http.ResponseWriter, req *http.Request) {
ctx := appengine.NewContext(req)
hc := &http.Client{
Transport: &oauth2.Transport{
Source: google.AppEngineTokenSource(ctx, storage.ScopeFullControl),
Base: &urlfetch.Transport{Context: ctx},
},
}
cctx := cloud.NewContext(appengine.AppID(ctx), hc)
rdr, hdr, err := req.FormFile("form-upload-file")
if err != nil {
http.Error(res, "ERROR RECEIVING FILE: "+err.Error(), 500)
return
}
writer := storage.NewWriter(cctx, bucketName, hdr.Filename)
io.Copy(writer, rdr)
err = writer.Close()
if err != nil {
http.Error(res, "ERROR WRITING TO BUCKET: "+err.Error(), 500)
return
}
}
示例2: newContext
func newContext(projectID, jsonKey string) (context.Context, error) {
if projectID == "" {
return nil, errors.New("project id not provided")
}
if jsonKey == "" {
return nil, errors.New("JSON key not provided")
}
key, err := ioutil.ReadFile(jsonKey)
if err != nil {
return nil, err
}
conf, err := google.JWTConfigFromJSON(
key,
pubsub.ScopeCloudPlatform,
pubsub.ScopePubSub,
)
if err != nil {
return nil, err
}
ctx := cloud.NewContext(projectID, conf.Client(oauth2.NoContext))
return ctx, nil
}
示例3: StartupHandler
func StartupHandler(w http.ResponseWriter, r *http.Request) {
if len(Config) == 0 {
c := appengine.NewContext(r)
client := &http.Client{
Transport: &oauth2.Transport{
Source: google.AppEngineTokenSource(c, storage.ScopeReadOnly),
Base: &urlfetch.Transport{
Context: c,
},
},
}
bucket, _ := file.DefaultBucketName(c)
ctx := cloud.NewContext("davine-web", client)
rc, err := storage.NewReader(ctx, bucket, "config.yaml")
if err != nil {
c.Errorf("error reading config: %v", err.Error())
return
}
configFile, err := ioutil.ReadAll(rc)
rc.Close()
if err != nil {
c.Errorf("error reading config: %v", err.Error())
return
}
c.Infof("loaded config file: %v", configFile)
yaml.Unmarshal(configFile, &Config)
c.Infof("loaded config struct: %v", Config)
}
}
示例4: main
// This example demonstrates calling the Cloud Pub/Sub API. As of 22
// Oct 2014, the Cloud Pub/Sub API is only available if you're
// whitelisted. If you're interested in using it, please apply for the
// Limited Preview program at the following form:
// http://goo.gl/Wql9HL
//
// Also, before running this example, be sure to enable Cloud Pub/Sub
// service on your project in Developer Console at:
// https://console.developers.google.com/
//
// Unless you run this sample on Compute Engine instance, please
// create a new service account and download a JSON key file for it at
// the developer console: https://console.developers.google.com/
//
// It has the following subcommands:
//
// create_topic <name>
// delete_topic <name>
// create_subscription <name> <linked_topic>
// delete_subscription <name>
// publish <topic> <message>
// pull_messages <subscription> <numworkers>
// publish_messages <topic> <numworkers>
//
// You can choose any names for topic and subscription as long as they
// follow the naming rule described at:
// https://cloud.google.com/pubsub/overview#names
//
// You can create/delete topics/subscriptions by self-explanatory
// subcommands.
//
// The "publish" subcommand is for publishing a single message to a
// specified Cloud Pub/Sub topic.
//
// The "pull_messages" subcommand is for continuously pulling messages
// from a specified Cloud Pub/Sub subscription with specified number
// of workers.
//
// The "publish_messages" subcommand is for continuously publishing
// messages to a specified Cloud Pub/Sub topic with specified number
// of workers.
func main() {
flag.Parse()
argv := flag.Args()
checkArgs(argv, 1)
client, err := newClient(*jsonFile)
if err != nil {
log.Fatalf("clientAndId failed, %v", err)
}
if *projID == "" {
usageAndExit("Please specify Project ID.")
}
ctx := cloud.NewContext(*projID, client)
m := map[string]func(ctx context.Context, argv []string){
"create_topic": createTopic,
"delete_topic": deleteTopic,
"create_subscription": createSubscription,
"delete_subscription": deleteSubscription,
"publish": publish,
"pull_messages": pullMessages,
"publish_messages": publishMessages,
}
subcommand := argv[0]
f, ok := m[subcommand]
if !ok {
usageAndExit(fmt.Sprintf("Function not found for %s", subcommand))
}
f(ctx, argv)
}
示例5: TestNamespaceQuery
func TestNamespaceQuery(t *testing.T) {
gotNamespace := make(chan string, 1)
ctx := cloud.NewContext("nsQueryTest", &http.Client{Transport: &fakeTransport{
Handler: func(req, resp proto.Message) error {
gotNamespace <- req.(*pb.RunQueryRequest).GetPartitionId().GetNamespace()
return errors.New("not implemented")
},
}})
var gs []Gopher
NewQuery("Gopher").GetAll(ctx, &gs)
if got, want := <-gotNamespace, ""; got != want {
t.Errorf("GetAll: got namespace %q, want %q", got, want)
}
NewQuery("Gopher").Count(ctx)
if got, want := <-gotNamespace, ""; got != want {
t.Errorf("Count: got namespace %q, want %q", got, want)
}
const ns = "not_default"
ctx = WithNamespace(ctx, ns)
NewQuery("Gopher").GetAll(ctx, &gs)
if got, want := <-gotNamespace, ns; got != want {
t.Errorf("GetAll: got namespace %q, want %q", got, want)
}
NewQuery("Gopher").Count(ctx)
if got, want := <-gotNamespace, ns; got != want {
t.Errorf("Count: got namespace %q, want %q", got, want)
}
}
示例6: Example_listObjects
func Example_listObjects() {
// see the auth example how to initiate a context.
ctx := cloud.NewContext("project-id", &http.Client{Transport: nil})
var query *storage.Query
for {
// If you are using this package on App Engine Managed VMs runtime,
// you can init a bucket client with your app's default bucket name.
// See http://godoc.org/google.golang.org/appengine/file#DefaultBucketName.
objects, err := storage.List(ctx, "bucketname", query)
if err != nil {
log.Fatal(err)
}
for _, obj := range objects.Results {
log.Printf("object name: %s, size: %v", obj.Name, obj.Size)
}
// if there are more results, objects.Next
// will be non-nil.
query = objects.Next
if query == nil {
break
}
}
log.Println("paginated through all object items in the bucket you specified.")
}
示例7: NoAuthContext
func NoAuthContext() context.Context {
projID := os.Getenv(envProjID)
if projID == "" {
log.Fatal("GCLOUD_TESTS_GOLANG_PROJECT_ID must be set. See CONTRIBUTING.md for details.")
}
return cloud.NewContext(projID, &http.Client{Transport: http.DefaultTransport})
}
示例8: getCloudContext
func getCloudContext(aeCtx context.Context) (context.Context, error) {
data, err := ioutil.ReadFile("gcs.xxjson")
if err != nil {
return nil, err
}
conf, err := google.JWTConfigFromJSON(
data,
storage.ScopeFullControl,
)
if err != nil {
return nil, err
}
tokenSource := conf.TokenSource(aeCtx)
hc := &http.Client{
Transport: &oauth2.Transport{
Source: tokenSource,
Base: &urlfetch.Transport{Context: aeCtx},
},
}
return cloud.NewContext(appengine.AppID(aeCtx), hc), nil
}
示例9: init
func init() {
if !metadata.OnGCE() {
return
}
hc, err := google.DefaultClient(oauth2.NoContext)
if err != nil {
registerBrokenFS(fmt.Errorf("could not get http client for context: %v", err))
return
}
projID, err := metadata.ProjectID()
if projID == "" || err != nil {
registerBrokenFS(fmt.Errorf("could not get GCE project ID: %v", err))
return
}
ctx := cloud.NewContext(projID, hc)
sc, err := storage.NewClient(ctx)
if err != nil {
registerBrokenFS(fmt.Errorf("could not get cloud storage client: %v", err))
return
}
wkfs.RegisterFS("/gcs/", &gcsFS{
ctx: ctx,
sc: sc,
})
}
示例10: NewGCSImageStore
func (this *Factory) NewGCSImageStore(conf map[string]string) ImageStore {
jsonKey, err := ioutil.ReadFile(conf["KeyFile"])
if err != nil {
log.Fatal(err)
}
cloudConf, err := google.JWTConfigFromJSON(
jsonKey,
gcs.ScopeFullControl,
)
if err != nil {
log.Fatal(err)
}
bucket := conf["BucketName"]
ctx := gcloud.NewContext(conf["AppID"], cloudConf.Client(oauth2.NoContext))
mapper := NewNamePathMapper(conf["NamePathRegex"], conf["NamePathMap"])
return NewGCSImageStore(
ctx,
bucket,
conf["StoreRoot"],
mapper,
)
}
示例11: handler
// handler is the main demo entry point that calls the GCS operations.
func handler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
c := appengine.NewContext(r)
if bucket == "" {
var err error
if bucket, err = file.DefaultBucketName(c); err != nil {
log.Errorf(c, "failed to get default GCS bucket name: %v", err)
return
}
}
hc := &http.Client{
Transport: &oauth2.Transport{
Source: google.AppEngineTokenSource(c, storage.ScopeFullControl),
// Note that the App Engine urlfetch service has a limit of 10MB uploads and
// 32MB downloads.
// See https://cloud.google.com/appengine/docs/go/urlfetch/#Go_Quotas_and_limits
// for more information.
Base: &urlfetch.Transport{Context: c},
},
}
ctx := cloud.NewContext(appengine.AppID(c), hc)
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
fmt.Fprintf(w, "Demo GCS Application running from Version: %v\n", appengine.VersionID(c))
fmt.Fprintf(w, "Using bucket name: %v\n\n", bucket)
d := &demo{
c: c,
w: w,
ctx: ctx,
}
n := "demo-testfile-go"
d.createFile(n)
d.readFile(n)
d.copyFile(n)
d.statFile(n)
d.createListFiles()
d.listBucket()
d.listBucketDirMode()
d.defaultACL()
d.putDefaultACLRule()
d.deleteDefaultACLRule()
d.bucketACL()
d.putBucketACLRule()
d.deleteBucketACLRule()
d.acl(n)
d.putACLRule(n)
d.deleteACLRule(n)
d.deleteFiles()
if d.failed {
io.WriteString(w, "\nDemo failed.\n")
} else {
io.WriteString(w, "\nDemo succeeded.\n")
}
}
示例12: Context
// TODO(djd): Delete this function when it's no longer used.
func Context(scopes ...string) context.Context {
ctx := oauth2.NoContext
ts := TokenSource(ctx, scopes...)
if ts == nil {
return nil
}
return cloud.NewContext(ProjID(), oauth2.NewClient(ctx, ts))
}
示例13: TestEmptyAckID
func TestEmptyAckID(t *testing.T) {
ctx := cloud.NewContext("project-id", &http.Client{})
id := []string{"test", ""}
err := Ack(ctx, "sub", id...)
if err == nil || !strings.Contains(err.Error(), "index 1") {
t.Errorf("Ack should report an error indicating the id is empty. Got: %v", err)
}
}
示例14: getCloudContext
func getCloudContext(gae context.Context) context.Context {
hc := &http.Client{
Transport: &oauth2.Transport{
Source: google.AppEngineTokenSource(gae, storage.ScopeFullControl),
Base: &urlfetch.Transport{Context: gae},
},
}
return cloud.NewContext(appengine.AppID(gae), hc)
}
示例15: authContext
func (bs *GCSBackupStorage) authContext() (context.Context, error) {
if bs.authCtx == nil {
client, err := google.DefaultClient(context.TODO())
if err != nil {
return nil, err
}
bs.authCtx = cloud.NewContext(*project, client)
}
return bs.authCtx, nil
}