Switch to using the dep tool and update all the dependencies
This commit is contained in:
parent
5135ff73cb
commit
98c2d2c41b
5321 changed files with 4483201 additions and 5922 deletions
368
vendor/google.golang.org/api/examples/bigquery.go
generated
vendored
Normal file
368
vendor/google.golang.org/api/examples/bigquery.go
generated
vendored
Normal file
|
@ -0,0 +1,368 @@
|
|||
// Copyright 2013 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"container/list"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"math"
|
||||
"math/rand"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
bigquery "google.golang.org/api/bigquery/v2"
|
||||
storage "google.golang.org/api/storage/v1"
|
||||
)
|
||||
|
||||
const (
|
||||
GB = 1 << 30
|
||||
MaxBackoff = 30000
|
||||
BaseBackoff = 250
|
||||
BackoffGrowthFactor = 1.8
|
||||
BackoffGrowthDamper = 0.25
|
||||
JobStatusDone = "DONE"
|
||||
DatasetAlreadyExists = "Already Exists: Dataset"
|
||||
TableWriteEmptyDisposition = "WRITE_EMPTY"
|
||||
)
|
||||
|
||||
func init() {
|
||||
scope := fmt.Sprintf("%s %s %s", bigquery.BigqueryScope,
|
||||
storage.DevstorageReadOnlyScope,
|
||||
"https://www.googleapis.com/auth/userinfo.profile")
|
||||
registerDemo("bigquery", scope, bqMain)
|
||||
}
|
||||
|
||||
// This example demonstrates loading objects from Google Cloud Storage into
|
||||
// BigQuery. Objects are specified by their bucket and a name prefix. Each
|
||||
// object will be loaded into a new table identified by the object name minus
|
||||
// any file extension. All tables are added to the specified dataset (one will
|
||||
// be created if necessary). Currently, tables will not be overwritten and an
|
||||
// attempt to load an object into a dataset that already contains its table
|
||||
// will emit an error message indicating the table already exists.
|
||||
// A schema file must be provided and it will be applied to every object/table.
|
||||
// Example usage:
|
||||
// go-api-demo -clientid="my-clientid" -secret="my-secret" bq myProject
|
||||
// myDataBucket datafile2013070 DataFiles2013
|
||||
// ./datafile_schema.json 100
|
||||
//
|
||||
// This will load all objects (e.g. all data files from July 2013) from
|
||||
// gs://myDataBucket into a (possibly new) BigQuery dataset named DataFiles2013
|
||||
// using the schema file provided and allowing up to 100 bad records. Assuming
|
||||
// each object is named like datafileYYYYMMDD.csv.gz and all of July's files are
|
||||
// stored in the bucket, 9 tables will be created named like datafile201307DD
|
||||
// where DD ranges from 01 to 09, inclusive.
|
||||
// When the program completes, it will emit a results line similar to:
|
||||
//
|
||||
// 9 files loaded in 3m58s (18m2.708s). Size: 7.18GB Rows: 7130725
|
||||
//
|
||||
// The total elapsed time from the start of first job to the end of the last job
|
||||
// (effectively wall clock time) is shown. In parenthesis is the aggregate time
|
||||
// taken to load all tables.
|
||||
func bqMain(client *http.Client, argv []string) {
|
||||
if len(argv) != 6 {
|
||||
fmt.Fprintln(os.Stderr,
|
||||
"Usage: bq project_id bucket prefix dataset schema max_bad_records")
|
||||
return
|
||||
}
|
||||
|
||||
var (
|
||||
project = argv[0]
|
||||
bucket = argv[1]
|
||||
objPrefix = argv[2]
|
||||
datasetId = argv[3]
|
||||
schemaFile = argv[4]
|
||||
)
|
||||
badRecords, err := strconv.ParseInt(argv[5], 10, 64)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
return
|
||||
}
|
||||
|
||||
rand.Seed(time.Now().UnixNano())
|
||||
|
||||
service, err := storage.New(client)
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to create Storage service: %v", err)
|
||||
}
|
||||
|
||||
// Get the list of objects in the bucket matching the specified prefix.
|
||||
list := service.Objects.List(bucket)
|
||||
list.Prefix(objPrefix)
|
||||
objects, err := list.Do()
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
return
|
||||
}
|
||||
|
||||
// Create the wrapper and insert the (new) dataset.
|
||||
dataset, err := newBQDataset(client, project, datasetId)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
return
|
||||
}
|
||||
if err = dataset.insert(true); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
return
|
||||
}
|
||||
|
||||
objectSource := &tableSource{
|
||||
maxBadRecords: badRecords,
|
||||
disposition: TableWriteEmptyDisposition,
|
||||
}
|
||||
|
||||
// Load the schema from disk.
|
||||
f, err := ioutil.ReadFile(schemaFile)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
return
|
||||
}
|
||||
if err = json.Unmarshal(f, &objectSource.schema); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
return
|
||||
}
|
||||
|
||||
// Assumes all objects have .csv, .csv.gz (or no) extension.
|
||||
tableIdFromObject := func(name string) string {
|
||||
return strings.TrimSuffix(strings.TrimSuffix(name, ".gz"), ".csv")
|
||||
}
|
||||
|
||||
// A jobset is way to group a collection of jobs together for monitoring.
|
||||
// For this example, we just use the name of the bucket and object prefix.
|
||||
jobset := fmt.Sprintf("%s:%s", bucket, objPrefix)
|
||||
fmt.Fprintf(os.Stderr, "\nLoading %d objects.\n", len(objects.Items))
|
||||
|
||||
// Load each object into a dataset of the same name (minus any extension).
|
||||
// A successful insert call will inject the job into our queue for monitoring.
|
||||
for _, o := range objects.Items {
|
||||
objectSource.id = tableIdFromObject(o.Name)
|
||||
objectSource.uri = fmt.Sprintf("gs://%s/%s", o.Bucket, o.Name)
|
||||
if err = dataset.load(jobset, objectSource); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
}
|
||||
}
|
||||
|
||||
dataset.monitor(jobset)
|
||||
}
|
||||
|
||||
// Wraps the BigQuery service and dataset and provides some helper functions.
|
||||
type bqDataset struct {
|
||||
project string
|
||||
id string
|
||||
bq *bigquery.Service
|
||||
dataset *bigquery.Dataset
|
||||
jobsets map[string]*list.List
|
||||
}
|
||||
|
||||
func newBQDataset(client *http.Client, dsProj string, dsId string) (*bqDataset,
|
||||
error) {
|
||||
|
||||
service, err := bigquery.New(client)
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to create BigQuery service: %v", err)
|
||||
}
|
||||
|
||||
return &bqDataset{
|
||||
project: dsProj,
|
||||
id: dsId,
|
||||
bq: service,
|
||||
dataset: &bigquery.Dataset{
|
||||
DatasetReference: &bigquery.DatasetReference{
|
||||
DatasetId: dsId,
|
||||
ProjectId: dsProj,
|
||||
},
|
||||
},
|
||||
jobsets: make(map[string]*list.List),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (ds *bqDataset) insert(existsOK bool) error {
|
||||
call := ds.bq.Datasets.Insert(ds.project, ds.dataset)
|
||||
_, err := call.Do()
|
||||
if err != nil && (!existsOK || !strings.Contains(err.Error(),
|
||||
DatasetAlreadyExists)) {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
type tableSource struct {
|
||||
id string
|
||||
uri string
|
||||
schema bigquery.TableSchema
|
||||
maxBadRecords int64
|
||||
disposition string
|
||||
}
|
||||
|
||||
func (ds *bqDataset) load(jobset string, source *tableSource) error {
|
||||
job := &bigquery.Job{
|
||||
Configuration: &bigquery.JobConfiguration{
|
||||
Load: &bigquery.JobConfigurationLoad{
|
||||
DestinationTable: &bigquery.TableReference{
|
||||
DatasetId: ds.dataset.DatasetReference.DatasetId,
|
||||
ProjectId: ds.project,
|
||||
TableId: source.id,
|
||||
},
|
||||
MaxBadRecords: source.maxBadRecords,
|
||||
Schema: &source.schema,
|
||||
SourceUris: []string{source.uri},
|
||||
WriteDisposition: source.disposition,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
call := ds.bq.Jobs.Insert(ds.project, job)
|
||||
job, err := call.Do()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, ok := ds.jobsets[jobset]
|
||||
if !ok {
|
||||
ds.jobsets[jobset] = list.New()
|
||||
}
|
||||
ds.jobsets[jobset].PushBack(job)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ds *bqDataset) getJob(id string) (*bigquery.Job, error) {
|
||||
return ds.bq.Jobs.Get(ds.project, id).Do()
|
||||
}
|
||||
|
||||
func (ds *bqDataset) monitor(jobset string) {
|
||||
jobq, ok := ds.jobsets[jobset]
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
var backoff float64 = BaseBackoff
|
||||
pause := func(grow bool) {
|
||||
if grow {
|
||||
backoff *= BackoffGrowthFactor
|
||||
backoff -= (backoff * rand.Float64() * BackoffGrowthDamper)
|
||||
backoff = math.Min(backoff, MaxBackoff)
|
||||
fmt.Fprintf(os.Stderr, "[%s] Checking remaining %d jobs...\n", jobset,
|
||||
1+jobq.Len())
|
||||
}
|
||||
time.Sleep(time.Duration(backoff) * time.Millisecond)
|
||||
}
|
||||
var stats jobStats
|
||||
|
||||
// Track a 'head' pending job in queue for detecting cycling.
|
||||
head := ""
|
||||
// Loop until all jobs are done - with either success or error.
|
||||
for jobq.Len() > 0 {
|
||||
jel := jobq.Front()
|
||||
job := jel.Value.(*bigquery.Job)
|
||||
jobq.Remove(jel)
|
||||
jid := job.JobReference.JobId
|
||||
loop := false
|
||||
|
||||
// Check and possibly pick a new head job id.
|
||||
if len(head) == 0 {
|
||||
head = jid
|
||||
} else {
|
||||
if jid == head {
|
||||
loop = true
|
||||
}
|
||||
}
|
||||
|
||||
// Retrieve the job's current status.
|
||||
pause(loop)
|
||||
j, err := ds.getJob(jid)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
// In this case of a transient API error, we want keep the job.
|
||||
if j == nil {
|
||||
jobq.PushBack(job)
|
||||
} else {
|
||||
// Must reset head tracker if job is discarded.
|
||||
if loop {
|
||||
head = ""
|
||||
backoff = BaseBackoff
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
// Reassign with the updated job data (from Get).
|
||||
// We don't use j here as Get might return nil for this value.
|
||||
job = j
|
||||
|
||||
if job.Status.State != JobStatusDone {
|
||||
jobq.PushBack(job)
|
||||
continue
|
||||
}
|
||||
|
||||
if res := job.Status.ErrorResult; res != nil {
|
||||
fmt.Fprintln(os.Stderr, res.Message)
|
||||
} else {
|
||||
stat := job.Statistics
|
||||
lstat := stat.Load
|
||||
stats.files += 1
|
||||
stats.bytesIn += lstat.InputFileBytes
|
||||
stats.bytesOut += lstat.OutputBytes
|
||||
stats.rows += lstat.OutputRows
|
||||
stats.elapsed +=
|
||||
time.Duration(stat.EndTime-stat.StartTime) * time.Millisecond
|
||||
|
||||
if stats.start.IsZero() {
|
||||
stats.start = time.Unix(stat.StartTime/1000, 0)
|
||||
} else {
|
||||
t := time.Unix(stat.StartTime/1000, 0)
|
||||
if stats.start.Sub(t) > 0 {
|
||||
stats.start = t
|
||||
}
|
||||
}
|
||||
|
||||
if stats.finish.IsZero() {
|
||||
stats.finish = time.Unix(stat.EndTime/1000, 0)
|
||||
} else {
|
||||
t := time.Unix(stat.EndTime/1000, 0)
|
||||
if t.Sub(stats.finish) > 0 {
|
||||
stats.finish = t
|
||||
}
|
||||
}
|
||||
}
|
||||
// When the head job is processed reset the backoff since the loads
|
||||
// run in BQ in parallel.
|
||||
if loop {
|
||||
head = ""
|
||||
backoff = BaseBackoff
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Fprintf(os.Stderr, "%#v\n", stats)
|
||||
}
|
||||
|
||||
type jobStats struct {
|
||||
// Number of files (sources) loaded.
|
||||
files int64
|
||||
// Bytes read from source (possibly compressed).
|
||||
bytesIn int64
|
||||
// Bytes loaded into BigQuery (uncompressed).
|
||||
bytesOut int64
|
||||
// Rows loaded into BigQuery.
|
||||
rows int64
|
||||
// Time taken to load source into table.
|
||||
elapsed time.Duration
|
||||
// Start time of the job.
|
||||
start time.Time
|
||||
// End time of the job.
|
||||
finish time.Time
|
||||
}
|
||||
|
||||
func (s jobStats) GoString() string {
|
||||
return fmt.Sprintf("\n%d files loaded in %v (%v). Size: %.2fGB Rows: %d\n",
|
||||
s.files, s.finish.Sub(s.start), s.elapsed, float64(s.bytesOut)/GB,
|
||||
s.rows)
|
||||
}
|
77
vendor/google.golang.org/api/examples/books.go
generated
vendored
Normal file
77
vendor/google.golang.org/api/examples/books.go
generated
vendored
Normal file
|
@ -0,0 +1,77 @@
|
|||
// Copyright 2014 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
books "google.golang.org/api/books/v1"
|
||||
"google.golang.org/api/googleapi"
|
||||
)
|
||||
|
||||
func init() {
|
||||
registerDemo("books", books.BooksScope, booksMain)
|
||||
}
|
||||
|
||||
// booksMain is an example that demonstrates calling the Books API.
|
||||
//
|
||||
// Example usage:
|
||||
// go build -o go-api-demo *.go
|
||||
// go-api-demo -clientid="my-clientid" -secret="my-secret" books
|
||||
func booksMain(client *http.Client, argv []string) {
|
||||
if len(argv) != 0 {
|
||||
fmt.Fprintln(os.Stderr, "Usage: books")
|
||||
return
|
||||
}
|
||||
|
||||
svc, err := books.New(client)
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to create Books service: %v", err)
|
||||
}
|
||||
|
||||
bs, err := svc.Mylibrary.Bookshelves.List().Do()
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to retrieve mylibrary bookshelves: %v", err)
|
||||
}
|
||||
|
||||
if len(bs.Items) == 0 {
|
||||
log.Fatal("You have no bookshelves to explore.")
|
||||
}
|
||||
for _, b := range bs.Items {
|
||||
// Note that sometimes VolumeCount is not populated, so it may erroneously say '0'.
|
||||
log.Printf("You have %v books on bookshelf %q:", b.VolumeCount, b.Title)
|
||||
|
||||
// List the volumes on this shelf.
|
||||
vol, err := svc.Mylibrary.Bookshelves.Volumes.List(strconv.FormatInt(b.Id, 10)).Do()
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to retrieve mylibrary bookshelf volumes: %v", err)
|
||||
}
|
||||
for _, v := range vol.Items {
|
||||
var info struct {
|
||||
Text bool `json:"text"`
|
||||
Image bool `json:"image"`
|
||||
}
|
||||
// Parse the additional fields, but ignore errors, as the information is not critical.
|
||||
googleapi.ConvertVariant(v.VolumeInfo.ReadingModes.(map[string]interface{}), &info)
|
||||
var s []string
|
||||
if info.Text {
|
||||
s = append(s, "text")
|
||||
}
|
||||
if info.Image {
|
||||
s = append(s, "image")
|
||||
}
|
||||
extra := fmt.Sprintf("; formats: %v", s)
|
||||
if v.VolumeInfo.ImageLinks != nil {
|
||||
extra += fmt.Sprintf("; thumbnail: %v", v.VolumeInfo.ImageLinks.Thumbnail)
|
||||
}
|
||||
log.Printf(" %q by %v%v", v.VolumeInfo.Title, strings.Join(v.VolumeInfo.Authors, ", "), extra)
|
||||
}
|
||||
}
|
||||
}
|
73
vendor/google.golang.org/api/examples/calendar.go
generated
vendored
Normal file
73
vendor/google.golang.org/api/examples/calendar.go
generated
vendored
Normal file
|
@ -0,0 +1,73 @@
|
|||
// Copyright 2014 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
|
||||
calendar "google.golang.org/api/calendar/v3"
|
||||
)
|
||||
|
||||
func init() {
|
||||
registerDemo("calendar", calendar.CalendarScope, calendarMain)
|
||||
}
|
||||
|
||||
// calendarMain is an example that demonstrates calling the Calendar API.
|
||||
// Its purpose is to test out the ability to get maps of struct objects.
|
||||
//
|
||||
// Example usage:
|
||||
// go build -o go-api-demo *.go
|
||||
// go-api-demo -clientid="my-clientid" -secret="my-secret" calendar
|
||||
func calendarMain(client *http.Client, argv []string) {
|
||||
if len(argv) != 0 {
|
||||
fmt.Fprintln(os.Stderr, "Usage: calendar")
|
||||
return
|
||||
}
|
||||
|
||||
svc, err := calendar.New(client)
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to create Calendar service: %v", err)
|
||||
}
|
||||
|
||||
c, err := svc.Colors.Get().Do()
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to retrieve calendar colors: %v", err)
|
||||
}
|
||||
|
||||
log.Printf("Kind of colors: %v", c.Kind)
|
||||
log.Printf("Colors last updated: %v", c.Updated)
|
||||
|
||||
for k, v := range c.Calendar {
|
||||
log.Printf("Calendar[%v]: Background=%v, Foreground=%v", k, v.Background, v.Foreground)
|
||||
}
|
||||
|
||||
for k, v := range c.Event {
|
||||
log.Printf("Event[%v]: Background=%v, Foreground=%v", k, v.Background, v.Foreground)
|
||||
}
|
||||
|
||||
listRes, err := svc.CalendarList.List().Fields("items/id").Do()
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to retrieve list of calendars: %v", err)
|
||||
}
|
||||
for _, v := range listRes.Items {
|
||||
log.Printf("Calendar ID: %v\n", v.Id)
|
||||
}
|
||||
|
||||
if len(listRes.Items) > 0 {
|
||||
id := listRes.Items[0].Id
|
||||
res, err := svc.Events.List(id).Fields("items(updated,summary)", "summary", "nextPageToken").Do()
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to retrieve calendar events list: %v", err)
|
||||
}
|
||||
for _, v := range res.Items {
|
||||
log.Printf("Calendar ID %q event: %v: %q\n", id, v.Updated, v.Summary)
|
||||
}
|
||||
log.Printf("Calendar ID %q Summary: %v\n", id, res.Summary)
|
||||
log.Printf("Calendar ID %q next page token: %v\n", id, res.NextPageToken)
|
||||
}
|
||||
}
|
107
vendor/google.golang.org/api/examples/compute.go
generated
vendored
Normal file
107
vendor/google.golang.org/api/examples/compute.go
generated
vendored
Normal file
|
@ -0,0 +1,107 @@
|
|||
// Copyright 2017 Google Inc. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
compute "google.golang.org/api/compute/v1"
|
||||
"google.golang.org/api/googleapi"
|
||||
)
|
||||
|
||||
func init() {
|
||||
scopes := strings.Join([]string{
|
||||
compute.DevstorageFullControlScope,
|
||||
compute.ComputeScope,
|
||||
}, " ")
|
||||
registerDemo("compute", scopes, computeMain)
|
||||
}
|
||||
|
||||
func computeMain(client *http.Client, argv []string) {
|
||||
if len(argv) != 2 {
|
||||
fmt.Fprintln(os.Stderr, "Usage: compute project_id instance_name (to start an instance)")
|
||||
return
|
||||
}
|
||||
|
||||
service, err := compute.New(client)
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to create Compute service: %v", err)
|
||||
}
|
||||
|
||||
projectId := argv[0]
|
||||
instanceName := argv[1]
|
||||
|
||||
prefix := "https://www.googleapis.com/compute/v1/projects/" + projectId
|
||||
imageURL := "https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/debian-7-wheezy-v20140606"
|
||||
zone := "us-central1-a"
|
||||
|
||||
// Show the current images that are available.
|
||||
res, err := service.Images.List(projectId).Do()
|
||||
log.Printf("Got compute.Images.List, err: %#v, %v", res, err)
|
||||
|
||||
instance := &compute.Instance{
|
||||
Name: instanceName,
|
||||
Description: "compute sample instance",
|
||||
MachineType: prefix + "/zones/" + zone + "/machineTypes/n1-standard-1",
|
||||
Disks: []*compute.AttachedDisk{
|
||||
{
|
||||
AutoDelete: true,
|
||||
Boot: true,
|
||||
Type: "PERSISTENT",
|
||||
InitializeParams: &compute.AttachedDiskInitializeParams{
|
||||
DiskName: "my-root-pd",
|
||||
SourceImage: imageURL,
|
||||
},
|
||||
},
|
||||
},
|
||||
NetworkInterfaces: []*compute.NetworkInterface{
|
||||
&compute.NetworkInterface{
|
||||
AccessConfigs: []*compute.AccessConfig{
|
||||
&compute.AccessConfig{
|
||||
Type: "ONE_TO_ONE_NAT",
|
||||
Name: "External NAT",
|
||||
},
|
||||
},
|
||||
Network: prefix + "/global/networks/default",
|
||||
},
|
||||
},
|
||||
ServiceAccounts: []*compute.ServiceAccount{
|
||||
{
|
||||
Email: "default",
|
||||
Scopes: []string{
|
||||
compute.DevstorageFullControlScope,
|
||||
compute.ComputeScope,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
op, err := service.Instances.Insert(projectId, zone, instance).Do()
|
||||
log.Printf("Got compute.Operation, err: %#v, %v", op, err)
|
||||
etag := op.Header.Get("Etag")
|
||||
log.Printf("Etag=%v", etag)
|
||||
|
||||
inst, err := service.Instances.Get(projectId, zone, instanceName).IfNoneMatch(etag).Do()
|
||||
log.Printf("Got compute.Instance, err: %#v, %v", inst, err)
|
||||
if googleapi.IsNotModified(err) {
|
||||
log.Printf("Instance not modified since insert.")
|
||||
} else {
|
||||
log.Printf("Instance modified since insert.")
|
||||
}
|
||||
}
|
86
vendor/google.golang.org/api/examples/debug.go
generated
vendored
Normal file
86
vendor/google.golang.org/api/examples/debug.go
generated
vendored
Normal file
|
@ -0,0 +1,86 @@
|
|||
// Copyright 2017 Google Inc. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"os"
|
||||
)
|
||||
|
||||
type logTransport struct {
|
||||
rt http.RoundTripper
|
||||
}
|
||||
|
||||
func (t *logTransport) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||
var buf bytes.Buffer
|
||||
|
||||
os.Stdout.Write([]byte("\n[request]\n"))
|
||||
if req.Body != nil {
|
||||
req.Body = ioutil.NopCloser(&readButCopy{req.Body, &buf})
|
||||
}
|
||||
req.Write(os.Stdout)
|
||||
if req.Body != nil {
|
||||
req.Body = ioutil.NopCloser(&buf)
|
||||
}
|
||||
os.Stdout.Write([]byte("\n[/request]\n"))
|
||||
|
||||
res, err := t.rt.RoundTrip(req)
|
||||
|
||||
fmt.Printf("[response]\n")
|
||||
if err != nil {
|
||||
fmt.Printf("ERROR: %v", err)
|
||||
} else {
|
||||
body := res.Body
|
||||
res.Body = nil
|
||||
res.Write(os.Stdout)
|
||||
if body != nil {
|
||||
res.Body = ioutil.NopCloser(&echoAsRead{body})
|
||||
}
|
||||
}
|
||||
|
||||
return res, err
|
||||
}
|
||||
|
||||
type echoAsRead struct {
|
||||
src io.Reader
|
||||
}
|
||||
|
||||
func (r *echoAsRead) Read(p []byte) (int, error) {
|
||||
n, err := r.src.Read(p)
|
||||
if n > 0 {
|
||||
os.Stdout.Write(p[:n])
|
||||
}
|
||||
if err == io.EOF {
|
||||
fmt.Printf("\n[/response]\n")
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
|
||||
type readButCopy struct {
|
||||
src io.Reader
|
||||
dst io.Writer
|
||||
}
|
||||
|
||||
func (r *readButCopy) Read(p []byte) (int, error) {
|
||||
n, err := r.src.Read(p)
|
||||
if n > 0 {
|
||||
r.dst.Write(p[:n])
|
||||
}
|
||||
return n, err
|
||||
}
|
49
vendor/google.golang.org/api/examples/drive.go
generated
vendored
Normal file
49
vendor/google.golang.org/api/examples/drive.go
generated
vendored
Normal file
|
@ -0,0 +1,49 @@
|
|||
// Copyright 2017 Google Inc. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
|
||||
drive "google.golang.org/api/drive/v2"
|
||||
)
|
||||
|
||||
func init() {
|
||||
registerDemo("drive", drive.DriveScope, driveMain)
|
||||
}
|
||||
|
||||
func driveMain(client *http.Client, argv []string) {
|
||||
if len(argv) != 1 {
|
||||
fmt.Fprintln(os.Stderr, "Usage: drive filename (to upload a file)")
|
||||
return
|
||||
}
|
||||
|
||||
service, err := drive.New(client)
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to create Drive service: %v", err)
|
||||
}
|
||||
|
||||
filename := argv[0]
|
||||
|
||||
goFile, err := os.Open(filename)
|
||||
if err != nil {
|
||||
log.Fatalf("error opening %q: %v", filename, err)
|
||||
}
|
||||
driveFile, err := service.Files.Insert(&drive.File{Title: filename}).Media(goFile).Do()
|
||||
log.Printf("Got drive.File, err: %#v, %v", driveFile, err)
|
||||
}
|
109
vendor/google.golang.org/api/examples/fitness.go
generated
vendored
Normal file
109
vendor/google.golang.org/api/examples/fitness.go
generated
vendored
Normal file
|
@ -0,0 +1,109 @@
|
|||
// Copyright 2014 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
fitness "google.golang.org/api/fitness/v1"
|
||||
)
|
||||
|
||||
const (
|
||||
layout = "Jan 2, 2006 at 3:04pm" // for time.Format
|
||||
nanosPerMilli = 1e6
|
||||
)
|
||||
|
||||
func init() {
|
||||
scopes := []string{
|
||||
fitness.FitnessActivityReadScope,
|
||||
fitness.FitnessActivityWriteScope,
|
||||
fitness.FitnessBodyReadScope,
|
||||
fitness.FitnessBodyWriteScope,
|
||||
fitness.FitnessLocationReadScope,
|
||||
fitness.FitnessLocationWriteScope,
|
||||
}
|
||||
registerDemo("fitness", strings.Join(scopes, " "), fitnessMain)
|
||||
}
|
||||
|
||||
// millisToTime converts Unix millis to time.Time.
|
||||
func millisToTime(t int64) time.Time {
|
||||
return time.Unix(0, t*nanosPerMilli)
|
||||
}
|
||||
|
||||
// fitnessMain is an example that demonstrates calling the Fitness API.
|
||||
//
|
||||
// Example usage:
|
||||
// go build -o go-api-demo *.go
|
||||
// go-api-demo -clientid="my-clientid" -secret="my-secret" fitness
|
||||
func fitnessMain(client *http.Client, argv []string) {
|
||||
if len(argv) != 0 {
|
||||
fmt.Fprintln(os.Stderr, "Usage: fitness")
|
||||
return
|
||||
}
|
||||
|
||||
svc, err := fitness.New(client)
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to create Fitness service: %v", err)
|
||||
}
|
||||
|
||||
us, err := svc.Users.Sessions.List("me").Do()
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to retrieve user's sessions: %v", err)
|
||||
}
|
||||
if len(us.Session) == 0 {
|
||||
log.Fatal("You have no user sessions to explore.")
|
||||
}
|
||||
|
||||
var minTime, maxTime time.Time
|
||||
for _, s := range us.Session {
|
||||
start := millisToTime(s.StartTimeMillis)
|
||||
end := millisToTime(s.EndTimeMillis)
|
||||
if minTime.IsZero() || start.Before(minTime) {
|
||||
minTime = start
|
||||
}
|
||||
if maxTime.IsZero() || end.After(maxTime) {
|
||||
maxTime = end
|
||||
}
|
||||
log.Printf("Session %q, %v - %v, activity type=%v", s.Name, start.Format(layout), end.Format(layout), s.ActivityType)
|
||||
}
|
||||
|
||||
ds, err := svc.Users.DataSources.List("me").Do()
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to retrieve user's data sources: %v", err)
|
||||
}
|
||||
if len(ds.DataSource) == 0 {
|
||||
log.Fatal("You have no data sources to explore.")
|
||||
}
|
||||
for _, d := range ds.DataSource {
|
||||
format := "integer"
|
||||
if d.DataType != nil && len(d.DataType.Field) > 0 {
|
||||
f := d.DataType.Field[0]
|
||||
format = f.Format
|
||||
log.Printf("Data source %q, name %q is of type %q", d.DataStreamName, f.Name, format)
|
||||
} else {
|
||||
log.Printf("Data source %q is of type %q", d.DataStreamName, d.Type)
|
||||
}
|
||||
setID := fmt.Sprintf("%v-%v", minTime.UnixNano(), maxTime.UnixNano())
|
||||
data, err := svc.Users.DataSources.Datasets.Get("me", d.DataStreamId, setID).Do()
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to retrieve user's data source stream %v, %v: %v", d.DataStreamId, setID, err)
|
||||
}
|
||||
for _, p := range data.Point {
|
||||
for _, v := range p.Value {
|
||||
t := millisToTime(p.ModifiedTimeMillis).Format(layout)
|
||||
if format == "integer" {
|
||||
log.Printf("data at %v = %v", t, v.IntVal)
|
||||
} else {
|
||||
log.Printf("data at %v = %v", t, v.FpVal)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
140
vendor/google.golang.org/api/examples/gmail.go
generated
vendored
Normal file
140
vendor/google.golang.org/api/examples/gmail.go
generated
vendored
Normal file
|
@ -0,0 +1,140 @@
|
|||
// Copyright 2014 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
gmail "google.golang.org/api/gmail/v1"
|
||||
)
|
||||
|
||||
func init() {
|
||||
registerDemo("gmail", gmail.MailGoogleComScope, gmailMain)
|
||||
}
|
||||
|
||||
type message struct {
|
||||
size int64
|
||||
gmailID string
|
||||
date string // retrieved from message header
|
||||
snippet string
|
||||
}
|
||||
|
||||
// gmailMain is an example that demonstrates calling the Gmail API.
|
||||
// It iterates over all messages of a user that are larger
|
||||
// than 5MB, sorts them by size, and then interactively asks the user to
|
||||
// choose either to Delete, Skip, or Quit for each message.
|
||||
//
|
||||
// Example usage:
|
||||
// go build -o go-api-demo *.go
|
||||
// go-api-demo -clientid="my-clientid" -secret="my-secret" gmail
|
||||
func gmailMain(client *http.Client, argv []string) {
|
||||
if len(argv) != 0 {
|
||||
fmt.Fprintln(os.Stderr, "Usage: gmail")
|
||||
return
|
||||
}
|
||||
|
||||
svc, err := gmail.New(client)
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to create Gmail service: %v", err)
|
||||
}
|
||||
|
||||
var total int64
|
||||
msgs := []message{}
|
||||
pageToken := ""
|
||||
for {
|
||||
req := svc.Users.Messages.List("me").Q("larger:5M")
|
||||
if pageToken != "" {
|
||||
req.PageToken(pageToken)
|
||||
}
|
||||
r, err := req.Do()
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to retrieve messages: %v", err)
|
||||
}
|
||||
|
||||
log.Printf("Processing %v messages...\n", len(r.Messages))
|
||||
for _, m := range r.Messages {
|
||||
msg, err := svc.Users.Messages.Get("me", m.Id).Do()
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to retrieve message %v: %v", m.Id, err)
|
||||
}
|
||||
total += msg.SizeEstimate
|
||||
date := ""
|
||||
for _, h := range msg.Payload.Headers {
|
||||
if h.Name == "Date" {
|
||||
date = h.Value
|
||||
break
|
||||
}
|
||||
}
|
||||
msgs = append(msgs, message{
|
||||
size: msg.SizeEstimate,
|
||||
gmailID: msg.Id,
|
||||
date: date,
|
||||
snippet: msg.Snippet,
|
||||
})
|
||||
}
|
||||
|
||||
if r.NextPageToken == "" {
|
||||
break
|
||||
}
|
||||
pageToken = r.NextPageToken
|
||||
}
|
||||
log.Printf("total: %v\n", total)
|
||||
|
||||
sortBySize(msgs)
|
||||
reader := bufio.NewReader(os.Stdin)
|
||||
count, deleted := 0, 0
|
||||
for _, m := range msgs {
|
||||
count++
|
||||
fmt.Printf("\nMessage URL: https://mail.google.com/mail/u/0/#all/%v\n", m.gmailID)
|
||||
fmt.Printf("Size: %v, Date: %v, Snippet: %q\n", m.size, m.date, m.snippet)
|
||||
fmt.Printf("Options: (d)elete, (s)kip, (q)uit: [s] ")
|
||||
val := ""
|
||||
if val, err = reader.ReadString('\n'); err != nil {
|
||||
log.Fatalf("unable to scan input: %v", err)
|
||||
}
|
||||
val = strings.TrimSpace(val)
|
||||
switch val {
|
||||
case "d": // delete message
|
||||
if err := svc.Users.Messages.Delete("me", m.gmailID).Do(); err != nil {
|
||||
log.Fatalf("unable to delete message %v: %v", m.gmailID, err)
|
||||
}
|
||||
log.Printf("Deleted message %v.\n", m.gmailID)
|
||||
deleted++
|
||||
case "q": // quit
|
||||
log.Printf("Done. %v messages processed, %v deleted\n", count, deleted)
|
||||
os.Exit(0)
|
||||
default:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type messageSorter struct {
|
||||
msg []message
|
||||
less func(i, j message) bool
|
||||
}
|
||||
|
||||
func sortBySize(msg []message) {
|
||||
sort.Sort(messageSorter{msg, func(i, j message) bool {
|
||||
return i.size > j.size
|
||||
}})
|
||||
}
|
||||
|
||||
func (s messageSorter) Len() int {
|
||||
return len(s.msg)
|
||||
}
|
||||
|
||||
func (s messageSorter) Swap(i, j int) {
|
||||
s.msg[i], s.msg[j] = s.msg[j], s.msg[i]
|
||||
}
|
||||
|
||||
func (s messageSorter) Less(i, j int) bool {
|
||||
return s.less(s.msg[i], s.msg[j])
|
||||
}
|
BIN
vendor/google.golang.org/api/examples/gopher.png
generated
vendored
Normal file
BIN
vendor/google.golang.org/api/examples/gopher.png
generated
vendored
Normal file
Binary file not shown.
After Width: | Height: | Size: 22 KiB |
206
vendor/google.golang.org/api/examples/main.go
generated
vendored
Normal file
206
vendor/google.golang.org/api/examples/main.go
generated
vendored
Normal file
|
@ -0,0 +1,206 @@
|
|||
// Copyright 2011 Google Inc. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/gob"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"hash/fnv"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"golang.org/x/net/context"
|
||||
"golang.org/x/oauth2"
|
||||
"golang.org/x/oauth2/google"
|
||||
)
|
||||
|
||||
// Flags
|
||||
var (
|
||||
clientID = flag.String("clientid", "", "OAuth 2.0 Client ID. If non-empty, overrides --clientid_file")
|
||||
clientIDFile = flag.String("clientid-file", "clientid.dat",
|
||||
"Name of a file containing just the project's OAuth 2.0 Client ID from https://developers.google.com/console.")
|
||||
secret = flag.String("secret", "", "OAuth 2.0 Client Secret. If non-empty, overrides --secret_file")
|
||||
secretFile = flag.String("secret-file", "clientsecret.dat",
|
||||
"Name of a file containing just the project's OAuth 2.0 Client Secret from https://developers.google.com/console.")
|
||||
cacheToken = flag.Bool("cachetoken", true, "cache the OAuth 2.0 token")
|
||||
debug = flag.Bool("debug", false, "show HTTP traffic")
|
||||
)
|
||||
|
||||
func usage() {
|
||||
fmt.Fprintf(os.Stderr, "Usage: go-api-demo <api-demo-name> [api name args]\n\nPossible APIs:\n\n")
|
||||
for n := range demoFunc {
|
||||
fmt.Fprintf(os.Stderr, " * %s\n", n)
|
||||
}
|
||||
os.Exit(2)
|
||||
}
|
||||
|
||||
func main() {
|
||||
flag.Parse()
|
||||
if flag.NArg() == 0 {
|
||||
usage()
|
||||
}
|
||||
|
||||
name := flag.Arg(0)
|
||||
demo, ok := demoFunc[name]
|
||||
if !ok {
|
||||
usage()
|
||||
}
|
||||
|
||||
config := &oauth2.Config{
|
||||
ClientID: valueOrFileContents(*clientID, *clientIDFile),
|
||||
ClientSecret: valueOrFileContents(*secret, *secretFile),
|
||||
Endpoint: google.Endpoint,
|
||||
Scopes: []string{demoScope[name]},
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
if *debug {
|
||||
ctx = context.WithValue(ctx, oauth2.HTTPClient, &http.Client{
|
||||
Transport: &logTransport{http.DefaultTransport},
|
||||
})
|
||||
}
|
||||
c := newOAuthClient(ctx, config)
|
||||
demo(c, flag.Args()[1:])
|
||||
}
|
||||
|
||||
var (
|
||||
demoFunc = make(map[string]func(*http.Client, []string))
|
||||
demoScope = make(map[string]string)
|
||||
)
|
||||
|
||||
func registerDemo(name, scope string, main func(c *http.Client, argv []string)) {
|
||||
if demoFunc[name] != nil {
|
||||
panic(name + " already registered")
|
||||
}
|
||||
demoFunc[name] = main
|
||||
demoScope[name] = scope
|
||||
}
|
||||
|
||||
func osUserCacheDir() string {
|
||||
switch runtime.GOOS {
|
||||
case "darwin":
|
||||
return filepath.Join(os.Getenv("HOME"), "Library", "Caches")
|
||||
case "linux", "freebsd":
|
||||
return filepath.Join(os.Getenv("HOME"), ".cache")
|
||||
}
|
||||
log.Printf("TODO: osUserCacheDir on GOOS %q", runtime.GOOS)
|
||||
return "."
|
||||
}
|
||||
|
||||
func tokenCacheFile(config *oauth2.Config) string {
|
||||
hash := fnv.New32a()
|
||||
hash.Write([]byte(config.ClientID))
|
||||
hash.Write([]byte(config.ClientSecret))
|
||||
hash.Write([]byte(strings.Join(config.Scopes, " ")))
|
||||
fn := fmt.Sprintf("go-api-demo-tok%v", hash.Sum32())
|
||||
return filepath.Join(osUserCacheDir(), url.QueryEscape(fn))
|
||||
}
|
||||
|
||||
func tokenFromFile(file string) (*oauth2.Token, error) {
|
||||
if !*cacheToken {
|
||||
return nil, errors.New("--cachetoken is false")
|
||||
}
|
||||
f, err := os.Open(file)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
t := new(oauth2.Token)
|
||||
err = gob.NewDecoder(f).Decode(t)
|
||||
return t, err
|
||||
}
|
||||
|
||||
func saveToken(file string, token *oauth2.Token) {
|
||||
f, err := os.Create(file)
|
||||
if err != nil {
|
||||
log.Printf("Warning: failed to cache oauth token: %v", err)
|
||||
return
|
||||
}
|
||||
defer f.Close()
|
||||
gob.NewEncoder(f).Encode(token)
|
||||
}
|
||||
|
||||
func newOAuthClient(ctx context.Context, config *oauth2.Config) *http.Client {
|
||||
cacheFile := tokenCacheFile(config)
|
||||
token, err := tokenFromFile(cacheFile)
|
||||
if err != nil {
|
||||
token = tokenFromWeb(ctx, config)
|
||||
saveToken(cacheFile, token)
|
||||
} else {
|
||||
log.Printf("Using cached token %#v from %q", token, cacheFile)
|
||||
}
|
||||
|
||||
return config.Client(ctx, token)
|
||||
}
|
||||
|
||||
func tokenFromWeb(ctx context.Context, config *oauth2.Config) *oauth2.Token {
|
||||
ch := make(chan string)
|
||||
randState := fmt.Sprintf("st%d", time.Now().UnixNano())
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
|
||||
if req.URL.Path == "/favicon.ico" {
|
||||
http.Error(rw, "", 404)
|
||||
return
|
||||
}
|
||||
if req.FormValue("state") != randState {
|
||||
log.Printf("State doesn't match: req = %#v", req)
|
||||
http.Error(rw, "", 500)
|
||||
return
|
||||
}
|
||||
if code := req.FormValue("code"); code != "" {
|
||||
fmt.Fprintf(rw, "<h1>Success</h1>Authorized.")
|
||||
rw.(http.Flusher).Flush()
|
||||
ch <- code
|
||||
return
|
||||
}
|
||||
log.Printf("no code")
|
||||
http.Error(rw, "", 500)
|
||||
}))
|
||||
defer ts.Close()
|
||||
|
||||
config.RedirectURL = ts.URL
|
||||
authURL := config.AuthCodeURL(randState)
|
||||
go openURL(authURL)
|
||||
log.Printf("Authorize this app at: %s", authURL)
|
||||
code := <-ch
|
||||
log.Printf("Got code: %s", code)
|
||||
|
||||
token, err := config.Exchange(ctx, code)
|
||||
if err != nil {
|
||||
log.Fatalf("Token exchange error: %v", err)
|
||||
}
|
||||
return token
|
||||
}
|
||||
|
||||
func openURL(url string) {
|
||||
try := []string{"xdg-open", "google-chrome", "open"}
|
||||
for _, bin := range try {
|
||||
err := exec.Command(bin, url).Run()
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
log.Printf("Error opening URL in browser.")
|
||||
}
|
||||
|
||||
func valueOrFileContents(value string, filename string) string {
|
||||
if value != "" {
|
||||
return value
|
||||
}
|
||||
slurp, err := ioutil.ReadFile(filename)
|
||||
if err != nil {
|
||||
log.Fatalf("Error reading %q: %v", filename, err)
|
||||
}
|
||||
return strings.TrimSpace(string(slurp))
|
||||
}
|
93
vendor/google.golang.org/api/examples/mapsengine.go
generated
vendored
Normal file
93
vendor/google.golang.org/api/examples/mapsengine.go
generated
vendored
Normal file
|
@ -0,0 +1,93 @@
|
|||
// Copyright 2014 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
mapsengine "google.golang.org/api/mapsengine/v1"
|
||||
)
|
||||
|
||||
func init() {
|
||||
scopes := []string{
|
||||
mapsengine.MapsengineScope,
|
||||
mapsengine.MapsengineReadonlyScope,
|
||||
}
|
||||
registerDemo("mapsengine", strings.Join(scopes, " "), mapsengineMain)
|
||||
}
|
||||
|
||||
func showMapFeatures(svc *mapsengine.Service, id string) {
|
||||
r, err := svc.Tables.Get(id).Version("published").Do()
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to get map %v table: %v", id, err)
|
||||
}
|
||||
fmt.Printf("Map ID: %v, Name: %q, Description: %q\n", id, r.Name, r.Description)
|
||||
|
||||
pageToken := ""
|
||||
for {
|
||||
time.Sleep(1 * time.Second) // Don't violate free rate limit
|
||||
// Read the location of every Feature in a Table.
|
||||
req := svc.Tables.Features.List(id).MaxResults(500).Version("published")
|
||||
if pageToken != "" {
|
||||
req.PageToken(pageToken)
|
||||
}
|
||||
r, err := req.Do()
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to list table features: %v", err)
|
||||
}
|
||||
|
||||
for _, f := range r.Features {
|
||||
if v, ok := f.Geometry.GeometryCollection(); ok {
|
||||
fmt.Printf("%v: %v\n", f.Geometry.Type(), v)
|
||||
} else if v, ok := f.Geometry.LineString(); ok {
|
||||
fmt.Printf("%v: %v\n", f.Geometry.Type(), v)
|
||||
} else if v, ok := f.Geometry.MultiLineString(); ok {
|
||||
fmt.Printf("%v: %v\n", f.Geometry.Type(), v)
|
||||
} else if v, ok := f.Geometry.MultiPoint(); ok {
|
||||
fmt.Printf("%v: %v\n", f.Geometry.Type(), v)
|
||||
} else if v, ok := f.Geometry.MultiPolygon(); ok {
|
||||
fmt.Printf("%v: %v\n", f.Geometry.Type(), v)
|
||||
} else if v, ok := f.Geometry.Point(); ok {
|
||||
fmt.Printf("%v: %v\n", f.Geometry.Type(), v)
|
||||
} else if v, ok := f.Geometry.Polygon(); ok {
|
||||
fmt.Printf("%v: %v\n", f.Geometry.Type(), v)
|
||||
} else {
|
||||
log.Fatalf("Unknown GeoJsonGeometry type %q", f.Geometry.Type())
|
||||
}
|
||||
}
|
||||
|
||||
if r.NextPageToken == "" {
|
||||
break
|
||||
}
|
||||
pageToken = r.NextPageToken
|
||||
}
|
||||
}
|
||||
|
||||
// mapsengineMain is an example that demonstrates calling the Mapsengine API.
|
||||
// Please see https://developers.google.com/maps-engine/documentation/hello-world#go
|
||||
// for more information.
|
||||
//
|
||||
// Example usage:
|
||||
// go build -o go-api-demo *.go
|
||||
// go-api-demo -clientid="my-clientid" -secret="my-secret" mapsengine
|
||||
func mapsengineMain(client *http.Client, argv []string) {
|
||||
if len(argv) != 0 {
|
||||
fmt.Fprintln(os.Stderr, "Usage: mapsengine")
|
||||
return
|
||||
}
|
||||
|
||||
svc, err := mapsengine.New(client)
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to create Mapsengine service: %v", err)
|
||||
}
|
||||
|
||||
showMapFeatures(svc, "14137585153106784136-16071188762309719429")
|
||||
showMapFeatures(svc, "12421761926155747447-06672618218968397709")
|
||||
}
|
97
vendor/google.golang.org/api/examples/mirror.go
generated
vendored
Normal file
97
vendor/google.golang.org/api/examples/mirror.go
generated
vendored
Normal file
|
@ -0,0 +1,97 @@
|
|||
// Copyright 2014 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
mirror "google.golang.org/api/mirror/v1"
|
||||
)
|
||||
|
||||
const mirrorLayout = "Jan 2, 2006 at 3:04pm"
|
||||
|
||||
func init() {
|
||||
scopes := []string{
|
||||
mirror.GlassLocationScope,
|
||||
mirror.GlassTimelineScope,
|
||||
}
|
||||
registerDemo("mirror", strings.Join(scopes, " "), mirrorMain)
|
||||
}
|
||||
|
||||
// mirrorMain is an example that demonstrates calling the Mirror API.
|
||||
//
|
||||
// Example usage:
|
||||
// go build -o go-api-demo *.go
|
||||
// go-api-demo -clientid="my-clientid" -secret="my-secret" mirror
|
||||
func mirrorMain(client *http.Client, argv []string) {
|
||||
if len(argv) != 0 {
|
||||
fmt.Fprintln(os.Stderr, "Usage: mirror")
|
||||
return
|
||||
}
|
||||
|
||||
svc, err := mirror.New(client)
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to create Mirror service: %v", err)
|
||||
}
|
||||
|
||||
cs, err := svc.Contacts.List().Do()
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to retrieve glass contacts: %v", err)
|
||||
}
|
||||
|
||||
if len(cs.Items) == 0 {
|
||||
log.Printf("You have no glass contacts. Let's add one.")
|
||||
mom := &mirror.Contact{
|
||||
DisplayName: "Mom",
|
||||
Id: "mom",
|
||||
PhoneNumber: "123-456-7890",
|
||||
SpeakableName: "mom",
|
||||
}
|
||||
_, err := svc.Contacts.Insert(mom).Do()
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to add %v to glass contacts: %v", mom.DisplayName, err)
|
||||
}
|
||||
}
|
||||
for _, c := range cs.Items {
|
||||
log.Printf("Found glass contact %q, phone number: %v", c.DisplayName, c.PhoneNumber)
|
||||
}
|
||||
|
||||
ls, err := svc.Locations.List().Do()
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to retrieve glass locations: %v", err)
|
||||
}
|
||||
|
||||
if len(ls.Items) == 0 {
|
||||
log.Printf("You have no glass locations.")
|
||||
}
|
||||
for _, loc := range ls.Items {
|
||||
t, err := time.Parse(time.RFC3339, loc.Timestamp)
|
||||
if err != nil {
|
||||
log.Printf("unable to parse time %q: %v", loc.Timestamp, err)
|
||||
}
|
||||
log.Printf("Found glass location: %q at %v, address: %v (lat=%v, lon=%v)", loc.DisplayName, t.Format(mirrorLayout), loc.Address, loc.Latitude, loc.Longitude)
|
||||
}
|
||||
|
||||
ts, err := svc.Timeline.List().Do()
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to retrieve glass timeline: %v", err)
|
||||
}
|
||||
|
||||
if len(ts.Items) == 0 {
|
||||
log.Printf("You have no glass timeline items.")
|
||||
}
|
||||
for _, v := range ts.Items {
|
||||
t, err := time.Parse(time.RFC3339, v.Updated)
|
||||
if err != nil {
|
||||
log.Printf("unable to parse time %q: %v", v.Updated, err)
|
||||
}
|
||||
log.Printf("Found glass timeline item: %q at %v", v.Text, t.Format(mirrorLayout))
|
||||
}
|
||||
}
|
137
vendor/google.golang.org/api/examples/prediction.go
generated
vendored
Normal file
137
vendor/google.golang.org/api/examples/prediction.go
generated
vendored
Normal file
|
@ -0,0 +1,137 @@
|
|||
// Copyright 2014 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"google.golang.org/api/googleapi"
|
||||
prediction "google.golang.org/api/prediction/v1.6"
|
||||
)
|
||||
|
||||
func init() {
|
||||
scopes := []string{
|
||||
prediction.DevstorageFullControlScope,
|
||||
prediction.DevstorageReadOnlyScope,
|
||||
prediction.DevstorageReadWriteScope,
|
||||
prediction.PredictionScope,
|
||||
}
|
||||
registerDemo("prediction", strings.Join(scopes, " "), predictionMain)
|
||||
}
|
||||
|
||||
type predictionType struct {
|
||||
api *prediction.Service
|
||||
projectNumber string
|
||||
bucketName string
|
||||
trainingFileName string
|
||||
modelName string
|
||||
}
|
||||
|
||||
// This example demonstrates calling the Prediction API.
|
||||
// Training data is uploaded to a pre-created Google Cloud Storage Bucket and
|
||||
// then the Prediction API is called to train a model based on that data.
|
||||
// After a few minutes, the model should be completely trained and ready
|
||||
// for prediction. At that point, text is sent to the model and the Prediction
|
||||
// API attempts to classify the data, and the results are printed out.
|
||||
//
|
||||
// To get started, follow the instructions found in the "Hello Prediction!"
|
||||
// Getting Started Guide located here:
|
||||
// https://developers.google.com/prediction/docs/hello_world
|
||||
//
|
||||
// Example usage:
|
||||
// go-api-demo -clientid="my-clientid" -secret="my-secret" prediction
|
||||
// my-project-number my-bucket-name my-training-filename my-model-name
|
||||
//
|
||||
// Example output:
|
||||
// Predict result: language=Spanish
|
||||
// English Score: 0.000000
|
||||
// French Score: 0.000000
|
||||
// Spanish Score: 1.000000
|
||||
// analyze: output feature text=&{157 English}
|
||||
// analyze: output feature text=&{149 French}
|
||||
// analyze: output feature text=&{100 Spanish}
|
||||
// feature text count=406
|
||||
func predictionMain(client *http.Client, argv []string) {
|
||||
if len(argv) != 4 {
|
||||
fmt.Fprintln(os.Stderr,
|
||||
"Usage: prediction project_number bucket training_data model_name")
|
||||
return
|
||||
}
|
||||
|
||||
api, err := prediction.New(client)
|
||||
if err != nil {
|
||||
log.Fatalf("unable to create prediction API client: %v", err)
|
||||
}
|
||||
|
||||
t := &predictionType{
|
||||
api: api,
|
||||
projectNumber: argv[0],
|
||||
bucketName: argv[1],
|
||||
trainingFileName: argv[2],
|
||||
modelName: argv[3],
|
||||
}
|
||||
|
||||
t.trainModel()
|
||||
t.predictModel()
|
||||
}
|
||||
|
||||
func (t *predictionType) trainModel() {
|
||||
// First, check to see if our trained model already exists.
|
||||
res, err := t.api.Trainedmodels.Get(t.projectNumber, t.modelName).Do()
|
||||
if err != nil {
|
||||
if ae, ok := err.(*googleapi.Error); ok && ae.Code != http.StatusNotFound {
|
||||
log.Fatalf("error getting trained model: %v", err)
|
||||
}
|
||||
log.Printf("Training model not found, creating new model.")
|
||||
res, err = t.api.Trainedmodels.Insert(t.projectNumber, &prediction.Insert{
|
||||
Id: t.modelName,
|
||||
StorageDataLocation: filepath.Join(t.bucketName, t.trainingFileName),
|
||||
}).Do()
|
||||
if err != nil {
|
||||
log.Fatalf("unable to create trained model: %v", err)
|
||||
}
|
||||
}
|
||||
if res.TrainingStatus != "DONE" {
|
||||
// Wait for the trained model to finish training.
|
||||
fmt.Printf("Training model. Please wait and re-run program after a few minutes.")
|
||||
os.Exit(0)
|
||||
}
|
||||
}
|
||||
|
||||
func (t *predictionType) predictModel() {
|
||||
// Model has now been trained. Predict with it.
|
||||
input := &prediction.Input{
|
||||
Input: &prediction.InputInput{
|
||||
CsvInstance: []interface{}{
|
||||
"Hola, con quien hablo",
|
||||
},
|
||||
},
|
||||
}
|
||||
res, err := t.api.Trainedmodels.Predict(t.projectNumber, t.modelName, input).Do()
|
||||
if err != nil {
|
||||
log.Fatalf("unable to get trained prediction: %v", err)
|
||||
}
|
||||
fmt.Printf("Predict result: language=%v\n", res.OutputLabel)
|
||||
for _, m := range res.OutputMulti {
|
||||
fmt.Printf("%v Score: %v\n", m.Label, m.Score)
|
||||
}
|
||||
|
||||
// Now analyze the model.
|
||||
an, err := t.api.Trainedmodels.Analyze(t.projectNumber, t.modelName).Do()
|
||||
if err != nil {
|
||||
log.Fatalf("unable to analyze trained model: %v", err)
|
||||
}
|
||||
for _, f := range an.DataDescription.OutputFeature.Text {
|
||||
fmt.Printf("analyze: output feature text=%v\n", f)
|
||||
}
|
||||
for _, f := range an.DataDescription.Features {
|
||||
fmt.Printf("feature text count=%v\n", f.Text.Count)
|
||||
}
|
||||
}
|
333
vendor/google.golang.org/api/examples/pubsub.go
generated
vendored
Normal file
333
vendor/google.golang.org/api/examples/pubsub.go
generated
vendored
Normal file
|
@ -0,0 +1,333 @@
|
|||
// Copyright 2017 Google Inc. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/textproto"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
pubsub "google.golang.org/api/pubsub/v1beta2"
|
||||
)
|
||||
|
||||
const USAGE = `Available arguments are:
|
||||
<project_id> list_topics
|
||||
<project_id> create_topic <topic>
|
||||
<project_id> delete_topic <topic>
|
||||
<project_id> list_subscriptions
|
||||
<project_id> create_subscription <subscription> <linked topic>
|
||||
<project_id> delete_subscription <subscription>
|
||||
<project_id> connect_irc <topic> <server> <channel>
|
||||
<project_id> pull_messages <subscription>
|
||||
`
|
||||
|
||||
type IRCBot struct {
|
||||
server string
|
||||
port string
|
||||
nick string
|
||||
user string
|
||||
channel string
|
||||
conn net.Conn
|
||||
tpReader *textproto.Reader
|
||||
}
|
||||
|
||||
func NewIRCBot(server, channel, nick string) *IRCBot {
|
||||
return &IRCBot{
|
||||
server: server,
|
||||
port: "6667",
|
||||
nick: nick,
|
||||
channel: channel,
|
||||
conn: nil,
|
||||
user: nick,
|
||||
}
|
||||
}
|
||||
|
||||
func (bot *IRCBot) Connect() {
|
||||
conn, err := net.Dial("tcp", bot.server+":"+bot.port)
|
||||
if err != nil {
|
||||
log.Fatal("unable to connect to IRC server ", err)
|
||||
}
|
||||
bot.conn = conn
|
||||
log.Printf("Connected to IRC server %s (%s)\n",
|
||||
bot.server, bot.conn.RemoteAddr())
|
||||
bot.tpReader = textproto.NewReader(bufio.NewReader(bot.conn))
|
||||
bot.Sendf("USER %s 8 * :%s\r\n", bot.nick, bot.nick)
|
||||
bot.Sendf("NICK %s\r\n", bot.nick)
|
||||
bot.Sendf("JOIN %s\r\n", bot.channel)
|
||||
}
|
||||
|
||||
func (bot *IRCBot) CheckConnection() {
|
||||
for {
|
||||
line, err := bot.ReadLine()
|
||||
if err != nil {
|
||||
log.Fatal("Unable to read a line during checking the connection.")
|
||||
}
|
||||
if parts := strings.Split(line, " "); len(parts) > 1 {
|
||||
if parts[1] == "004" {
|
||||
log.Println("The nick accepted.")
|
||||
} else if parts[1] == "433" {
|
||||
log.Fatalf("The nick is already in use: %s", line)
|
||||
} else if parts[1] == "366" {
|
||||
log.Println("Starting to publish messages.")
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (bot *IRCBot) Sendf(format string, args ...interface{}) {
|
||||
fmt.Fprintf(bot.conn, format, args...)
|
||||
}
|
||||
|
||||
func (bot *IRCBot) Close() {
|
||||
bot.conn.Close()
|
||||
}
|
||||
|
||||
func (bot *IRCBot) ReadLine() (line string, err error) {
|
||||
return bot.tpReader.ReadLine()
|
||||
}
|
||||
|
||||
func init() {
|
||||
registerDemo("pubsub", pubsub.PubsubScope, pubsubMain)
|
||||
}
|
||||
|
||||
func pubsubUsage() {
|
||||
fmt.Fprint(os.Stderr, USAGE)
|
||||
}
|
||||
|
||||
// Returns a fully qualified resource name for Cloud Pub/Sub.
|
||||
func fqrn(res, proj, name string) string {
|
||||
return fmt.Sprintf("projects/%s/%s/%s", proj, res, name)
|
||||
}
|
||||
|
||||
func fullTopicName(proj, topic string) string {
|
||||
return fqrn("topics", proj, topic)
|
||||
}
|
||||
|
||||
func fullSubName(proj, topic string) string {
|
||||
return fqrn("subscriptions", proj, topic)
|
||||
}
|
||||
|
||||
// Check the length of the arguments.
|
||||
func checkArgs(argv []string, min int) {
|
||||
if len(argv) < min {
|
||||
pubsubUsage()
|
||||
os.Exit(2)
|
||||
}
|
||||
}
|
||||
|
||||
func listTopics(service *pubsub.Service, argv []string) {
|
||||
next := ""
|
||||
for {
|
||||
topicsList, err := service.Projects.Topics.List(fmt.Sprintf("projects/%s", argv[0])).PageToken(next).Do()
|
||||
if err != nil {
|
||||
log.Fatalf("listTopics query.Do() failed: %v", err)
|
||||
}
|
||||
for _, topic := range topicsList.Topics {
|
||||
fmt.Println(topic.Name)
|
||||
}
|
||||
next = topicsList.NextPageToken
|
||||
if next == "" {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func createTopic(service *pubsub.Service, argv []string) {
|
||||
checkArgs(argv, 3)
|
||||
topic, err := service.Projects.Topics.Create(fullTopicName(argv[0], argv[2]), &pubsub.Topic{}).Do()
|
||||
if err != nil {
|
||||
log.Fatalf("createTopic Create().Do() failed: %v", err)
|
||||
}
|
||||
fmt.Printf("Topic %s was created.\n", topic.Name)
|
||||
}
|
||||
|
||||
func deleteTopic(service *pubsub.Service, argv []string) {
|
||||
checkArgs(argv, 3)
|
||||
topicName := fullTopicName(argv[0], argv[2])
|
||||
if _, err := service.Projects.Topics.Delete(topicName).Do(); err != nil {
|
||||
log.Fatalf("deleteTopic Delete().Do() failed: %v", err)
|
||||
}
|
||||
fmt.Printf("Topic %s was deleted.\n", topicName)
|
||||
}
|
||||
|
||||
func listSubscriptions(service *pubsub.Service, argv []string) {
|
||||
next := ""
|
||||
for {
|
||||
subscriptionsList, err := service.Projects.Subscriptions.List(fmt.Sprintf("projects/%s", argv[0])).PageToken(next).Do()
|
||||
if err != nil {
|
||||
log.Fatalf("listSubscriptions query.Do() failed: %v", err)
|
||||
}
|
||||
for _, subscription := range subscriptionsList.Subscriptions {
|
||||
sub_text, _ := json.MarshalIndent(subscription, "", " ")
|
||||
fmt.Printf("%s\n", sub_text)
|
||||
}
|
||||
next = subscriptionsList.NextPageToken
|
||||
if next == "" {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func createSubscription(service *pubsub.Service, argv []string) {
|
||||
checkArgs(argv, 4)
|
||||
name := fullSubName(argv[0], argv[2])
|
||||
sub := &pubsub.Subscription{Topic: fullTopicName(argv[0], argv[3])}
|
||||
subscription, err := service.Projects.Subscriptions.Create(name, sub).Do()
|
||||
if err != nil {
|
||||
log.Fatalf("createSubscription Create().Do() failed: %v", err)
|
||||
}
|
||||
fmt.Printf("Subscription %s was created.\n", subscription.Name)
|
||||
}
|
||||
|
||||
func deleteSubscription(service *pubsub.Service, argv []string) {
|
||||
checkArgs(argv, 3)
|
||||
name := fullSubName(argv[0], argv[2])
|
||||
if _, err := service.Projects.Subscriptions.Delete(name).Do(); err != nil {
|
||||
log.Fatalf("deleteSubscription Delete().Do() failed: %v", err)
|
||||
}
|
||||
fmt.Printf("Subscription %s was deleted.\n", name)
|
||||
}
|
||||
|
||||
func connectIRC(service *pubsub.Service, argv []string) {
|
||||
checkArgs(argv, 5)
|
||||
topicName := fullTopicName(argv[0], argv[2])
|
||||
server := argv[3]
|
||||
channel := argv[4]
|
||||
nick := fmt.Sprintf("bot-%s", argv[2])
|
||||
ircbot := NewIRCBot(server, channel, nick)
|
||||
ircbot.Connect()
|
||||
defer ircbot.Close()
|
||||
ircbot.CheckConnection()
|
||||
privMark := fmt.Sprintf("PRIVMSG %s :", ircbot.channel)
|
||||
for {
|
||||
line, err := ircbot.ReadLine()
|
||||
if err != nil {
|
||||
log.Fatal("Unable to read a line from the connection.")
|
||||
}
|
||||
parts := strings.Split(line, " ")
|
||||
if len(parts) > 0 && parts[0] == "PING" {
|
||||
ircbot.Sendf("PONG %s\r\n", parts[1])
|
||||
} else {
|
||||
pos := strings.Index(line, privMark)
|
||||
if pos == -1 {
|
||||
continue
|
||||
}
|
||||
privMsg := line[pos+len(privMark) : len(line)]
|
||||
pubsubMessage := &pubsub.PubsubMessage{
|
||||
Data: base64.StdEncoding.EncodeToString([]byte(privMsg)),
|
||||
}
|
||||
publishRequest := &pubsub.PublishRequest{
|
||||
Messages: []*pubsub.PubsubMessage{pubsubMessage},
|
||||
}
|
||||
if _, err := service.Projects.Topics.Publish(topicName, publishRequest).Do(); err != nil {
|
||||
log.Fatalf("connectIRC Publish().Do() failed: %v", err)
|
||||
}
|
||||
log.Println("Published a message to the topic.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func pullMessages(service *pubsub.Service, argv []string) {
|
||||
checkArgs(argv, 3)
|
||||
subName := fullSubName(argv[0], argv[2])
|
||||
pullRequest := &pubsub.PullRequest{
|
||||
ReturnImmediately: false,
|
||||
MaxMessages: 1,
|
||||
}
|
||||
for {
|
||||
pullResponse, err := service.Projects.Subscriptions.Pull(subName, pullRequest).Do()
|
||||
if err != nil {
|
||||
log.Fatalf("pullMessages Pull().Do() failed: %v", err)
|
||||
}
|
||||
for _, receivedMessage := range pullResponse.ReceivedMessages {
|
||||
data, err := base64.StdEncoding.DecodeString(receivedMessage.Message.Data)
|
||||
if err != nil {
|
||||
log.Fatalf("pullMessages DecodeString() failed: %v", err)
|
||||
}
|
||||
fmt.Printf("%s\n", data)
|
||||
ackRequest := &pubsub.AcknowledgeRequest{
|
||||
AckIds: []string{receivedMessage.AckId},
|
||||
}
|
||||
if _, err = service.Projects.Subscriptions.Acknowledge(subName, ackRequest).Do(); err != nil {
|
||||
log.Printf("pullMessages Acknowledge().Do() failed: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// This example demonstrates calling the Cloud Pub/Sub API. As of 20
|
||||
// Aug 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/
|
||||
//
|
||||
// It has 8 subcommands as follows:
|
||||
//
|
||||
// <project_id> list_topics
|
||||
// <project_id> create_topic <topic>
|
||||
// <project_id> delete_topic <topic>
|
||||
// <project_id> list_subscriptions
|
||||
// <project_id> create_subscription <subscription> <linked topic>
|
||||
// <project_id> delete_subscription <subscription>
|
||||
// <project_id> connect_irc <topic> <server> <channel>
|
||||
// <project_id> pull_messages <subscription>
|
||||
//
|
||||
// You can use either of your alphanumerical or numerial Cloud Project
|
||||
// ID for project_id. You can choose any names for topic and
|
||||
// subscription as long as they follow the naming rule described at:
|
||||
// https://developers.google.com/pubsub/overview#names
|
||||
//
|
||||
// You can list/create/delete topics/subscriptions by self-explanatory
|
||||
// subcommands, as well as connect to an IRC channel and publish
|
||||
// messages from the IRC channel to a specified Cloud Pub/Sub topic by
|
||||
// the "connect_irc" subcommand, or continuously pull messages from a
|
||||
// specified Cloud Pub/Sub subscription and display the data by the
|
||||
// "pull_messages" subcommand.
|
||||
func pubsubMain(client *http.Client, argv []string) {
|
||||
checkArgs(argv, 2)
|
||||
service, err := pubsub.New(client)
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to create PubSub service: %v", err)
|
||||
}
|
||||
|
||||
m := map[string]func(service *pubsub.Service, argv []string){
|
||||
"list_topics": listTopics,
|
||||
"create_topic": createTopic,
|
||||
"delete_topic": deleteTopic,
|
||||
"list_subscriptions": listSubscriptions,
|
||||
"create_subscription": createSubscription,
|
||||
"delete_subscription": deleteSubscription,
|
||||
"connect_irc": connectIRC,
|
||||
"pull_messages": pullMessages,
|
||||
}
|
||||
f, ok := m[argv[1]]
|
||||
if !ok {
|
||||
pubsubUsage()
|
||||
os.Exit(2)
|
||||
}
|
||||
f(service, argv)
|
||||
}
|
78
vendor/google.golang.org/api/examples/storage.go
generated
vendored
Normal file
78
vendor/google.golang.org/api/examples/storage.go
generated
vendored
Normal file
|
@ -0,0 +1,78 @@
|
|||
// Copyright 2017 Google Inc. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
|
||||
"google.golang.org/api/googleapi"
|
||||
storage "google.golang.org/api/storage/v1"
|
||||
)
|
||||
|
||||
func init() {
|
||||
registerDemo("storage", storage.DevstorageReadWriteScope, storageMain)
|
||||
}
|
||||
|
||||
func storageMain(client *http.Client, argv []string) {
|
||||
if len(argv) != 2 {
|
||||
fmt.Fprintln(os.Stderr, "Usage: storage filename bucket (to upload an object)")
|
||||
return
|
||||
}
|
||||
|
||||
service, err := storage.New(client)
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to create Storage service: %v", err)
|
||||
}
|
||||
|
||||
filename := argv[0]
|
||||
bucket := argv[1]
|
||||
|
||||
goFile, err := os.Open(filename)
|
||||
if err != nil {
|
||||
log.Fatalf("error opening %q: %v", filename, err)
|
||||
}
|
||||
storageObject, err := service.Objects.Insert(bucket, &storage.Object{Name: filename}).Media(goFile).Do()
|
||||
log.Printf("Got storage.Object, err: %#v, %v", storageObject, err)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := service.Objects.Get(bucket, filename).Download()
|
||||
if err != nil {
|
||||
log.Fatalf("error downloading %q: %v", filename, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
n, err := io.Copy(ioutil.Discard, resp.Body)
|
||||
if err != nil {
|
||||
log.Fatalf("error downloading %q: %v", filename, err)
|
||||
}
|
||||
|
||||
log.Printf("Downloaded %d bytes", n)
|
||||
|
||||
// Test If-None-Match - should get a "HTTP 304 Not Modified" response.
|
||||
obj, err := service.Objects.Get(bucket, filename).IfNoneMatch(storageObject.Etag).Do()
|
||||
log.Printf("Got obj, err: %#v, %v", obj, err)
|
||||
if googleapi.IsNotModified(err) {
|
||||
log.Printf("Success. Object not modified since upload.")
|
||||
} else {
|
||||
log.Printf("Error: expected object to not be modified since upload.")
|
||||
}
|
||||
}
|
40
vendor/google.golang.org/api/examples/tasks.go
generated
vendored
Normal file
40
vendor/google.golang.org/api/examples/tasks.go
generated
vendored
Normal file
|
@ -0,0 +1,40 @@
|
|||
// Copyright 2017 Google Inc. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
tasks "google.golang.org/api/tasks/v1"
|
||||
)
|
||||
|
||||
func init() {
|
||||
registerDemo("tasks", tasks.TasksScope, tasksMain)
|
||||
}
|
||||
|
||||
func tasksMain(client *http.Client, argv []string) {
|
||||
taskapi, err := tasks.New(client)
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to create Tasks service: %v", err)
|
||||
}
|
||||
|
||||
task, err := taskapi.Tasks.Insert("@default", &tasks.Task{
|
||||
Title: "finish this API code generator thing",
|
||||
Notes: "ummmm",
|
||||
Due: "2011-10-15T12:00:00.000Z",
|
||||
}).Do()
|
||||
log.Printf("Got task, err: %#v, %v", task, err)
|
||||
}
|
64
vendor/google.golang.org/api/examples/urlshortener.go
generated
vendored
Normal file
64
vendor/google.golang.org/api/examples/urlshortener.go
generated
vendored
Normal file
|
@ -0,0 +1,64 @@
|
|||
// Copyright 2017 Google Inc. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
urlshortener "google.golang.org/api/urlshortener/v1"
|
||||
)
|
||||
|
||||
func init() {
|
||||
registerDemo("urlshortener", urlshortener.UrlshortenerScope, urlShortenerMain)
|
||||
}
|
||||
|
||||
func urlShortenerMain(client *http.Client, argv []string) {
|
||||
if len(argv) != 1 {
|
||||
fmt.Fprintf(os.Stderr, "Usage: urlshortener http://goo.gl/xxxxx (to look up details)\n")
|
||||
fmt.Fprintf(os.Stderr, " urlshortener http://example.com/long (to shorten)\n")
|
||||
return
|
||||
}
|
||||
|
||||
svc, err := urlshortener.New(client)
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to create UrlShortener service: %v", err)
|
||||
}
|
||||
|
||||
urlstr := argv[0]
|
||||
|
||||
// short -> long
|
||||
if strings.HasPrefix(urlstr, "http://goo.gl/") || strings.HasPrefix(urlstr, "https://goo.gl/") {
|
||||
url, err := svc.Url.Get(urlstr).Do()
|
||||
if err != nil {
|
||||
log.Fatalf("URL Get: %v", err)
|
||||
}
|
||||
fmt.Printf("Lookup of %s: %s\n", urlstr, url.LongUrl)
|
||||
return
|
||||
}
|
||||
|
||||
// long -> short
|
||||
url, err := svc.Url.Insert(&urlshortener.Url{
|
||||
Kind: "urlshortener#url", // Not really needed
|
||||
LongUrl: urlstr,
|
||||
}).Do()
|
||||
if err != nil {
|
||||
log.Fatalf("URL Insert: %v", err)
|
||||
}
|
||||
fmt.Printf("Shortened %s => %s\n", urlstr, url.Id)
|
||||
}
|
65
vendor/google.golang.org/api/examples/youtube.go
generated
vendored
Normal file
65
vendor/google.golang.org/api/examples/youtube.go
generated
vendored
Normal file
|
@ -0,0 +1,65 @@
|
|||
// Copyright 2015 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
|
||||
youtube "google.golang.org/api/youtube/v3"
|
||||
)
|
||||
|
||||
func init() {
|
||||
registerDemo("youtube", youtube.YoutubeUploadScope, youtubeMain)
|
||||
}
|
||||
|
||||
// youtubeMain is an example that demonstrates calling the YouTube API.
|
||||
// It is similar to the sample found on the Google Developers website:
|
||||
// https://developers.google.com/youtube/v3/docs/videos/insert
|
||||
// but has been modified slightly to fit into the examples framework.
|
||||
//
|
||||
// Example usage:
|
||||
// go build -o go-api-demo
|
||||
// go-api-demo -clientid="my-clientid" -secret="my-secret" youtube filename
|
||||
func youtubeMain(client *http.Client, argv []string) {
|
||||
if len(argv) < 1 {
|
||||
fmt.Fprintln(os.Stderr, "Usage: youtube filename")
|
||||
return
|
||||
}
|
||||
filename := argv[0]
|
||||
|
||||
service, err := youtube.New(client)
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to create YouTube service: %v", err)
|
||||
}
|
||||
|
||||
upload := &youtube.Video{
|
||||
Snippet: &youtube.VideoSnippet{
|
||||
Title: "Test Title",
|
||||
Description: "Test Description", // can not use non-alpha-numeric characters
|
||||
CategoryId: "22",
|
||||
},
|
||||
Status: &youtube.VideoStatus{PrivacyStatus: "unlisted"},
|
||||
}
|
||||
|
||||
// The API returns a 400 Bad Request response if tags is an empty string.
|
||||
upload.Snippet.Tags = []string{"test", "upload", "api"}
|
||||
|
||||
call := service.Videos.Insert("snippet,status", upload)
|
||||
|
||||
file, err := os.Open(filename)
|
||||
defer file.Close()
|
||||
if err != nil {
|
||||
log.Fatalf("Error opening %v: %v", filename, err)
|
||||
}
|
||||
|
||||
response, err := call.Media(file).Do()
|
||||
if err != nil {
|
||||
log.Fatalf("Error making YouTube API call: %v", err)
|
||||
}
|
||||
fmt.Printf("Upload successful! Video ID: %v\n", response.Id)
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue