fix(git): add vendor in .gitignore
This commit is contained in:
11
vendor/google.golang.org/api/AUTHORS
generated
vendored
11
vendor/google.golang.org/api/AUTHORS
generated
vendored
@@ -1,11 +0,0 @@
|
||||
# This is the official list of authors for copyright purposes.
|
||||
# This file is distinct from the CONTRIBUTORS files.
|
||||
# See the latter for an explanation.
|
||||
|
||||
# Names should be added to this file as
|
||||
# Name or Organization <email address>
|
||||
# The email address is not required for organizations.
|
||||
|
||||
# Please keep the list sorted.
|
||||
Google Inc.
|
||||
LightStep Inc.
|
||||
56
vendor/google.golang.org/api/CONTRIBUTORS
generated
vendored
56
vendor/google.golang.org/api/CONTRIBUTORS
generated
vendored
@@ -1,56 +0,0 @@
|
||||
# This is the official list of people who can contribute
|
||||
# (and typically have contributed) code to the repository.
|
||||
# The AUTHORS file lists the copyright holders; this file
|
||||
# lists people. For example, Google employees are listed here
|
||||
# but not in AUTHORS, because Google holds the copyright.
|
||||
#
|
||||
# The submission process automatically checks to make sure
|
||||
# that people submitting code are listed in this file (by email address).
|
||||
#
|
||||
# Names should be added to this file only after verifying that
|
||||
# the individual or the individual's organization has agreed to
|
||||
# the appropriate Contributor License Agreement, found here:
|
||||
#
|
||||
# https://cla.developers.google.com/about/google-individual
|
||||
# https://cla.developers.google.com/about/google-corporate
|
||||
#
|
||||
# The CLA can be filled out on the web:
|
||||
#
|
||||
# https://cla.developers.google.com/
|
||||
#
|
||||
# When adding J Random Contributor's name to this file,
|
||||
# either J's name or J's organization's name should be
|
||||
# added to the AUTHORS file, depending on whether the
|
||||
# individual or corporate CLA was used.
|
||||
|
||||
# Names should be added to this file like so:
|
||||
# Name <email address>
|
||||
#
|
||||
# An entry with two email addresses specifies that the
|
||||
# first address should be used in the submit logs and
|
||||
# that the second address should be recognized as the
|
||||
# same person when interacting with Rietveld.
|
||||
|
||||
# Please keep the list sorted.
|
||||
|
||||
Alain Vongsouvanhalainv <alainv@google.com>
|
||||
Andrew Gerrand <adg@golang.org>
|
||||
Brad Fitzpatrick <bradfitz@golang.org>
|
||||
Eric Koleda <ekoleda+devrel@googlers.com>
|
||||
Francesc Campoy <campoy@golang.org>
|
||||
Garrick Evans <garrick@google.com>
|
||||
Glenn Lewis <gmlewis@google.com>
|
||||
Ivan Krasin <krasin@golang.org>
|
||||
Jason Hall <jasonhall@google.com>
|
||||
Johan Euphrosine <proppy@google.com>
|
||||
Kostik Shtoyk <kostik@google.com>
|
||||
Kunpei Sakai <namusyaka@gmail.com>
|
||||
Matthew Dolan <dolan@lightstep.com>
|
||||
Matthew Whisenhunt <matt.whisenhunt@gmail.com>
|
||||
Michael McGreevy <mcgreevy@golang.org>
|
||||
Nick Craig-Wood <nickcw@gmail.com>
|
||||
Robbie Trencheny <me@robbiet.us>
|
||||
Ross Light <light@google.com>
|
||||
Sarah Adams <shadams@google.com>
|
||||
Scott Van Woudenberg <scottvw@google.com>
|
||||
Takashi Matsuo <tmatsuo@google.com>
|
||||
27
vendor/google.golang.org/api/LICENSE
generated
vendored
27
vendor/google.golang.org/api/LICENSE
generated
vendored
@@ -1,27 +0,0 @@
|
||||
Copyright (c) 2011 Google Inc. All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are
|
||||
met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above
|
||||
copyright notice, this list of conditions and the following disclaimer
|
||||
in the documentation and/or other materials provided with the
|
||||
distribution.
|
||||
* Neither the name of Google Inc. nor the names of its
|
||||
contributors may be used to endorse or promote products derived from
|
||||
this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
448
vendor/google.golang.org/api/googleapi/googleapi.go
generated
vendored
448
vendor/google.golang.org/api/googleapi/googleapi.go
generated
vendored
@@ -1,448 +0,0 @@
|
||||
// Copyright 2011 Google LLC. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package googleapi contains the common code shared by all Google API
|
||||
// libraries.
|
||||
package googleapi // import "google.golang.org/api/googleapi"
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"google.golang.org/api/internal/third_party/uritemplates"
|
||||
)
|
||||
|
||||
// ContentTyper is an interface for Readers which know (or would like
|
||||
// to override) their Content-Type. If a media body doesn't implement
|
||||
// ContentTyper, the type is sniffed from the content using
|
||||
// http.DetectContentType.
|
||||
type ContentTyper interface {
|
||||
ContentType() string
|
||||
}
|
||||
|
||||
// A SizeReaderAt is a ReaderAt with a Size method.
|
||||
// An io.SectionReader implements SizeReaderAt.
|
||||
type SizeReaderAt interface {
|
||||
io.ReaderAt
|
||||
Size() int64
|
||||
}
|
||||
|
||||
// ServerResponse is embedded in each Do response and
|
||||
// provides the HTTP status code and header sent by the server.
|
||||
type ServerResponse struct {
|
||||
// HTTPStatusCode is the server's response status code. When using a
|
||||
// resource method's Do call, this will always be in the 2xx range.
|
||||
HTTPStatusCode int
|
||||
// Header contains the response header fields from the server.
|
||||
Header http.Header
|
||||
}
|
||||
|
||||
const (
|
||||
// Version defines the gax version being used. This is typically sent
|
||||
// in an HTTP header to services.
|
||||
Version = "0.5"
|
||||
|
||||
// UserAgent is the header string used to identify this package.
|
||||
UserAgent = "google-api-go-client/" + Version
|
||||
|
||||
// DefaultUploadChunkSize is the default chunk size to use for resumable
|
||||
// uploads if not specified by the user.
|
||||
DefaultUploadChunkSize = 16 * 1024 * 1024
|
||||
|
||||
// MinUploadChunkSize is the minimum chunk size that can be used for
|
||||
// resumable uploads. All user-specified chunk sizes must be multiple of
|
||||
// this value.
|
||||
MinUploadChunkSize = 256 * 1024
|
||||
)
|
||||
|
||||
// Error contains an error response from the server.
|
||||
type Error struct {
|
||||
// Code is the HTTP response status code and will always be populated.
|
||||
Code int `json:"code"`
|
||||
// Message is the server response message and is only populated when
|
||||
// explicitly referenced by the JSON server response.
|
||||
Message string `json:"message"`
|
||||
// Details provide more context to an error.
|
||||
Details []interface{} `json:"details"`
|
||||
// Body is the raw response returned by the server.
|
||||
// It is often but not always JSON, depending on how the request fails.
|
||||
Body string
|
||||
// Header contains the response header fields from the server.
|
||||
Header http.Header
|
||||
|
||||
Errors []ErrorItem
|
||||
}
|
||||
|
||||
// ErrorItem is a detailed error code & message from the Google API frontend.
|
||||
type ErrorItem struct {
|
||||
// Reason is the typed error code. For example: "some_example".
|
||||
Reason string `json:"reason"`
|
||||
// Message is the human-readable description of the error.
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
func (e *Error) Error() string {
|
||||
if len(e.Errors) == 0 && e.Message == "" {
|
||||
return fmt.Sprintf("googleapi: got HTTP response code %d with body: %v", e.Code, e.Body)
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
fmt.Fprintf(&buf, "googleapi: Error %d: ", e.Code)
|
||||
if e.Message != "" {
|
||||
fmt.Fprintf(&buf, "%s", e.Message)
|
||||
}
|
||||
if len(e.Details) > 0 {
|
||||
var detailBuf bytes.Buffer
|
||||
enc := json.NewEncoder(&detailBuf)
|
||||
enc.SetIndent("", " ")
|
||||
if err := enc.Encode(e.Details); err == nil {
|
||||
fmt.Fprint(&buf, "\nDetails:")
|
||||
fmt.Fprintf(&buf, "\n%s", detailBuf.String())
|
||||
|
||||
}
|
||||
}
|
||||
if len(e.Errors) == 0 {
|
||||
return strings.TrimSpace(buf.String())
|
||||
}
|
||||
if len(e.Errors) == 1 && e.Errors[0].Message == e.Message {
|
||||
fmt.Fprintf(&buf, ", %s", e.Errors[0].Reason)
|
||||
return buf.String()
|
||||
}
|
||||
fmt.Fprintln(&buf, "\nMore details:")
|
||||
for _, v := range e.Errors {
|
||||
fmt.Fprintf(&buf, "Reason: %s, Message: %s\n", v.Reason, v.Message)
|
||||
}
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
type errorReply struct {
|
||||
Error *Error `json:"error"`
|
||||
}
|
||||
|
||||
// CheckResponse returns an error (of type *Error) if the response
|
||||
// status code is not 2xx.
|
||||
func CheckResponse(res *http.Response) error {
|
||||
if res.StatusCode >= 200 && res.StatusCode <= 299 {
|
||||
return nil
|
||||
}
|
||||
slurp, err := ioutil.ReadAll(res.Body)
|
||||
if err == nil {
|
||||
jerr := new(errorReply)
|
||||
err = json.Unmarshal(slurp, jerr)
|
||||
if err == nil && jerr.Error != nil {
|
||||
if jerr.Error.Code == 0 {
|
||||
jerr.Error.Code = res.StatusCode
|
||||
}
|
||||
jerr.Error.Body = string(slurp)
|
||||
return jerr.Error
|
||||
}
|
||||
}
|
||||
return &Error{
|
||||
Code: res.StatusCode,
|
||||
Body: string(slurp),
|
||||
Header: res.Header,
|
||||
}
|
||||
}
|
||||
|
||||
// IsNotModified reports whether err is the result of the
|
||||
// server replying with http.StatusNotModified.
|
||||
// Such error values are sometimes returned by "Do" methods
|
||||
// on calls when If-None-Match is used.
|
||||
func IsNotModified(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
ae, ok := err.(*Error)
|
||||
return ok && ae.Code == http.StatusNotModified
|
||||
}
|
||||
|
||||
// CheckMediaResponse returns an error (of type *Error) if the response
|
||||
// status code is not 2xx. Unlike CheckResponse it does not assume the
|
||||
// body is a JSON error document.
|
||||
// It is the caller's responsibility to close res.Body.
|
||||
func CheckMediaResponse(res *http.Response) error {
|
||||
if res.StatusCode >= 200 && res.StatusCode <= 299 {
|
||||
return nil
|
||||
}
|
||||
slurp, _ := ioutil.ReadAll(io.LimitReader(res.Body, 1<<20))
|
||||
return &Error{
|
||||
Code: res.StatusCode,
|
||||
Body: string(slurp),
|
||||
}
|
||||
}
|
||||
|
||||
// MarshalStyle defines whether to marshal JSON with a {"data": ...} wrapper.
|
||||
type MarshalStyle bool
|
||||
|
||||
// WithDataWrapper marshals JSON with a {"data": ...} wrapper.
|
||||
var WithDataWrapper = MarshalStyle(true)
|
||||
|
||||
// WithoutDataWrapper marshals JSON without a {"data": ...} wrapper.
|
||||
var WithoutDataWrapper = MarshalStyle(false)
|
||||
|
||||
func (wrap MarshalStyle) JSONReader(v interface{}) (io.Reader, error) {
|
||||
buf := new(bytes.Buffer)
|
||||
if wrap {
|
||||
buf.Write([]byte(`{"data": `))
|
||||
}
|
||||
err := json.NewEncoder(buf).Encode(v)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if wrap {
|
||||
buf.Write([]byte(`}`))
|
||||
}
|
||||
return buf, nil
|
||||
}
|
||||
|
||||
// ProgressUpdater is a function that is called upon every progress update of a resumable upload.
|
||||
// This is the only part of a resumable upload (from googleapi) that is usable by the developer.
|
||||
// The remaining usable pieces of resumable uploads is exposed in each auto-generated API.
|
||||
type ProgressUpdater func(current, total int64)
|
||||
|
||||
// MediaOption defines the interface for setting media options.
|
||||
type MediaOption interface {
|
||||
setOptions(o *MediaOptions)
|
||||
}
|
||||
|
||||
type contentTypeOption string
|
||||
|
||||
func (ct contentTypeOption) setOptions(o *MediaOptions) {
|
||||
o.ContentType = string(ct)
|
||||
if o.ContentType == "" {
|
||||
o.ForceEmptyContentType = true
|
||||
}
|
||||
}
|
||||
|
||||
// ContentType returns a MediaOption which sets the Content-Type header for media uploads.
|
||||
// If ctype is empty, the Content-Type header will be omitted.
|
||||
func ContentType(ctype string) MediaOption {
|
||||
return contentTypeOption(ctype)
|
||||
}
|
||||
|
||||
type chunkSizeOption int
|
||||
|
||||
func (cs chunkSizeOption) setOptions(o *MediaOptions) {
|
||||
size := int(cs)
|
||||
if size%MinUploadChunkSize != 0 {
|
||||
size += MinUploadChunkSize - (size % MinUploadChunkSize)
|
||||
}
|
||||
o.ChunkSize = size
|
||||
}
|
||||
|
||||
// ChunkSize returns a MediaOption which sets the chunk size for media uploads.
|
||||
// size will be rounded up to the nearest multiple of 256K.
|
||||
// Media which contains fewer than size bytes will be uploaded in a single request.
|
||||
// Media which contains size bytes or more will be uploaded in separate chunks.
|
||||
// If size is zero, media will be uploaded in a single request.
|
||||
func ChunkSize(size int) MediaOption {
|
||||
return chunkSizeOption(size)
|
||||
}
|
||||
|
||||
// MediaOptions stores options for customizing media upload. It is not used by developers directly.
|
||||
type MediaOptions struct {
|
||||
ContentType string
|
||||
ForceEmptyContentType bool
|
||||
|
||||
ChunkSize int
|
||||
}
|
||||
|
||||
// ProcessMediaOptions stores options from opts in a MediaOptions.
|
||||
// It is not used by developers directly.
|
||||
func ProcessMediaOptions(opts []MediaOption) *MediaOptions {
|
||||
mo := &MediaOptions{ChunkSize: DefaultUploadChunkSize}
|
||||
for _, o := range opts {
|
||||
o.setOptions(mo)
|
||||
}
|
||||
return mo
|
||||
}
|
||||
|
||||
// ResolveRelative resolves relatives such as "http://www.golang.org/" and
|
||||
// "topics/myproject/mytopic" into a single string, such as
|
||||
// "http://www.golang.org/topics/myproject/mytopic". It strips all parent
|
||||
// references (e.g. ../..) as well as anything after the host
|
||||
// (e.g. /bar/gaz gets stripped out of foo.com/bar/gaz).
|
||||
//
|
||||
// ResolveRelative panics if either basestr or relstr is not able to be parsed.
|
||||
func ResolveRelative(basestr, relstr string) string {
|
||||
u, err := url.Parse(basestr)
|
||||
if err != nil {
|
||||
panic(fmt.Sprintf("failed to parse %q", basestr))
|
||||
}
|
||||
afterColonPath := ""
|
||||
if i := strings.IndexRune(relstr, ':'); i > 0 {
|
||||
afterColonPath = relstr[i+1:]
|
||||
relstr = relstr[:i]
|
||||
}
|
||||
rel, err := url.Parse(relstr)
|
||||
if err != nil {
|
||||
panic(fmt.Sprintf("failed to parse %q", relstr))
|
||||
}
|
||||
u = u.ResolveReference(rel)
|
||||
us := u.String()
|
||||
if afterColonPath != "" {
|
||||
us = fmt.Sprintf("%s:%s", us, afterColonPath)
|
||||
}
|
||||
us = strings.Replace(us, "%7B", "{", -1)
|
||||
us = strings.Replace(us, "%7D", "}", -1)
|
||||
us = strings.Replace(us, "%2A", "*", -1)
|
||||
return us
|
||||
}
|
||||
|
||||
// Expand subsitutes any {encoded} strings in the URL passed in using
|
||||
// the map supplied.
|
||||
//
|
||||
// This calls SetOpaque to avoid encoding of the parameters in the URL path.
|
||||
func Expand(u *url.URL, expansions map[string]string) {
|
||||
escaped, unescaped, err := uritemplates.Expand(u.Path, expansions)
|
||||
if err == nil {
|
||||
u.Path = unescaped
|
||||
u.RawPath = escaped
|
||||
}
|
||||
}
|
||||
|
||||
// CloseBody is used to close res.Body.
|
||||
// Prior to calling Close, it also tries to Read a small amount to see an EOF.
|
||||
// Not seeing an EOF can prevent HTTP Transports from reusing connections.
|
||||
func CloseBody(res *http.Response) {
|
||||
if res == nil || res.Body == nil {
|
||||
return
|
||||
}
|
||||
// Justification for 3 byte reads: two for up to "\r\n" after
|
||||
// a JSON/XML document, and then 1 to see EOF if we haven't yet.
|
||||
// TODO(bradfitz): detect Go 1.3+ and skip these reads.
|
||||
// See https://codereview.appspot.com/58240043
|
||||
// and https://codereview.appspot.com/49570044
|
||||
buf := make([]byte, 1)
|
||||
for i := 0; i < 3; i++ {
|
||||
_, err := res.Body.Read(buf)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
res.Body.Close()
|
||||
|
||||
}
|
||||
|
||||
// VariantType returns the type name of the given variant.
|
||||
// If the map doesn't contain the named key or the value is not a []interface{}, "" is returned.
|
||||
// This is used to support "variant" APIs that can return one of a number of different types.
|
||||
func VariantType(t map[string]interface{}) string {
|
||||
s, _ := t["type"].(string)
|
||||
return s
|
||||
}
|
||||
|
||||
// ConvertVariant uses the JSON encoder/decoder to fill in the struct 'dst' with the fields found in variant 'v'.
|
||||
// This is used to support "variant" APIs that can return one of a number of different types.
|
||||
// It reports whether the conversion was successful.
|
||||
func ConvertVariant(v map[string]interface{}, dst interface{}) bool {
|
||||
var buf bytes.Buffer
|
||||
err := json.NewEncoder(&buf).Encode(v)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return json.Unmarshal(buf.Bytes(), dst) == nil
|
||||
}
|
||||
|
||||
// A Field names a field to be retrieved with a partial response.
|
||||
// https://cloud.google.com/storage/docs/json_api/v1/how-tos/performance
|
||||
//
|
||||
// Partial responses can dramatically reduce the amount of data that must be sent to your application.
|
||||
// In order to request partial responses, you can specify the full list of fields
|
||||
// that your application needs by adding the Fields option to your request.
|
||||
//
|
||||
// Field strings use camelCase with leading lower-case characters to identify fields within the response.
|
||||
//
|
||||
// For example, if your response has a "NextPageToken" and a slice of "Items" with "Id" fields,
|
||||
// you could request just those fields like this:
|
||||
//
|
||||
// svc.Events.List().Fields("nextPageToken", "items/id").Do()
|
||||
//
|
||||
// or if you were also interested in each Item's "Updated" field, you can combine them like this:
|
||||
//
|
||||
// svc.Events.List().Fields("nextPageToken", "items(id,updated)").Do()
|
||||
//
|
||||
// Another way to find field names is through the Google API explorer:
|
||||
// https://developers.google.com/apis-explorer/#p/
|
||||
type Field string
|
||||
|
||||
// CombineFields combines fields into a single string.
|
||||
func CombineFields(s []Field) string {
|
||||
r := make([]string, len(s))
|
||||
for i, v := range s {
|
||||
r[i] = string(v)
|
||||
}
|
||||
return strings.Join(r, ",")
|
||||
}
|
||||
|
||||
// A CallOption is an optional argument to an API call.
|
||||
// It should be treated as an opaque value by users of Google APIs.
|
||||
//
|
||||
// A CallOption is something that configures an API call in a way that is
|
||||
// not specific to that API; for instance, controlling the quota user for
|
||||
// an API call is common across many APIs, and is thus a CallOption.
|
||||
type CallOption interface {
|
||||
Get() (key, value string)
|
||||
}
|
||||
|
||||
// A MultiCallOption is an option argument to an API call and can be passed
|
||||
// anywhere a CallOption is accepted. It additionally supports returning a slice
|
||||
// of values for a given key.
|
||||
type MultiCallOption interface {
|
||||
CallOption
|
||||
GetMulti() (key string, value []string)
|
||||
}
|
||||
|
||||
// QuotaUser returns a CallOption that will set the quota user for a call.
|
||||
// The quota user can be used by server-side applications to control accounting.
|
||||
// It can be an arbitrary string up to 40 characters, and will override UserIP
|
||||
// if both are provided.
|
||||
func QuotaUser(u string) CallOption { return quotaUser(u) }
|
||||
|
||||
type quotaUser string
|
||||
|
||||
func (q quotaUser) Get() (string, string) { return "quotaUser", string(q) }
|
||||
|
||||
// UserIP returns a CallOption that will set the "userIp" parameter of a call.
|
||||
// This should be the IP address of the originating request.
|
||||
func UserIP(ip string) CallOption { return userIP(ip) }
|
||||
|
||||
type userIP string
|
||||
|
||||
func (i userIP) Get() (string, string) { return "userIp", string(i) }
|
||||
|
||||
// Trace returns a CallOption that enables diagnostic tracing for a call.
|
||||
// traceToken is an ID supplied by Google support.
|
||||
func Trace(traceToken string) CallOption { return traceTok(traceToken) }
|
||||
|
||||
type traceTok string
|
||||
|
||||
func (t traceTok) Get() (string, string) { return "trace", "token:" + string(t) }
|
||||
|
||||
type queryParameter struct {
|
||||
key string
|
||||
values []string
|
||||
}
|
||||
|
||||
// QueryParameter allows setting the value(s) of an arbitrary key.
|
||||
func QueryParameter(key string, values ...string) CallOption {
|
||||
return queryParameter{key: key, values: append([]string{}, values...)}
|
||||
}
|
||||
|
||||
// Get will never actually be called -- GetMulti will.
|
||||
func (q queryParameter) Get() (string, string) {
|
||||
return "", ""
|
||||
}
|
||||
|
||||
// GetMulti returns the key and values values associated to that key.
|
||||
func (q queryParameter) GetMulti() (string, []string) {
|
||||
return q.key, q.values
|
||||
}
|
||||
|
||||
// TODO: Fields too
|
||||
44
vendor/google.golang.org/api/googleapi/transport/apikey.go
generated
vendored
44
vendor/google.golang.org/api/googleapi/transport/apikey.go
generated
vendored
@@ -1,44 +0,0 @@
|
||||
// Copyright 2012 Google LLC. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package transport contains HTTP transports used to make
|
||||
// authenticated API requests.
|
||||
//
|
||||
// This package is DEPRECATED. Users should instead use,
|
||||
//
|
||||
// service, err := NewService(..., option.WithAPIKey(...))
|
||||
package transport
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// APIKey is an HTTP Transport which wraps an underlying transport and
|
||||
// appends an API Key "key" parameter to the URL of outgoing requests.
|
||||
//
|
||||
// Deprecated: please use NewService(..., option.WithAPIKey(...)) instead.
|
||||
type APIKey struct {
|
||||
// Key is the API Key to set on requests.
|
||||
Key string
|
||||
|
||||
// Transport is the underlying HTTP transport.
|
||||
// If nil, http.DefaultTransport is used.
|
||||
Transport http.RoundTripper
|
||||
}
|
||||
|
||||
func (t *APIKey) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||
rt := t.Transport
|
||||
if rt == nil {
|
||||
rt = http.DefaultTransport
|
||||
if rt == nil {
|
||||
return nil, errors.New("googleapi/transport: no Transport specified or available")
|
||||
}
|
||||
}
|
||||
newReq := *req
|
||||
args := newReq.URL.Query()
|
||||
args.Set("key", t.Key)
|
||||
newReq.URL.RawQuery = args.Encode()
|
||||
return rt.RoundTrip(&newReq)
|
||||
}
|
||||
202
vendor/google.golang.org/api/googleapi/types.go
generated
vendored
202
vendor/google.golang.org/api/googleapi/types.go
generated
vendored
@@ -1,202 +0,0 @@
|
||||
// Copyright 2013 Google LLC. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package googleapi
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// Int64s is a slice of int64s that marshal as quoted strings in JSON.
|
||||
type Int64s []int64
|
||||
|
||||
func (q *Int64s) UnmarshalJSON(raw []byte) error {
|
||||
*q = (*q)[:0]
|
||||
var ss []string
|
||||
if err := json.Unmarshal(raw, &ss); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, s := range ss {
|
||||
v, err := strconv.ParseInt(s, 10, 64)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*q = append(*q, int64(v))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Int32s is a slice of int32s that marshal as quoted strings in JSON.
|
||||
type Int32s []int32
|
||||
|
||||
func (q *Int32s) UnmarshalJSON(raw []byte) error {
|
||||
*q = (*q)[:0]
|
||||
var ss []string
|
||||
if err := json.Unmarshal(raw, &ss); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, s := range ss {
|
||||
v, err := strconv.ParseInt(s, 10, 32)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*q = append(*q, int32(v))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Uint64s is a slice of uint64s that marshal as quoted strings in JSON.
|
||||
type Uint64s []uint64
|
||||
|
||||
func (q *Uint64s) UnmarshalJSON(raw []byte) error {
|
||||
*q = (*q)[:0]
|
||||
var ss []string
|
||||
if err := json.Unmarshal(raw, &ss); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, s := range ss {
|
||||
v, err := strconv.ParseUint(s, 10, 64)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*q = append(*q, uint64(v))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Uint32s is a slice of uint32s that marshal as quoted strings in JSON.
|
||||
type Uint32s []uint32
|
||||
|
||||
func (q *Uint32s) UnmarshalJSON(raw []byte) error {
|
||||
*q = (*q)[:0]
|
||||
var ss []string
|
||||
if err := json.Unmarshal(raw, &ss); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, s := range ss {
|
||||
v, err := strconv.ParseUint(s, 10, 32)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*q = append(*q, uint32(v))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Float64s is a slice of float64s that marshal as quoted strings in JSON.
|
||||
type Float64s []float64
|
||||
|
||||
func (q *Float64s) UnmarshalJSON(raw []byte) error {
|
||||
*q = (*q)[:0]
|
||||
var ss []string
|
||||
if err := json.Unmarshal(raw, &ss); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, s := range ss {
|
||||
v, err := strconv.ParseFloat(s, 64)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*q = append(*q, float64(v))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func quotedList(n int, fn func(dst []byte, i int) []byte) ([]byte, error) {
|
||||
dst := make([]byte, 0, 2+n*10) // somewhat arbitrary
|
||||
dst = append(dst, '[')
|
||||
for i := 0; i < n; i++ {
|
||||
if i > 0 {
|
||||
dst = append(dst, ',')
|
||||
}
|
||||
dst = append(dst, '"')
|
||||
dst = fn(dst, i)
|
||||
dst = append(dst, '"')
|
||||
}
|
||||
dst = append(dst, ']')
|
||||
return dst, nil
|
||||
}
|
||||
|
||||
func (q Int64s) MarshalJSON() ([]byte, error) {
|
||||
return quotedList(len(q), func(dst []byte, i int) []byte {
|
||||
return strconv.AppendInt(dst, q[i], 10)
|
||||
})
|
||||
}
|
||||
|
||||
func (q Int32s) MarshalJSON() ([]byte, error) {
|
||||
return quotedList(len(q), func(dst []byte, i int) []byte {
|
||||
return strconv.AppendInt(dst, int64(q[i]), 10)
|
||||
})
|
||||
}
|
||||
|
||||
func (q Uint64s) MarshalJSON() ([]byte, error) {
|
||||
return quotedList(len(q), func(dst []byte, i int) []byte {
|
||||
return strconv.AppendUint(dst, q[i], 10)
|
||||
})
|
||||
}
|
||||
|
||||
func (q Uint32s) MarshalJSON() ([]byte, error) {
|
||||
return quotedList(len(q), func(dst []byte, i int) []byte {
|
||||
return strconv.AppendUint(dst, uint64(q[i]), 10)
|
||||
})
|
||||
}
|
||||
|
||||
func (q Float64s) MarshalJSON() ([]byte, error) {
|
||||
return quotedList(len(q), func(dst []byte, i int) []byte {
|
||||
return strconv.AppendFloat(dst, q[i], 'g', -1, 64)
|
||||
})
|
||||
}
|
||||
|
||||
// RawMessage is a raw encoded JSON value.
|
||||
// It is identical to json.RawMessage, except it does not suffer from
|
||||
// https://golang.org/issue/14493.
|
||||
type RawMessage []byte
|
||||
|
||||
// MarshalJSON returns m.
|
||||
func (m RawMessage) MarshalJSON() ([]byte, error) {
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// UnmarshalJSON sets *m to a copy of data.
|
||||
func (m *RawMessage) UnmarshalJSON(data []byte) error {
|
||||
if m == nil {
|
||||
return errors.New("googleapi.RawMessage: UnmarshalJSON on nil pointer")
|
||||
}
|
||||
*m = append((*m)[:0], data...)
|
||||
return nil
|
||||
}
|
||||
|
||||
/*
|
||||
* Helper routines for simplifying the creation of optional fields of basic type.
|
||||
*/
|
||||
|
||||
// Bool is a helper routine that allocates a new bool value
|
||||
// to store v and returns a pointer to it.
|
||||
func Bool(v bool) *bool { return &v }
|
||||
|
||||
// Int32 is a helper routine that allocates a new int32 value
|
||||
// to store v and returns a pointer to it.
|
||||
func Int32(v int32) *int32 { return &v }
|
||||
|
||||
// Int64 is a helper routine that allocates a new int64 value
|
||||
// to store v and returns a pointer to it.
|
||||
func Int64(v int64) *int64 { return &v }
|
||||
|
||||
// Float64 is a helper routine that allocates a new float64 value
|
||||
// to store v and returns a pointer to it.
|
||||
func Float64(v float64) *float64 { return &v }
|
||||
|
||||
// Uint32 is a helper routine that allocates a new uint32 value
|
||||
// to store v and returns a pointer to it.
|
||||
func Uint32(v uint32) *uint32 { return &v }
|
||||
|
||||
// Uint64 is a helper routine that allocates a new uint64 value
|
||||
// to store v and returns a pointer to it.
|
||||
func Uint64(v uint64) *uint64 { return &v }
|
||||
|
||||
// String is a helper routine that allocates a new string value
|
||||
// to store v and returns a pointer to it.
|
||||
func String(v string) *string { return &v }
|
||||
30
vendor/google.golang.org/api/internal/conn_pool.go
generated
vendored
30
vendor/google.golang.org/api/internal/conn_pool.go
generated
vendored
@@ -1,30 +0,0 @@
|
||||
// Copyright 2020 Google LLC.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package internal
|
||||
|
||||
import (
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
// ConnPool is a pool of grpc.ClientConns.
|
||||
type ConnPool interface {
|
||||
// Conn returns a ClientConn from the pool.
|
||||
//
|
||||
// Conns aren't returned to the pool.
|
||||
Conn() *grpc.ClientConn
|
||||
|
||||
// Num returns the number of connections in the pool.
|
||||
//
|
||||
// It will always return the same value.
|
||||
Num() int
|
||||
|
||||
// Close closes every ClientConn in the pool.
|
||||
//
|
||||
// The error returned by Close may be a single error or multiple errors.
|
||||
Close() error
|
||||
|
||||
// ConnPool implements grpc.ClientConnInterface to enable it to be used directly with generated proto stubs.
|
||||
grpc.ClientConnInterface
|
||||
}
|
||||
158
vendor/google.golang.org/api/internal/creds.go
generated
vendored
158
vendor/google.golang.org/api/internal/creds.go
generated
vendored
@@ -1,158 +0,0 @@
|
||||
// Copyright 2017 Google LLC.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package internal
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
|
||||
"golang.org/x/oauth2"
|
||||
"google.golang.org/api/internal/impersonate"
|
||||
|
||||
"golang.org/x/oauth2/google"
|
||||
)
|
||||
|
||||
// Creds returns credential information obtained from DialSettings, or if none, then
|
||||
// it returns default credential information.
|
||||
func Creds(ctx context.Context, ds *DialSettings) (*google.Credentials, error) {
|
||||
creds, err := baseCreds(ctx, ds)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if ds.ImpersonationConfig != nil {
|
||||
return impersonateCredentials(ctx, creds, ds)
|
||||
}
|
||||
return creds, nil
|
||||
}
|
||||
|
||||
func baseCreds(ctx context.Context, ds *DialSettings) (*google.Credentials, error) {
|
||||
if ds.InternalCredentials != nil {
|
||||
return ds.InternalCredentials, nil
|
||||
}
|
||||
if ds.Credentials != nil {
|
||||
return ds.Credentials, nil
|
||||
}
|
||||
if ds.CredentialsJSON != nil {
|
||||
return credentialsFromJSON(ctx, ds.CredentialsJSON, ds)
|
||||
}
|
||||
if ds.CredentialsFile != "" {
|
||||
data, err := ioutil.ReadFile(ds.CredentialsFile)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot read credentials file: %v", err)
|
||||
}
|
||||
return credentialsFromJSON(ctx, data, ds)
|
||||
}
|
||||
if ds.TokenSource != nil {
|
||||
return &google.Credentials{TokenSource: ds.TokenSource}, nil
|
||||
}
|
||||
cred, err := google.FindDefaultCredentials(ctx, ds.GetScopes()...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(cred.JSON) > 0 {
|
||||
return credentialsFromJSON(ctx, cred.JSON, ds)
|
||||
}
|
||||
// For GAE and GCE, the JSON is empty so return the default credentials directly.
|
||||
return cred, nil
|
||||
}
|
||||
|
||||
// JSON key file type.
|
||||
const (
|
||||
serviceAccountKey = "service_account"
|
||||
)
|
||||
|
||||
// credentialsFromJSON returns a google.Credentials from the JSON data
|
||||
//
|
||||
// - A self-signed JWT flow will be executed if the following conditions are
|
||||
// met:
|
||||
// (1) At least one of the following is true:
|
||||
// (a) No scope is provided
|
||||
// (b) Scope for self-signed JWT flow is enabled
|
||||
// (c) Audiences are explicitly provided by users
|
||||
// (2) No service account impersontation
|
||||
//
|
||||
// - Otherwise, executes standard OAuth 2.0 flow
|
||||
// More details: google.aip.dev/auth/4111
|
||||
func credentialsFromJSON(ctx context.Context, data []byte, ds *DialSettings) (*google.Credentials, error) {
|
||||
// By default, a standard OAuth 2.0 token source is created
|
||||
cred, err := google.CredentialsFromJSON(ctx, data, ds.GetScopes()...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Override the token source to use self-signed JWT if conditions are met
|
||||
isJWTFlow, err := isSelfSignedJWTFlow(data, ds)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if isJWTFlow {
|
||||
ts, err := selfSignedJWTTokenSource(data, ds)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cred.TokenSource = ts
|
||||
}
|
||||
|
||||
return cred, err
|
||||
}
|
||||
|
||||
func isSelfSignedJWTFlow(data []byte, ds *DialSettings) (bool, error) {
|
||||
if (ds.EnableJwtWithScope || ds.HasCustomAudience()) &&
|
||||
ds.ImpersonationConfig == nil {
|
||||
// Check if JSON is a service account and if so create a self-signed JWT.
|
||||
var f struct {
|
||||
Type string `json:"type"`
|
||||
// The rest JSON fields are omitted because they are not used.
|
||||
}
|
||||
if err := json.Unmarshal(data, &f); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return f.Type == serviceAccountKey, nil
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
func selfSignedJWTTokenSource(data []byte, ds *DialSettings) (oauth2.TokenSource, error) {
|
||||
if len(ds.GetScopes()) > 0 && !ds.HasCustomAudience() {
|
||||
// Scopes are preferred in self-signed JWT unless the scope is not available
|
||||
// or a custom audience is used.
|
||||
return google.JWTAccessTokenSourceWithScope(data, ds.GetScopes()...)
|
||||
} else if ds.GetAudience() != "" {
|
||||
// Fallback to audience if scope is not provided
|
||||
return google.JWTAccessTokenSourceFromJSON(data, ds.GetAudience())
|
||||
} else {
|
||||
return nil, errors.New("neither scopes or audience are available for the self-signed JWT")
|
||||
}
|
||||
}
|
||||
|
||||
// QuotaProjectFromCreds returns the quota project from the JSON blob in the provided credentials.
|
||||
//
|
||||
// NOTE(cbro): consider promoting this to a field on google.Credentials.
|
||||
func QuotaProjectFromCreds(cred *google.Credentials) string {
|
||||
var v struct {
|
||||
QuotaProject string `json:"quota_project_id"`
|
||||
}
|
||||
if err := json.Unmarshal(cred.JSON, &v); err != nil {
|
||||
return ""
|
||||
}
|
||||
return v.QuotaProject
|
||||
}
|
||||
|
||||
func impersonateCredentials(ctx context.Context, creds *google.Credentials, ds *DialSettings) (*google.Credentials, error) {
|
||||
if len(ds.ImpersonationConfig.Scopes) == 0 {
|
||||
ds.ImpersonationConfig.Scopes = ds.GetScopes()
|
||||
}
|
||||
ts, err := impersonate.TokenSource(ctx, creds.TokenSource, ds.ImpersonationConfig)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &google.Credentials{
|
||||
TokenSource: ts,
|
||||
ProjectID: creds.ProjectID,
|
||||
}, nil
|
||||
}
|
||||
79
vendor/google.golang.org/api/internal/gensupport/buffer.go
generated
vendored
79
vendor/google.golang.org/api/internal/gensupport/buffer.go
generated
vendored
@@ -1,79 +0,0 @@
|
||||
// Copyright 2016 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 gensupport
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
|
||||
"google.golang.org/api/googleapi"
|
||||
)
|
||||
|
||||
// MediaBuffer buffers data from an io.Reader to support uploading media in
|
||||
// retryable chunks. It should be created with NewMediaBuffer.
|
||||
type MediaBuffer struct {
|
||||
media io.Reader
|
||||
|
||||
chunk []byte // The current chunk which is pending upload. The capacity is the chunk size.
|
||||
err error // Any error generated when populating chunk by reading media.
|
||||
|
||||
// The absolute position of chunk in the underlying media.
|
||||
off int64
|
||||
}
|
||||
|
||||
// NewMediaBuffer initializes a MediaBuffer.
|
||||
func NewMediaBuffer(media io.Reader, chunkSize int) *MediaBuffer {
|
||||
return &MediaBuffer{media: media, chunk: make([]byte, 0, chunkSize)}
|
||||
}
|
||||
|
||||
// Chunk returns the current buffered chunk, the offset in the underlying media
|
||||
// from which the chunk is drawn, and the size of the chunk.
|
||||
// Successive calls to Chunk return the same chunk between calls to Next.
|
||||
func (mb *MediaBuffer) Chunk() (chunk io.Reader, off int64, size int, err error) {
|
||||
// There may already be data in chunk if Next has not been called since the previous call to Chunk.
|
||||
if mb.err == nil && len(mb.chunk) == 0 {
|
||||
mb.err = mb.loadChunk()
|
||||
}
|
||||
return bytes.NewReader(mb.chunk), mb.off, len(mb.chunk), mb.err
|
||||
}
|
||||
|
||||
// loadChunk will read from media into chunk, up to the capacity of chunk.
|
||||
func (mb *MediaBuffer) loadChunk() error {
|
||||
bufSize := cap(mb.chunk)
|
||||
mb.chunk = mb.chunk[:bufSize]
|
||||
|
||||
read := 0
|
||||
var err error
|
||||
for err == nil && read < bufSize {
|
||||
var n int
|
||||
n, err = mb.media.Read(mb.chunk[read:])
|
||||
read += n
|
||||
}
|
||||
mb.chunk = mb.chunk[:read]
|
||||
return err
|
||||
}
|
||||
|
||||
// Next advances to the next chunk, which will be returned by the next call to Chunk.
|
||||
// Calls to Next without a corresponding prior call to Chunk will have no effect.
|
||||
func (mb *MediaBuffer) Next() {
|
||||
mb.off += int64(len(mb.chunk))
|
||||
mb.chunk = mb.chunk[0:0]
|
||||
}
|
||||
|
||||
type readerTyper struct {
|
||||
io.Reader
|
||||
googleapi.ContentTyper
|
||||
}
|
||||
|
||||
// ReaderAtToReader adapts a ReaderAt to be used as a Reader.
|
||||
// If ra implements googleapi.ContentTyper, then the returned reader
|
||||
// will also implement googleapi.ContentTyper, delegating to ra.
|
||||
func ReaderAtToReader(ra io.ReaderAt, size int64) io.Reader {
|
||||
r := io.NewSectionReader(ra, 0, size)
|
||||
if typer, ok := ra.(googleapi.ContentTyper); ok {
|
||||
return readerTyper{r, typer}
|
||||
}
|
||||
return r
|
||||
}
|
||||
10
vendor/google.golang.org/api/internal/gensupport/doc.go
generated
vendored
10
vendor/google.golang.org/api/internal/gensupport/doc.go
generated
vendored
@@ -1,10 +0,0 @@
|
||||
// Copyright 2016 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 gensupport is an internal implementation detail used by code
|
||||
// generated by the google-api-go-generator tool.
|
||||
//
|
||||
// This package may be modified at any time without regard for backwards
|
||||
// compatibility. It should not be used directly by API users.
|
||||
package gensupport
|
||||
211
vendor/google.golang.org/api/internal/gensupport/json.go
generated
vendored
211
vendor/google.golang.org/api/internal/gensupport/json.go
generated
vendored
@@ -1,211 +0,0 @@
|
||||
// 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 gensupport
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// MarshalJSON returns a JSON encoding of schema containing only selected fields.
|
||||
// A field is selected if any of the following is true:
|
||||
// * it has a non-empty value
|
||||
// * its field name is present in forceSendFields and it is not a nil pointer or nil interface
|
||||
// * its field name is present in nullFields.
|
||||
// The JSON key for each selected field is taken from the field's json: struct tag.
|
||||
func MarshalJSON(schema interface{}, forceSendFields, nullFields []string) ([]byte, error) {
|
||||
if len(forceSendFields) == 0 && len(nullFields) == 0 {
|
||||
return json.Marshal(schema)
|
||||
}
|
||||
|
||||
mustInclude := make(map[string]bool)
|
||||
for _, f := range forceSendFields {
|
||||
mustInclude[f] = true
|
||||
}
|
||||
useNull := make(map[string]bool)
|
||||
useNullMaps := make(map[string]map[string]bool)
|
||||
for _, nf := range nullFields {
|
||||
parts := strings.SplitN(nf, ".", 2)
|
||||
field := parts[0]
|
||||
if len(parts) == 1 {
|
||||
useNull[field] = true
|
||||
} else {
|
||||
if useNullMaps[field] == nil {
|
||||
useNullMaps[field] = map[string]bool{}
|
||||
}
|
||||
useNullMaps[field][parts[1]] = true
|
||||
}
|
||||
}
|
||||
|
||||
dataMap, err := schemaToMap(schema, mustInclude, useNull, useNullMaps)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return json.Marshal(dataMap)
|
||||
}
|
||||
|
||||
func schemaToMap(schema interface{}, mustInclude, useNull map[string]bool, useNullMaps map[string]map[string]bool) (map[string]interface{}, error) {
|
||||
m := make(map[string]interface{})
|
||||
s := reflect.ValueOf(schema)
|
||||
st := s.Type()
|
||||
|
||||
for i := 0; i < s.NumField(); i++ {
|
||||
jsonTag := st.Field(i).Tag.Get("json")
|
||||
if jsonTag == "" {
|
||||
continue
|
||||
}
|
||||
tag, err := parseJSONTag(jsonTag)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if tag.ignore {
|
||||
continue
|
||||
}
|
||||
|
||||
v := s.Field(i)
|
||||
f := st.Field(i)
|
||||
|
||||
if useNull[f.Name] {
|
||||
if !isEmptyValue(v) {
|
||||
return nil, fmt.Errorf("field %q in NullFields has non-empty value", f.Name)
|
||||
}
|
||||
m[tag.apiName] = nil
|
||||
continue
|
||||
}
|
||||
|
||||
if !includeField(v, f, mustInclude) {
|
||||
continue
|
||||
}
|
||||
|
||||
// If map fields are explicitly set to null, use a map[string]interface{}.
|
||||
if f.Type.Kind() == reflect.Map && useNullMaps[f.Name] != nil {
|
||||
ms, ok := v.Interface().(map[string]string)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("field %q has keys in NullFields but is not a map[string]string", f.Name)
|
||||
}
|
||||
mi := map[string]interface{}{}
|
||||
for k, v := range ms {
|
||||
mi[k] = v
|
||||
}
|
||||
for k := range useNullMaps[f.Name] {
|
||||
mi[k] = nil
|
||||
}
|
||||
m[tag.apiName] = mi
|
||||
continue
|
||||
}
|
||||
|
||||
// nil maps are treated as empty maps.
|
||||
if f.Type.Kind() == reflect.Map && v.IsNil() {
|
||||
m[tag.apiName] = map[string]string{}
|
||||
continue
|
||||
}
|
||||
|
||||
// nil slices are treated as empty slices.
|
||||
if f.Type.Kind() == reflect.Slice && v.IsNil() {
|
||||
m[tag.apiName] = []bool{}
|
||||
continue
|
||||
}
|
||||
|
||||
if tag.stringFormat {
|
||||
m[tag.apiName] = formatAsString(v, f.Type.Kind())
|
||||
} else {
|
||||
m[tag.apiName] = v.Interface()
|
||||
}
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// formatAsString returns a string representation of v, dereferencing it first if possible.
|
||||
func formatAsString(v reflect.Value, kind reflect.Kind) string {
|
||||
if kind == reflect.Ptr && !v.IsNil() {
|
||||
v = v.Elem()
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%v", v.Interface())
|
||||
}
|
||||
|
||||
// jsonTag represents a restricted version of the struct tag format used by encoding/json.
|
||||
// It is used to describe the JSON encoding of fields in a Schema struct.
|
||||
type jsonTag struct {
|
||||
apiName string
|
||||
stringFormat bool
|
||||
ignore bool
|
||||
}
|
||||
|
||||
// parseJSONTag parses a restricted version of the struct tag format used by encoding/json.
|
||||
// The format of the tag must match that generated by the Schema.writeSchemaStruct method
|
||||
// in the api generator.
|
||||
func parseJSONTag(val string) (jsonTag, error) {
|
||||
if val == "-" {
|
||||
return jsonTag{ignore: true}, nil
|
||||
}
|
||||
|
||||
var tag jsonTag
|
||||
|
||||
i := strings.Index(val, ",")
|
||||
if i == -1 || val[:i] == "" {
|
||||
return tag, fmt.Errorf("malformed json tag: %s", val)
|
||||
}
|
||||
|
||||
tag = jsonTag{
|
||||
apiName: val[:i],
|
||||
}
|
||||
|
||||
switch val[i+1:] {
|
||||
case "omitempty":
|
||||
case "omitempty,string":
|
||||
tag.stringFormat = true
|
||||
default:
|
||||
return tag, fmt.Errorf("malformed json tag: %s", val)
|
||||
}
|
||||
|
||||
return tag, nil
|
||||
}
|
||||
|
||||
// Reports whether the struct field "f" with value "v" should be included in JSON output.
|
||||
func includeField(v reflect.Value, f reflect.StructField, mustInclude map[string]bool) bool {
|
||||
// The regular JSON encoding of a nil pointer is "null", which means "delete this field".
|
||||
// Therefore, we could enable field deletion by honoring pointer fields' presence in the mustInclude set.
|
||||
// However, many fields are not pointers, so there would be no way to delete these fields.
|
||||
// Rather than partially supporting field deletion, we ignore mustInclude for nil pointer fields.
|
||||
// Deletion will be handled by a separate mechanism.
|
||||
if f.Type.Kind() == reflect.Ptr && v.IsNil() {
|
||||
return false
|
||||
}
|
||||
|
||||
// The "any" type is represented as an interface{}. If this interface
|
||||
// is nil, there is no reasonable representation to send. We ignore
|
||||
// these fields, for the same reasons as given above for pointers.
|
||||
if f.Type.Kind() == reflect.Interface && v.IsNil() {
|
||||
return false
|
||||
}
|
||||
|
||||
return mustInclude[f.Name] || !isEmptyValue(v)
|
||||
}
|
||||
|
||||
// isEmptyValue reports whether v is the empty value for its type. This
|
||||
// implementation is based on that of the encoding/json package, but its
|
||||
// correctness does not depend on it being identical. What's important is that
|
||||
// this function return false in situations where v should not be sent as part
|
||||
// of a PATCH operation.
|
||||
func isEmptyValue(v reflect.Value) bool {
|
||||
switch v.Kind() {
|
||||
case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
|
||||
return v.Len() == 0
|
||||
case reflect.Bool:
|
||||
return !v.Bool()
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||
return v.Int() == 0
|
||||
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
|
||||
return v.Uint() == 0
|
||||
case reflect.Float32, reflect.Float64:
|
||||
return v.Float() == 0
|
||||
case reflect.Interface, reflect.Ptr:
|
||||
return v.IsNil()
|
||||
}
|
||||
return false
|
||||
}
|
||||
47
vendor/google.golang.org/api/internal/gensupport/jsonfloat.go
generated
vendored
47
vendor/google.golang.org/api/internal/gensupport/jsonfloat.go
generated
vendored
@@ -1,47 +0,0 @@
|
||||
// Copyright 2016 Google LLC.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package gensupport
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
)
|
||||
|
||||
// JSONFloat64 is a float64 that supports proper unmarshaling of special float
|
||||
// values in JSON, according to
|
||||
// https://developers.google.com/protocol-buffers/docs/proto3#json. Although
|
||||
// that is a proto-to-JSON spec, it applies to all Google APIs.
|
||||
//
|
||||
// The jsonpb package
|
||||
// (https://github.com/golang/protobuf/blob/master/jsonpb/jsonpb.go) has
|
||||
// similar functionality, but only for direct translation from proto messages
|
||||
// to JSON.
|
||||
type JSONFloat64 float64
|
||||
|
||||
func (f *JSONFloat64) UnmarshalJSON(data []byte) error {
|
||||
var ff float64
|
||||
if err := json.Unmarshal(data, &ff); err == nil {
|
||||
*f = JSONFloat64(ff)
|
||||
return nil
|
||||
}
|
||||
var s string
|
||||
if err := json.Unmarshal(data, &s); err == nil {
|
||||
switch s {
|
||||
case "NaN":
|
||||
ff = math.NaN()
|
||||
case "Infinity":
|
||||
ff = math.Inf(1)
|
||||
case "-Infinity":
|
||||
ff = math.Inf(-1)
|
||||
default:
|
||||
return fmt.Errorf("google.golang.org/api/internal: bad float string %q", s)
|
||||
}
|
||||
*f = JSONFloat64(ff)
|
||||
return nil
|
||||
}
|
||||
return errors.New("google.golang.org/api/internal: data not float or string")
|
||||
}
|
||||
372
vendor/google.golang.org/api/internal/gensupport/media.go
generated
vendored
372
vendor/google.golang.org/api/internal/gensupport/media.go
generated
vendored
@@ -1,372 +0,0 @@
|
||||
// Copyright 2016 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 gensupport
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"mime"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"net/textproto"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"google.golang.org/api/googleapi"
|
||||
)
|
||||
|
||||
const sniffBuffSize = 512
|
||||
|
||||
func newContentSniffer(r io.Reader) *contentSniffer {
|
||||
return &contentSniffer{r: r}
|
||||
}
|
||||
|
||||
// contentSniffer wraps a Reader, and reports the content type determined by sniffing up to 512 bytes from the Reader.
|
||||
type contentSniffer struct {
|
||||
r io.Reader
|
||||
start []byte // buffer for the sniffed bytes.
|
||||
err error // set to any error encountered while reading bytes to be sniffed.
|
||||
|
||||
ctype string // set on first sniff.
|
||||
sniffed bool // set to true on first sniff.
|
||||
}
|
||||
|
||||
func (cs *contentSniffer) Read(p []byte) (n int, err error) {
|
||||
// Ensure that the content type is sniffed before any data is consumed from Reader.
|
||||
_, _ = cs.ContentType()
|
||||
|
||||
if len(cs.start) > 0 {
|
||||
n := copy(p, cs.start)
|
||||
cs.start = cs.start[n:]
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// We may have read some bytes into start while sniffing, even if the read ended in an error.
|
||||
// We should first return those bytes, then the error.
|
||||
if cs.err != nil {
|
||||
return 0, cs.err
|
||||
}
|
||||
|
||||
// Now we have handled all bytes that were buffered while sniffing. Now just delegate to the underlying reader.
|
||||
return cs.r.Read(p)
|
||||
}
|
||||
|
||||
// ContentType returns the sniffed content type, and whether the content type was successfully sniffed.
|
||||
func (cs *contentSniffer) ContentType() (string, bool) {
|
||||
if cs.sniffed {
|
||||
return cs.ctype, cs.ctype != ""
|
||||
}
|
||||
cs.sniffed = true
|
||||
// If ReadAll hits EOF, it returns err==nil.
|
||||
cs.start, cs.err = ioutil.ReadAll(io.LimitReader(cs.r, sniffBuffSize))
|
||||
|
||||
// Don't try to detect the content type based on possibly incomplete data.
|
||||
if cs.err != nil {
|
||||
return "", false
|
||||
}
|
||||
|
||||
cs.ctype = http.DetectContentType(cs.start)
|
||||
return cs.ctype, true
|
||||
}
|
||||
|
||||
// DetermineContentType determines the content type of the supplied reader.
|
||||
// If the content type is already known, it can be specified via ctype.
|
||||
// Otherwise, the content of media will be sniffed to determine the content type.
|
||||
// If media implements googleapi.ContentTyper (deprecated), this will be used
|
||||
// instead of sniffing the content.
|
||||
// After calling DetectContentType the caller must not perform further reads on
|
||||
// media, but rather read from the Reader that is returned.
|
||||
func DetermineContentType(media io.Reader, ctype string) (io.Reader, string) {
|
||||
// Note: callers could avoid calling DetectContentType if ctype != "",
|
||||
// but doing the check inside this function reduces the amount of
|
||||
// generated code.
|
||||
if ctype != "" {
|
||||
return media, ctype
|
||||
}
|
||||
|
||||
// For backwards compatibility, allow clients to set content
|
||||
// type by providing a ContentTyper for media.
|
||||
if typer, ok := media.(googleapi.ContentTyper); ok {
|
||||
return media, typer.ContentType()
|
||||
}
|
||||
|
||||
sniffer := newContentSniffer(media)
|
||||
if ctype, ok := sniffer.ContentType(); ok {
|
||||
return sniffer, ctype
|
||||
}
|
||||
// If content type could not be sniffed, reads from sniffer will eventually fail with an error.
|
||||
return sniffer, ""
|
||||
}
|
||||
|
||||
type typeReader struct {
|
||||
io.Reader
|
||||
typ string
|
||||
}
|
||||
|
||||
// multipartReader combines the contents of multiple readers to create a multipart/related HTTP body.
|
||||
// Close must be called if reads from the multipartReader are abandoned before reaching EOF.
|
||||
type multipartReader struct {
|
||||
pr *io.PipeReader
|
||||
ctype string
|
||||
mu sync.Mutex
|
||||
pipeOpen bool
|
||||
}
|
||||
|
||||
// boundary optionally specifies the MIME boundary
|
||||
func newMultipartReader(parts []typeReader, boundary string) *multipartReader {
|
||||
mp := &multipartReader{pipeOpen: true}
|
||||
var pw *io.PipeWriter
|
||||
mp.pr, pw = io.Pipe()
|
||||
mpw := multipart.NewWriter(pw)
|
||||
if boundary != "" {
|
||||
mpw.SetBoundary(boundary)
|
||||
}
|
||||
mp.ctype = "multipart/related; boundary=" + mpw.Boundary()
|
||||
go func() {
|
||||
for _, part := range parts {
|
||||
w, err := mpw.CreatePart(typeHeader(part.typ))
|
||||
if err != nil {
|
||||
mpw.Close()
|
||||
pw.CloseWithError(fmt.Errorf("googleapi: CreatePart failed: %v", err))
|
||||
return
|
||||
}
|
||||
_, err = io.Copy(w, part.Reader)
|
||||
if err != nil {
|
||||
mpw.Close()
|
||||
pw.CloseWithError(fmt.Errorf("googleapi: Copy failed: %v", err))
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
mpw.Close()
|
||||
pw.Close()
|
||||
}()
|
||||
return mp
|
||||
}
|
||||
|
||||
func (mp *multipartReader) Read(data []byte) (n int, err error) {
|
||||
return mp.pr.Read(data)
|
||||
}
|
||||
|
||||
func (mp *multipartReader) Close() error {
|
||||
mp.mu.Lock()
|
||||
if !mp.pipeOpen {
|
||||
mp.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
mp.pipeOpen = false
|
||||
mp.mu.Unlock()
|
||||
return mp.pr.Close()
|
||||
}
|
||||
|
||||
// CombineBodyMedia combines a json body with media content to create a multipart/related HTTP body.
|
||||
// It returns a ReadCloser containing the combined body, and the overall "multipart/related" content type, with random boundary.
|
||||
//
|
||||
// The caller must call Close on the returned ReadCloser if reads are abandoned before reaching EOF.
|
||||
func CombineBodyMedia(body io.Reader, bodyContentType string, media io.Reader, mediaContentType string) (io.ReadCloser, string) {
|
||||
return combineBodyMedia(body, bodyContentType, media, mediaContentType, "")
|
||||
}
|
||||
|
||||
// combineBodyMedia is CombineBodyMedia but with an optional mimeBoundary field.
|
||||
func combineBodyMedia(body io.Reader, bodyContentType string, media io.Reader, mediaContentType, mimeBoundary string) (io.ReadCloser, string) {
|
||||
mp := newMultipartReader([]typeReader{
|
||||
{body, bodyContentType},
|
||||
{media, mediaContentType},
|
||||
}, mimeBoundary)
|
||||
return mp, mp.ctype
|
||||
}
|
||||
|
||||
func typeHeader(contentType string) textproto.MIMEHeader {
|
||||
h := make(textproto.MIMEHeader)
|
||||
if contentType != "" {
|
||||
h.Set("Content-Type", contentType)
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
// PrepareUpload determines whether the data in the supplied reader should be
|
||||
// uploaded in a single request, or in sequential chunks.
|
||||
// chunkSize is the size of the chunk that media should be split into.
|
||||
//
|
||||
// If chunkSize is zero, media is returned as the first value, and the other
|
||||
// two return values are nil, true.
|
||||
//
|
||||
// Otherwise, a MediaBuffer is returned, along with a bool indicating whether the
|
||||
// contents of media fit in a single chunk.
|
||||
//
|
||||
// After PrepareUpload has been called, media should no longer be used: the
|
||||
// media content should be accessed via one of the return values.
|
||||
func PrepareUpload(media io.Reader, chunkSize int) (r io.Reader, mb *MediaBuffer, singleChunk bool) {
|
||||
if chunkSize == 0 { // do not chunk
|
||||
return media, nil, true
|
||||
}
|
||||
mb = NewMediaBuffer(media, chunkSize)
|
||||
_, _, _, err := mb.Chunk()
|
||||
// If err is io.EOF, we can upload this in a single request. Otherwise, err is
|
||||
// either nil or a non-EOF error. If it is the latter, then the next call to
|
||||
// mb.Chunk will return the same error. Returning a MediaBuffer ensures that this
|
||||
// error will be handled at some point.
|
||||
return nil, mb, err == io.EOF
|
||||
}
|
||||
|
||||
// MediaInfo holds information for media uploads. It is intended for use by generated
|
||||
// code only.
|
||||
type MediaInfo struct {
|
||||
// At most one of Media and MediaBuffer will be set.
|
||||
media io.Reader
|
||||
buffer *MediaBuffer
|
||||
singleChunk bool
|
||||
mType string
|
||||
size int64 // mediaSize, if known. Used only for calls to progressUpdater_.
|
||||
progressUpdater googleapi.ProgressUpdater
|
||||
}
|
||||
|
||||
// NewInfoFromMedia should be invoked from the Media method of a call. It returns a
|
||||
// MediaInfo populated with chunk size and content type, and a reader or MediaBuffer
|
||||
// if needed.
|
||||
func NewInfoFromMedia(r io.Reader, options []googleapi.MediaOption) *MediaInfo {
|
||||
mi := &MediaInfo{}
|
||||
opts := googleapi.ProcessMediaOptions(options)
|
||||
if !opts.ForceEmptyContentType {
|
||||
r, mi.mType = DetermineContentType(r, opts.ContentType)
|
||||
}
|
||||
mi.media, mi.buffer, mi.singleChunk = PrepareUpload(r, opts.ChunkSize)
|
||||
return mi
|
||||
}
|
||||
|
||||
// NewInfoFromResumableMedia should be invoked from the ResumableMedia method of a
|
||||
// call. It returns a MediaInfo using the given reader, size and media type.
|
||||
func NewInfoFromResumableMedia(r io.ReaderAt, size int64, mediaType string) *MediaInfo {
|
||||
rdr := ReaderAtToReader(r, size)
|
||||
rdr, mType := DetermineContentType(rdr, mediaType)
|
||||
return &MediaInfo{
|
||||
size: size,
|
||||
mType: mType,
|
||||
buffer: NewMediaBuffer(rdr, googleapi.DefaultUploadChunkSize),
|
||||
media: nil,
|
||||
singleChunk: false,
|
||||
}
|
||||
}
|
||||
|
||||
// SetProgressUpdater sets the progress updater for the media info.
|
||||
func (mi *MediaInfo) SetProgressUpdater(pu googleapi.ProgressUpdater) {
|
||||
if mi != nil {
|
||||
mi.progressUpdater = pu
|
||||
}
|
||||
}
|
||||
|
||||
// UploadType determines the type of upload: a single request, or a resumable
|
||||
// series of requests.
|
||||
func (mi *MediaInfo) UploadType() string {
|
||||
if mi.singleChunk {
|
||||
return "multipart"
|
||||
}
|
||||
return "resumable"
|
||||
}
|
||||
|
||||
// UploadRequest sets up an HTTP request for media upload. It adds headers
|
||||
// as necessary, and returns a replacement for the body and a function for http.Request.GetBody.
|
||||
func (mi *MediaInfo) UploadRequest(reqHeaders http.Header, body io.Reader) (newBody io.Reader, getBody func() (io.ReadCloser, error), cleanup func()) {
|
||||
cleanup = func() {}
|
||||
if mi == nil {
|
||||
return body, nil, cleanup
|
||||
}
|
||||
var media io.Reader
|
||||
if mi.media != nil {
|
||||
// This only happens when the caller has turned off chunking. In that
|
||||
// case, we write all of media in a single non-retryable request.
|
||||
media = mi.media
|
||||
} else if mi.singleChunk {
|
||||
// The data fits in a single chunk, which has now been read into the MediaBuffer.
|
||||
// We obtain that chunk so we can write it in a single request. The request can
|
||||
// be retried because the data is stored in the MediaBuffer.
|
||||
media, _, _, _ = mi.buffer.Chunk()
|
||||
}
|
||||
if media != nil {
|
||||
fb := readerFunc(body)
|
||||
fm := readerFunc(media)
|
||||
combined, ctype := CombineBodyMedia(body, "application/json", media, mi.mType)
|
||||
toCleanup := []io.Closer{
|
||||
combined,
|
||||
}
|
||||
if fb != nil && fm != nil {
|
||||
getBody = func() (io.ReadCloser, error) {
|
||||
rb := ioutil.NopCloser(fb())
|
||||
rm := ioutil.NopCloser(fm())
|
||||
var mimeBoundary string
|
||||
if _, params, err := mime.ParseMediaType(ctype); err == nil {
|
||||
mimeBoundary = params["boundary"]
|
||||
}
|
||||
r, _ := combineBodyMedia(rb, "application/json", rm, mi.mType, mimeBoundary)
|
||||
toCleanup = append(toCleanup, r)
|
||||
return r, nil
|
||||
}
|
||||
}
|
||||
cleanup = func() {
|
||||
for _, closer := range toCleanup {
|
||||
_ = closer.Close()
|
||||
}
|
||||
|
||||
}
|
||||
reqHeaders.Set("Content-Type", ctype)
|
||||
body = combined
|
||||
}
|
||||
if mi.buffer != nil && mi.mType != "" && !mi.singleChunk {
|
||||
reqHeaders.Set("X-Upload-Content-Type", mi.mType)
|
||||
}
|
||||
return body, getBody, cleanup
|
||||
}
|
||||
|
||||
// readerFunc returns a function that always returns an io.Reader that has the same
|
||||
// contents as r, provided that can be done without consuming r. Otherwise, it
|
||||
// returns nil.
|
||||
// See http.NewRequest (in net/http/request.go).
|
||||
func readerFunc(r io.Reader) func() io.Reader {
|
||||
switch r := r.(type) {
|
||||
case *bytes.Buffer:
|
||||
buf := r.Bytes()
|
||||
return func() io.Reader { return bytes.NewReader(buf) }
|
||||
case *bytes.Reader:
|
||||
snapshot := *r
|
||||
return func() io.Reader { r := snapshot; return &r }
|
||||
case *strings.Reader:
|
||||
snapshot := *r
|
||||
return func() io.Reader { r := snapshot; return &r }
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// ResumableUpload returns an appropriately configured ResumableUpload value if the
|
||||
// upload is resumable, or nil otherwise.
|
||||
func (mi *MediaInfo) ResumableUpload(locURI string) *ResumableUpload {
|
||||
if mi == nil || mi.singleChunk {
|
||||
return nil
|
||||
}
|
||||
return &ResumableUpload{
|
||||
URI: locURI,
|
||||
Media: mi.buffer,
|
||||
MediaType: mi.mType,
|
||||
Callback: func(curr int64) {
|
||||
if mi.progressUpdater != nil {
|
||||
mi.progressUpdater(curr, mi.size)
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// SetGetBody sets the GetBody field of req to f. This was once needed
|
||||
// to gracefully support Go 1.7 and earlier which didn't have that
|
||||
// field.
|
||||
//
|
||||
// Deprecated: the code generator no longer uses this as of
|
||||
// 2019-02-19. Nothing else should be calling this anyway, but we
|
||||
// won't delete this immediately; it will be deleted in as early as 6
|
||||
// months.
|
||||
func SetGetBody(req *http.Request, f func() (io.ReadCloser, error)) {
|
||||
req.GetBody = f
|
||||
}
|
||||
57
vendor/google.golang.org/api/internal/gensupport/params.go
generated
vendored
57
vendor/google.golang.org/api/internal/gensupport/params.go
generated
vendored
@@ -1,57 +0,0 @@
|
||||
// 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 gensupport
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
|
||||
"google.golang.org/api/googleapi"
|
||||
)
|
||||
|
||||
// URLParams is a simplified replacement for url.Values
|
||||
// that safely builds up URL parameters for encoding.
|
||||
type URLParams map[string][]string
|
||||
|
||||
// Get returns the first value for the given key, or "".
|
||||
func (u URLParams) Get(key string) string {
|
||||
vs := u[key]
|
||||
if len(vs) == 0 {
|
||||
return ""
|
||||
}
|
||||
return vs[0]
|
||||
}
|
||||
|
||||
// Set sets the key to value.
|
||||
// It replaces any existing values.
|
||||
func (u URLParams) Set(key, value string) {
|
||||
u[key] = []string{value}
|
||||
}
|
||||
|
||||
// SetMulti sets the key to an array of values.
|
||||
// It replaces any existing values.
|
||||
// Note that values must not be modified after calling SetMulti
|
||||
// so the caller is responsible for making a copy if necessary.
|
||||
func (u URLParams) SetMulti(key string, values []string) {
|
||||
u[key] = values
|
||||
}
|
||||
|
||||
// Encode encodes the values into ``URL encoded'' form
|
||||
// ("bar=baz&foo=quux") sorted by key.
|
||||
func (u URLParams) Encode() string {
|
||||
return url.Values(u).Encode()
|
||||
}
|
||||
|
||||
// SetOptions sets the URL params and any additional `CallOption` or
|
||||
// `MultiCallOption` passed in.
|
||||
func SetOptions(u URLParams, opts ...googleapi.CallOption) {
|
||||
for _, o := range opts {
|
||||
m, ok := o.(googleapi.MultiCallOption)
|
||||
if ok {
|
||||
u.SetMulti(m.GetMulti())
|
||||
continue
|
||||
}
|
||||
u.Set(o.Get())
|
||||
}
|
||||
}
|
||||
258
vendor/google.golang.org/api/internal/gensupport/resumable.go
generated
vendored
258
vendor/google.golang.org/api/internal/gensupport/resumable.go
generated
vendored
@@ -1,258 +0,0 @@
|
||||
// Copyright 2016 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 gensupport
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
gax "github.com/googleapis/gax-go/v2"
|
||||
)
|
||||
|
||||
// Backoff is an interface around gax.Backoff's Pause method, allowing tests to provide their
|
||||
// own implementation.
|
||||
type Backoff interface {
|
||||
Pause() time.Duration
|
||||
}
|
||||
|
||||
// These are declared as global variables so that tests can overwrite them.
|
||||
var (
|
||||
retryDeadline = 32 * time.Second
|
||||
backoff = func() Backoff {
|
||||
return &gax.Backoff{Initial: 100 * time.Millisecond}
|
||||
}
|
||||
// isRetryable is a platform-specific hook, specified in retryable_linux.go
|
||||
syscallRetryable func(error) bool = func(err error) bool { return false }
|
||||
)
|
||||
|
||||
const (
|
||||
// statusTooManyRequests is returned by the storage API if the
|
||||
// per-project limits have been temporarily exceeded. The request
|
||||
// should be retried.
|
||||
// https://cloud.google.com/storage/docs/json_api/v1/status-codes#standardcodes
|
||||
statusTooManyRequests = 429
|
||||
)
|
||||
|
||||
// ResumableUpload is used by the generated APIs to provide resumable uploads.
|
||||
// It is not used by developers directly.
|
||||
type ResumableUpload struct {
|
||||
Client *http.Client
|
||||
// URI is the resumable resource destination provided by the server after specifying "&uploadType=resumable".
|
||||
URI string
|
||||
UserAgent string // User-Agent for header of the request
|
||||
// Media is the object being uploaded.
|
||||
Media *MediaBuffer
|
||||
// MediaType defines the media type, e.g. "image/jpeg".
|
||||
MediaType string
|
||||
|
||||
mu sync.Mutex // guards progress
|
||||
progress int64 // number of bytes uploaded so far
|
||||
|
||||
// Callback is an optional function that will be periodically called with the cumulative number of bytes uploaded.
|
||||
Callback func(int64)
|
||||
}
|
||||
|
||||
// Progress returns the number of bytes uploaded at this point.
|
||||
func (rx *ResumableUpload) Progress() int64 {
|
||||
rx.mu.Lock()
|
||||
defer rx.mu.Unlock()
|
||||
return rx.progress
|
||||
}
|
||||
|
||||
// doUploadRequest performs a single HTTP request to upload data.
|
||||
// off specifies the offset in rx.Media from which data is drawn.
|
||||
// size is the number of bytes in data.
|
||||
// final specifies whether data is the final chunk to be uploaded.
|
||||
func (rx *ResumableUpload) doUploadRequest(ctx context.Context, data io.Reader, off, size int64, final bool) (*http.Response, error) {
|
||||
req, err := http.NewRequest("POST", rx.URI, data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
req.ContentLength = size
|
||||
var contentRange string
|
||||
if final {
|
||||
if size == 0 {
|
||||
contentRange = fmt.Sprintf("bytes */%v", off)
|
||||
} else {
|
||||
contentRange = fmt.Sprintf("bytes %v-%v/%v", off, off+size-1, off+size)
|
||||
}
|
||||
} else {
|
||||
contentRange = fmt.Sprintf("bytes %v-%v/*", off, off+size-1)
|
||||
}
|
||||
req.Header.Set("Content-Range", contentRange)
|
||||
req.Header.Set("Content-Type", rx.MediaType)
|
||||
req.Header.Set("User-Agent", rx.UserAgent)
|
||||
|
||||
// Google's upload endpoint uses status code 308 for a
|
||||
// different purpose than the "308 Permanent Redirect"
|
||||
// since-standardized in RFC 7238. Because of the conflict in
|
||||
// semantics, Google added this new request header which
|
||||
// causes it to not use "308" and instead reply with 200 OK
|
||||
// and sets the upload-specific "X-HTTP-Status-Code-Override:
|
||||
// 308" response header.
|
||||
req.Header.Set("X-GUploader-No-308", "yes")
|
||||
|
||||
return SendRequest(ctx, rx.Client, req)
|
||||
}
|
||||
|
||||
func statusResumeIncomplete(resp *http.Response) bool {
|
||||
// This is how the server signals "status resume incomplete"
|
||||
// when X-GUploader-No-308 is set to "yes":
|
||||
return resp != nil && resp.Header.Get("X-Http-Status-Code-Override") == "308"
|
||||
}
|
||||
|
||||
// reportProgress calls a user-supplied callback to report upload progress.
|
||||
// If old==updated, the callback is not called.
|
||||
func (rx *ResumableUpload) reportProgress(old, updated int64) {
|
||||
if updated-old == 0 {
|
||||
return
|
||||
}
|
||||
rx.mu.Lock()
|
||||
rx.progress = updated
|
||||
rx.mu.Unlock()
|
||||
if rx.Callback != nil {
|
||||
rx.Callback(updated)
|
||||
}
|
||||
}
|
||||
|
||||
// transferChunk performs a single HTTP request to upload a single chunk from rx.Media.
|
||||
func (rx *ResumableUpload) transferChunk(ctx context.Context) (*http.Response, error) {
|
||||
chunk, off, size, err := rx.Media.Chunk()
|
||||
|
||||
done := err == io.EOF
|
||||
if !done && err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
res, err := rx.doUploadRequest(ctx, chunk, off, int64(size), done)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
// We sent "X-GUploader-No-308: yes" (see comment elsewhere in
|
||||
// this file), so we don't expect to get a 308.
|
||||
if res.StatusCode == 308 {
|
||||
return nil, errors.New("unexpected 308 response status code")
|
||||
}
|
||||
|
||||
if res.StatusCode == http.StatusOK {
|
||||
rx.reportProgress(off, off+int64(size))
|
||||
}
|
||||
|
||||
if statusResumeIncomplete(res) {
|
||||
rx.Media.Next()
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
|
||||
// Upload starts the process of a resumable upload with a cancellable context.
|
||||
// It retries using the provided back off strategy until cancelled or the
|
||||
// strategy indicates to stop retrying.
|
||||
// It is called from the auto-generated API code and is not visible to the user.
|
||||
// Before sending an HTTP request, Upload calls any registered hook functions,
|
||||
// and calls the returned functions after the request returns (see send.go).
|
||||
// rx is private to the auto-generated API code.
|
||||
// Exactly one of resp or err will be nil. If resp is non-nil, the caller must call resp.Body.Close.
|
||||
func (rx *ResumableUpload) Upload(ctx context.Context) (resp *http.Response, err error) {
|
||||
|
||||
// There are a couple of cases where it's possible for err and resp to both
|
||||
// be non-nil. However, we expose a simpler contract to our callers: exactly
|
||||
// one of resp and err will be non-nil. This means that any response body
|
||||
// must be closed here before returning a non-nil error.
|
||||
var prepareReturn = func(resp *http.Response, err error) (*http.Response, error) {
|
||||
if err != nil {
|
||||
if resp != nil && resp.Body != nil {
|
||||
resp.Body.Close()
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// Send all chunks.
|
||||
for {
|
||||
var pause time.Duration
|
||||
|
||||
// Each chunk gets its own initialized-at-zero retry.
|
||||
bo := backoff()
|
||||
quitAfter := time.After(retryDeadline)
|
||||
|
||||
// Retry loop for a single chunk.
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
if err == nil {
|
||||
err = ctx.Err()
|
||||
}
|
||||
return prepareReturn(resp, err)
|
||||
case <-time.After(pause):
|
||||
case <-quitAfter:
|
||||
return prepareReturn(resp, err)
|
||||
}
|
||||
|
||||
resp, err = rx.transferChunk(ctx)
|
||||
|
||||
var status int
|
||||
if resp != nil {
|
||||
status = resp.StatusCode
|
||||
}
|
||||
|
||||
// Check if we should retry the request.
|
||||
if !shouldRetry(status, err) {
|
||||
break
|
||||
}
|
||||
|
||||
pause = bo.Pause()
|
||||
if resp != nil && resp.Body != nil {
|
||||
resp.Body.Close()
|
||||
}
|
||||
}
|
||||
|
||||
// If the chunk was uploaded successfully, but there's still
|
||||
// more to go, upload the next chunk without any delay.
|
||||
if statusResumeIncomplete(resp) {
|
||||
resp.Body.Close()
|
||||
continue
|
||||
}
|
||||
|
||||
return prepareReturn(resp, err)
|
||||
}
|
||||
}
|
||||
|
||||
// shouldRetry indicates whether an error is retryable for the purposes of this
|
||||
// package, following guidance from
|
||||
// https://cloud.google.com/storage/docs/exponential-backoff .
|
||||
func shouldRetry(status int, err error) bool {
|
||||
if 500 <= status && status <= 599 {
|
||||
return true
|
||||
}
|
||||
if status == statusTooManyRequests {
|
||||
return true
|
||||
}
|
||||
if err == io.ErrUnexpectedEOF {
|
||||
return true
|
||||
}
|
||||
// Transient network errors should be retried.
|
||||
if syscallRetryable(err) {
|
||||
return true
|
||||
}
|
||||
if err, ok := err.(interface{ Temporary() bool }); ok {
|
||||
if err.Temporary() {
|
||||
return true
|
||||
}
|
||||
}
|
||||
// If Go 1.13 error unwrapping is available, use this to examine wrapped
|
||||
// errors.
|
||||
if err, ok := err.(interface{ Unwrap() error }); ok {
|
||||
return shouldRetry(status, err.Unwrap())
|
||||
}
|
||||
return false
|
||||
}
|
||||
16
vendor/google.golang.org/api/internal/gensupport/retryable_linux.go
generated
vendored
16
vendor/google.golang.org/api/internal/gensupport/retryable_linux.go
generated
vendored
@@ -1,16 +0,0 @@
|
||||
// Copyright 2020 Google LLC.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
//go:build linux
|
||||
// +build linux
|
||||
|
||||
package gensupport
|
||||
|
||||
import "syscall"
|
||||
|
||||
func init() {
|
||||
// Initialize syscallRetryable to return true on transient socket-level
|
||||
// errors. These errors are specific to Linux.
|
||||
syscallRetryable = func(err error) bool { return err == syscall.ECONNRESET || err == syscall.ECONNREFUSED }
|
||||
}
|
||||
123
vendor/google.golang.org/api/internal/gensupport/send.go
generated
vendored
123
vendor/google.golang.org/api/internal/gensupport/send.go
generated
vendored
@@ -1,123 +0,0 @@
|
||||
// Copyright 2016 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 gensupport
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
// SendRequest sends a single HTTP request using the given client.
|
||||
// If ctx is non-nil, it calls all hooks, then sends the request with
|
||||
// req.WithContext, then calls any functions returned by the hooks in
|
||||
// reverse order.
|
||||
func SendRequest(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error) {
|
||||
// Disallow Accept-Encoding because it interferes with the automatic gzip handling
|
||||
// done by the default http.Transport. See https://github.com/google/google-api-go-client/issues/219.
|
||||
if _, ok := req.Header["Accept-Encoding"]; ok {
|
||||
return nil, errors.New("google api: custom Accept-Encoding headers not allowed")
|
||||
}
|
||||
if ctx == nil {
|
||||
return client.Do(req)
|
||||
}
|
||||
return send(ctx, client, req)
|
||||
}
|
||||
|
||||
func send(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error) {
|
||||
if client == nil {
|
||||
client = http.DefaultClient
|
||||
}
|
||||
resp, err := client.Do(req.WithContext(ctx))
|
||||
// If we got an error, and the context has been canceled,
|
||||
// the context's error is probably more useful.
|
||||
if err != nil {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
err = ctx.Err()
|
||||
default:
|
||||
}
|
||||
}
|
||||
return resp, err
|
||||
}
|
||||
|
||||
// SendRequestWithRetry sends a single HTTP request using the given client,
|
||||
// with retries if a retryable error is returned.
|
||||
// If ctx is non-nil, it calls all hooks, then sends the request with
|
||||
// req.WithContext, then calls any functions returned by the hooks in
|
||||
// reverse order.
|
||||
func SendRequestWithRetry(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error) {
|
||||
// Disallow Accept-Encoding because it interferes with the automatic gzip handling
|
||||
// done by the default http.Transport. See https://github.com/google/google-api-go-client/issues/219.
|
||||
if _, ok := req.Header["Accept-Encoding"]; ok {
|
||||
return nil, errors.New("google api: custom Accept-Encoding headers not allowed")
|
||||
}
|
||||
if ctx == nil {
|
||||
return client.Do(req)
|
||||
}
|
||||
return sendAndRetry(ctx, client, req)
|
||||
}
|
||||
|
||||
func sendAndRetry(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error) {
|
||||
if client == nil {
|
||||
client = http.DefaultClient
|
||||
}
|
||||
|
||||
var resp *http.Response
|
||||
var err error
|
||||
|
||||
// Loop to retry the request, up to the context deadline.
|
||||
var pause time.Duration
|
||||
bo := backoff()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
// If we got an error, and the context has been canceled,
|
||||
// the context's error is probably more useful.
|
||||
if err == nil {
|
||||
err = ctx.Err()
|
||||
}
|
||||
return resp, err
|
||||
case <-time.After(pause):
|
||||
}
|
||||
|
||||
resp, err = client.Do(req.WithContext(ctx))
|
||||
|
||||
var status int
|
||||
if resp != nil {
|
||||
status = resp.StatusCode
|
||||
}
|
||||
|
||||
// Check if we can retry the request. A retry can only be done if the error
|
||||
// is retryable and the request body can be re-created using GetBody (this
|
||||
// will not be possible if the body was unbuffered).
|
||||
if req.GetBody == nil || !shouldRetry(status, err) {
|
||||
break
|
||||
}
|
||||
var errBody error
|
||||
req.Body, errBody = req.GetBody()
|
||||
if errBody != nil {
|
||||
break
|
||||
}
|
||||
|
||||
pause = bo.Pause()
|
||||
if resp != nil && resp.Body != nil {
|
||||
resp.Body.Close()
|
||||
}
|
||||
}
|
||||
return resp, err
|
||||
}
|
||||
|
||||
// DecodeResponse decodes the body of res into target. If there is no body,
|
||||
// target is unchanged.
|
||||
func DecodeResponse(target interface{}, res *http.Response) error {
|
||||
if res.StatusCode == http.StatusNoContent {
|
||||
return nil
|
||||
}
|
||||
return json.NewDecoder(res.Body).Decode(target)
|
||||
}
|
||||
53
vendor/google.golang.org/api/internal/gensupport/version.go
generated
vendored
53
vendor/google.golang.org/api/internal/gensupport/version.go
generated
vendored
@@ -1,53 +0,0 @@
|
||||
// Copyright 2020 Google LLC. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package gensupport
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
"strings"
|
||||
"unicode"
|
||||
)
|
||||
|
||||
// GoVersion returns the Go runtime version. The returned string
|
||||
// has no whitespace.
|
||||
func GoVersion() string {
|
||||
return goVersion
|
||||
}
|
||||
|
||||
var goVersion = goVer(runtime.Version())
|
||||
|
||||
const develPrefix = "devel +"
|
||||
|
||||
func goVer(s string) string {
|
||||
if strings.HasPrefix(s, develPrefix) {
|
||||
s = s[len(develPrefix):]
|
||||
if p := strings.IndexFunc(s, unicode.IsSpace); p >= 0 {
|
||||
s = s[:p]
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
if strings.HasPrefix(s, "go1") {
|
||||
s = s[2:]
|
||||
var prerelease string
|
||||
if p := strings.IndexFunc(s, notSemverRune); p >= 0 {
|
||||
s, prerelease = s[:p], s[p:]
|
||||
}
|
||||
if strings.HasSuffix(s, ".") {
|
||||
s += "0"
|
||||
} else if strings.Count(s, ".") < 2 {
|
||||
s += ".0"
|
||||
}
|
||||
if prerelease != "" {
|
||||
s += "-" + prerelease
|
||||
}
|
||||
return s
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func notSemverRune(r rune) bool {
|
||||
return !strings.ContainsRune("0123456789.", r)
|
||||
}
|
||||
128
vendor/google.golang.org/api/internal/impersonate/impersonate.go
generated
vendored
128
vendor/google.golang.org/api/internal/impersonate/impersonate.go
generated
vendored
@@ -1,128 +0,0 @@
|
||||
// Copyright 2020 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 impersonate is used to impersonate Google Credentials.
|
||||
package impersonate
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"golang.org/x/oauth2"
|
||||
)
|
||||
|
||||
// Config for generating impersonated credentials.
|
||||
type Config struct {
|
||||
// Target is the service account to impersonate. Required.
|
||||
Target string
|
||||
// Scopes the impersonated credential should have. Required.
|
||||
Scopes []string
|
||||
// Delegates are the service accounts in a delegation chain. Each service
|
||||
// account must be granted roles/iam.serviceAccountTokenCreator on the next
|
||||
// service account in the chain. Optional.
|
||||
Delegates []string
|
||||
}
|
||||
|
||||
// TokenSource returns an impersonated TokenSource configured with the provided
|
||||
// config using ts as the base credential provider for making requests.
|
||||
func TokenSource(ctx context.Context, ts oauth2.TokenSource, config *Config) (oauth2.TokenSource, error) {
|
||||
if len(config.Scopes) == 0 {
|
||||
return nil, fmt.Errorf("impersonate: scopes must be provided")
|
||||
}
|
||||
its := impersonatedTokenSource{
|
||||
ctx: ctx,
|
||||
ts: ts,
|
||||
name: formatIAMServiceAccountName(config.Target),
|
||||
// Default to the longest acceptable value of one hour as the token will
|
||||
// be refreshed automatically.
|
||||
lifetime: "3600s",
|
||||
}
|
||||
|
||||
its.delegates = make([]string, len(config.Delegates))
|
||||
for i, v := range config.Delegates {
|
||||
its.delegates[i] = formatIAMServiceAccountName(v)
|
||||
}
|
||||
its.scopes = make([]string, len(config.Scopes))
|
||||
copy(its.scopes, config.Scopes)
|
||||
|
||||
return oauth2.ReuseTokenSource(nil, its), nil
|
||||
}
|
||||
|
||||
func formatIAMServiceAccountName(name string) string {
|
||||
return fmt.Sprintf("projects/-/serviceAccounts/%s", name)
|
||||
}
|
||||
|
||||
type generateAccessTokenReq struct {
|
||||
Delegates []string `json:"delegates,omitempty"`
|
||||
Lifetime string `json:"lifetime,omitempty"`
|
||||
Scope []string `json:"scope,omitempty"`
|
||||
}
|
||||
|
||||
type generateAccessTokenResp struct {
|
||||
AccessToken string `json:"accessToken"`
|
||||
ExpireTime string `json:"expireTime"`
|
||||
}
|
||||
|
||||
type impersonatedTokenSource struct {
|
||||
ctx context.Context
|
||||
ts oauth2.TokenSource
|
||||
|
||||
name string
|
||||
lifetime string
|
||||
scopes []string
|
||||
delegates []string
|
||||
}
|
||||
|
||||
// Token returns an impersonated Token.
|
||||
func (i impersonatedTokenSource) Token() (*oauth2.Token, error) {
|
||||
hc := oauth2.NewClient(i.ctx, i.ts)
|
||||
reqBody := generateAccessTokenReq{
|
||||
Delegates: i.delegates,
|
||||
Lifetime: i.lifetime,
|
||||
Scope: i.scopes,
|
||||
}
|
||||
b, err := json.Marshal(reqBody)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("impersonate: unable to marshal request: %v", err)
|
||||
}
|
||||
url := fmt.Sprintf("https://iamcredentials.googleapis.com/v1/%s:generateAccessToken", i.name)
|
||||
req, err := http.NewRequest("POST", url, bytes.NewReader(b))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("impersonate: unable to create request: %v", err)
|
||||
}
|
||||
req = req.WithContext(i.ctx)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := hc.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("impersonate: unable to generate access token: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, err := ioutil.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("impersonate: unable to read body: %v", err)
|
||||
}
|
||||
if c := resp.StatusCode; c < 200 || c > 299 {
|
||||
return nil, fmt.Errorf("impersonate: status code %d: %s", c, body)
|
||||
}
|
||||
|
||||
var accessTokenResp generateAccessTokenResp
|
||||
if err := json.Unmarshal(body, &accessTokenResp); err != nil {
|
||||
return nil, fmt.Errorf("impersonate: unable to parse response: %v", err)
|
||||
}
|
||||
expiry, err := time.Parse(time.RFC3339, accessTokenResp.ExpireTime)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("impersonate: unable to parse expiry: %v", err)
|
||||
}
|
||||
return &oauth2.Token{
|
||||
AccessToken: accessTokenResp.AccessToken,
|
||||
Expiry: expiry,
|
||||
}, nil
|
||||
}
|
||||
142
vendor/google.golang.org/api/internal/settings.go
generated
vendored
142
vendor/google.golang.org/api/internal/settings.go
generated
vendored
@@ -1,142 +0,0 @@
|
||||
// Copyright 2017 Google LLC.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package internal supports the options and transport packages.
|
||||
package internal
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"golang.org/x/oauth2"
|
||||
"golang.org/x/oauth2/google"
|
||||
"google.golang.org/api/internal/impersonate"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
// DialSettings holds information needed to establish a connection with a
|
||||
// Google API service.
|
||||
type DialSettings struct {
|
||||
Endpoint string
|
||||
DefaultEndpoint string
|
||||
DefaultMTLSEndpoint string
|
||||
Scopes []string
|
||||
DefaultScopes []string
|
||||
EnableJwtWithScope bool
|
||||
TokenSource oauth2.TokenSource
|
||||
Credentials *google.Credentials
|
||||
CredentialsFile string // if set, Token Source is ignored.
|
||||
CredentialsJSON []byte
|
||||
InternalCredentials *google.Credentials
|
||||
UserAgent string
|
||||
APIKey string
|
||||
Audiences []string
|
||||
DefaultAudience string
|
||||
HTTPClient *http.Client
|
||||
GRPCDialOpts []grpc.DialOption
|
||||
GRPCConn *grpc.ClientConn
|
||||
GRPCConnPool ConnPool
|
||||
GRPCConnPoolSize int
|
||||
NoAuth bool
|
||||
TelemetryDisabled bool
|
||||
ClientCertSource func(*tls.CertificateRequestInfo) (*tls.Certificate, error)
|
||||
CustomClaims map[string]interface{}
|
||||
SkipValidation bool
|
||||
ImpersonationConfig *impersonate.Config
|
||||
EnableDirectPath bool
|
||||
AllowNonDefaultServiceAccount bool
|
||||
|
||||
// Google API system parameters. For more information please read:
|
||||
// https://cloud.google.com/apis/docs/system-parameters
|
||||
QuotaProject string
|
||||
RequestReason string
|
||||
}
|
||||
|
||||
// GetScopes returns the user-provided scopes, if set, or else falls back to the
|
||||
// default scopes.
|
||||
func (ds *DialSettings) GetScopes() []string {
|
||||
if len(ds.Scopes) > 0 {
|
||||
return ds.Scopes
|
||||
}
|
||||
return ds.DefaultScopes
|
||||
}
|
||||
|
||||
// GetAudience returns the user-provided audience, if set, or else falls back to the default audience.
|
||||
func (ds *DialSettings) GetAudience() string {
|
||||
if ds.HasCustomAudience() {
|
||||
return ds.Audiences[0]
|
||||
}
|
||||
return ds.DefaultAudience
|
||||
}
|
||||
|
||||
// HasCustomAudience returns true if a custom audience is provided by users.
|
||||
func (ds *DialSettings) HasCustomAudience() bool {
|
||||
return len(ds.Audiences) > 0
|
||||
}
|
||||
|
||||
// Validate reports an error if ds is invalid.
|
||||
func (ds *DialSettings) Validate() error {
|
||||
if ds.SkipValidation {
|
||||
return nil
|
||||
}
|
||||
hasCreds := ds.APIKey != "" || ds.TokenSource != nil || ds.CredentialsFile != "" || ds.Credentials != nil
|
||||
if ds.NoAuth && hasCreds {
|
||||
return errors.New("options.WithoutAuthentication is incompatible with any option that provides credentials")
|
||||
}
|
||||
// Credentials should not appear with other options.
|
||||
// We currently allow TokenSource and CredentialsFile to coexist.
|
||||
// TODO(jba): make TokenSource & CredentialsFile an error (breaking change).
|
||||
nCreds := 0
|
||||
if ds.Credentials != nil {
|
||||
nCreds++
|
||||
}
|
||||
if ds.CredentialsJSON != nil {
|
||||
nCreds++
|
||||
}
|
||||
if ds.CredentialsFile != "" {
|
||||
nCreds++
|
||||
}
|
||||
if ds.APIKey != "" {
|
||||
nCreds++
|
||||
}
|
||||
if ds.TokenSource != nil {
|
||||
nCreds++
|
||||
}
|
||||
if len(ds.Scopes) > 0 && len(ds.Audiences) > 0 {
|
||||
return errors.New("WithScopes is incompatible with WithAudience")
|
||||
}
|
||||
// Accept only one form of credentials, except we allow TokenSource and CredentialsFile for backwards compatibility.
|
||||
if nCreds > 1 && !(nCreds == 2 && ds.TokenSource != nil && ds.CredentialsFile != "") {
|
||||
return errors.New("multiple credential options provided")
|
||||
}
|
||||
if ds.GRPCConn != nil && ds.GRPCConnPool != nil {
|
||||
return errors.New("WithGRPCConn is incompatible with WithConnPool")
|
||||
}
|
||||
if ds.HTTPClient != nil && ds.GRPCConnPool != nil {
|
||||
return errors.New("WithHTTPClient is incompatible with WithConnPool")
|
||||
}
|
||||
if ds.HTTPClient != nil && ds.GRPCConn != nil {
|
||||
return errors.New("WithHTTPClient is incompatible with WithGRPCConn")
|
||||
}
|
||||
if ds.HTTPClient != nil && ds.GRPCDialOpts != nil {
|
||||
return errors.New("WithHTTPClient is incompatible with gRPC dial options")
|
||||
}
|
||||
if ds.HTTPClient != nil && ds.QuotaProject != "" {
|
||||
return errors.New("WithHTTPClient is incompatible with QuotaProject")
|
||||
}
|
||||
if ds.HTTPClient != nil && ds.RequestReason != "" {
|
||||
return errors.New("WithHTTPClient is incompatible with RequestReason")
|
||||
}
|
||||
if ds.HTTPClient != nil && ds.ClientCertSource != nil {
|
||||
return errors.New("WithHTTPClient is incompatible with WithClientCertSource")
|
||||
}
|
||||
if ds.ClientCertSource != nil && (ds.GRPCConn != nil || ds.GRPCConnPool != nil || ds.GRPCConnPoolSize != 0 || ds.GRPCDialOpts != nil) {
|
||||
return errors.New("WithClientCertSource is currently only supported for HTTP. gRPC settings are incompatible")
|
||||
}
|
||||
if ds.ImpersonationConfig != nil && len(ds.ImpersonationConfig.Scopes) == 0 && len(ds.Scopes) == 0 {
|
||||
return errors.New("WithImpersonatedCredentials requires scopes being provided")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
27
vendor/google.golang.org/api/internal/third_party/uritemplates/LICENSE
generated
vendored
27
vendor/google.golang.org/api/internal/third_party/uritemplates/LICENSE
generated
vendored
@@ -1,27 +0,0 @@
|
||||
Copyright (c) 2013 Joshua Tacoma. All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are
|
||||
met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above
|
||||
copyright notice, this list of conditions and the following disclaimer
|
||||
in the documentation and/or other materials provided with the
|
||||
distribution.
|
||||
* Neither the name of Google Inc. nor the names of its
|
||||
contributors may be used to endorse or promote products derived from
|
||||
this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
14
vendor/google.golang.org/api/internal/third_party/uritemplates/METADATA
generated
vendored
14
vendor/google.golang.org/api/internal/third_party/uritemplates/METADATA
generated
vendored
@@ -1,14 +0,0 @@
|
||||
name: "uritemplates"
|
||||
description:
|
||||
"Package uritemplates is a level 4 implementation of RFC 6570 (URI "
|
||||
"Template, http://tools.ietf.org/html/rfc6570)."
|
||||
|
||||
third_party {
|
||||
url {
|
||||
type: GIT
|
||||
value: "https://github.com/jtacoma/uritemplates"
|
||||
}
|
||||
version: "0.1"
|
||||
last_upgrade_date { year: 2014 month: 8 day: 18 }
|
||||
license_type: NOTICE
|
||||
}
|
||||
248
vendor/google.golang.org/api/internal/third_party/uritemplates/uritemplates.go
generated
vendored
248
vendor/google.golang.org/api/internal/third_party/uritemplates/uritemplates.go
generated
vendored
@@ -1,248 +0,0 @@
|
||||
// Copyright 2013 Joshua Tacoma. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package uritemplates is a level 3 implementation of RFC 6570 (URI
|
||||
// Template, http://tools.ietf.org/html/rfc6570).
|
||||
// uritemplates does not support composite values (in Go: slices or maps)
|
||||
// and so does not qualify as a level 4 implementation.
|
||||
package uritemplates
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var (
|
||||
unreserved = regexp.MustCompile("[^A-Za-z0-9\\-._~]")
|
||||
reserved = regexp.MustCompile("[^A-Za-z0-9\\-._~:/?#[\\]@!$&'()*+,;=]")
|
||||
validname = regexp.MustCompile("^([A-Za-z0-9_\\.]|%[0-9A-Fa-f][0-9A-Fa-f])+$")
|
||||
hex = []byte("0123456789ABCDEF")
|
||||
)
|
||||
|
||||
func pctEncode(src []byte) []byte {
|
||||
dst := make([]byte, len(src)*3)
|
||||
for i, b := range src {
|
||||
buf := dst[i*3 : i*3+3]
|
||||
buf[0] = 0x25
|
||||
buf[1] = hex[b/16]
|
||||
buf[2] = hex[b%16]
|
||||
}
|
||||
return dst
|
||||
}
|
||||
|
||||
// pairWriter is a convenience struct which allows escaped and unescaped
|
||||
// versions of the template to be written in parallel.
|
||||
type pairWriter struct {
|
||||
escaped, unescaped bytes.Buffer
|
||||
}
|
||||
|
||||
// Write writes the provided string directly without any escaping.
|
||||
func (w *pairWriter) Write(s string) {
|
||||
w.escaped.WriteString(s)
|
||||
w.unescaped.WriteString(s)
|
||||
}
|
||||
|
||||
// Escape writes the provided string, escaping the string for the
|
||||
// escaped output.
|
||||
func (w *pairWriter) Escape(s string, allowReserved bool) {
|
||||
w.unescaped.WriteString(s)
|
||||
if allowReserved {
|
||||
w.escaped.Write(reserved.ReplaceAllFunc([]byte(s), pctEncode))
|
||||
} else {
|
||||
w.escaped.Write(unreserved.ReplaceAllFunc([]byte(s), pctEncode))
|
||||
}
|
||||
}
|
||||
|
||||
// Escaped returns the escaped string.
|
||||
func (w *pairWriter) Escaped() string {
|
||||
return w.escaped.String()
|
||||
}
|
||||
|
||||
// Unescaped returns the unescaped string.
|
||||
func (w *pairWriter) Unescaped() string {
|
||||
return w.unescaped.String()
|
||||
}
|
||||
|
||||
// A uriTemplate is a parsed representation of a URI template.
|
||||
type uriTemplate struct {
|
||||
raw string
|
||||
parts []templatePart
|
||||
}
|
||||
|
||||
// parse parses a URI template string into a uriTemplate object.
|
||||
func parse(rawTemplate string) (*uriTemplate, error) {
|
||||
split := strings.Split(rawTemplate, "{")
|
||||
parts := make([]templatePart, len(split)*2-1)
|
||||
for i, s := range split {
|
||||
if i == 0 {
|
||||
if strings.Contains(s, "}") {
|
||||
return nil, errors.New("unexpected }")
|
||||
}
|
||||
parts[i].raw = s
|
||||
continue
|
||||
}
|
||||
subsplit := strings.Split(s, "}")
|
||||
if len(subsplit) != 2 {
|
||||
return nil, errors.New("malformed template")
|
||||
}
|
||||
expression := subsplit[0]
|
||||
var err error
|
||||
parts[i*2-1], err = parseExpression(expression)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
parts[i*2].raw = subsplit[1]
|
||||
}
|
||||
return &uriTemplate{
|
||||
raw: rawTemplate,
|
||||
parts: parts,
|
||||
}, nil
|
||||
}
|
||||
|
||||
type templatePart struct {
|
||||
raw string
|
||||
terms []templateTerm
|
||||
first string
|
||||
sep string
|
||||
named bool
|
||||
ifemp string
|
||||
allowReserved bool
|
||||
}
|
||||
|
||||
type templateTerm struct {
|
||||
name string
|
||||
explode bool
|
||||
truncate int
|
||||
}
|
||||
|
||||
func parseExpression(expression string) (result templatePart, err error) {
|
||||
switch expression[0] {
|
||||
case '+':
|
||||
result.sep = ","
|
||||
result.allowReserved = true
|
||||
expression = expression[1:]
|
||||
case '.':
|
||||
result.first = "."
|
||||
result.sep = "."
|
||||
expression = expression[1:]
|
||||
case '/':
|
||||
result.first = "/"
|
||||
result.sep = "/"
|
||||
expression = expression[1:]
|
||||
case ';':
|
||||
result.first = ";"
|
||||
result.sep = ";"
|
||||
result.named = true
|
||||
expression = expression[1:]
|
||||
case '?':
|
||||
result.first = "?"
|
||||
result.sep = "&"
|
||||
result.named = true
|
||||
result.ifemp = "="
|
||||
expression = expression[1:]
|
||||
case '&':
|
||||
result.first = "&"
|
||||
result.sep = "&"
|
||||
result.named = true
|
||||
result.ifemp = "="
|
||||
expression = expression[1:]
|
||||
case '#':
|
||||
result.first = "#"
|
||||
result.sep = ","
|
||||
result.allowReserved = true
|
||||
expression = expression[1:]
|
||||
default:
|
||||
result.sep = ","
|
||||
}
|
||||
rawterms := strings.Split(expression, ",")
|
||||
result.terms = make([]templateTerm, len(rawterms))
|
||||
for i, raw := range rawterms {
|
||||
result.terms[i], err = parseTerm(raw)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
return result, err
|
||||
}
|
||||
|
||||
func parseTerm(term string) (result templateTerm, err error) {
|
||||
// TODO(djd): Remove "*" suffix parsing once we check that no APIs have
|
||||
// mistakenly used that attribute.
|
||||
if strings.HasSuffix(term, "*") {
|
||||
result.explode = true
|
||||
term = term[:len(term)-1]
|
||||
}
|
||||
split := strings.Split(term, ":")
|
||||
if len(split) == 1 {
|
||||
result.name = term
|
||||
} else if len(split) == 2 {
|
||||
result.name = split[0]
|
||||
var parsed int64
|
||||
parsed, err = strconv.ParseInt(split[1], 10, 0)
|
||||
result.truncate = int(parsed)
|
||||
} else {
|
||||
err = errors.New("multiple colons in same term")
|
||||
}
|
||||
if !validname.MatchString(result.name) {
|
||||
err = errors.New("not a valid name: " + result.name)
|
||||
}
|
||||
if result.explode && result.truncate > 0 {
|
||||
err = errors.New("both explode and prefix modifiers on same term")
|
||||
}
|
||||
return result, err
|
||||
}
|
||||
|
||||
// Expand expands a URI template with a set of values to produce the
|
||||
// resultant URI. Two forms of the result are returned: one with all the
|
||||
// elements escaped, and one with the elements unescaped.
|
||||
func (t *uriTemplate) Expand(values map[string]string) (escaped, unescaped string) {
|
||||
var w pairWriter
|
||||
for _, p := range t.parts {
|
||||
p.expand(&w, values)
|
||||
}
|
||||
return w.Escaped(), w.Unescaped()
|
||||
}
|
||||
|
||||
func (tp *templatePart) expand(w *pairWriter, values map[string]string) {
|
||||
if len(tp.raw) > 0 {
|
||||
w.Write(tp.raw)
|
||||
return
|
||||
}
|
||||
var first = true
|
||||
for _, term := range tp.terms {
|
||||
value, exists := values[term.name]
|
||||
if !exists {
|
||||
continue
|
||||
}
|
||||
if first {
|
||||
w.Write(tp.first)
|
||||
first = false
|
||||
} else {
|
||||
w.Write(tp.sep)
|
||||
}
|
||||
tp.expandString(w, term, value)
|
||||
}
|
||||
}
|
||||
|
||||
func (tp *templatePart) expandName(w *pairWriter, name string, empty bool) {
|
||||
if tp.named {
|
||||
w.Write(name)
|
||||
if empty {
|
||||
w.Write(tp.ifemp)
|
||||
} else {
|
||||
w.Write("=")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (tp *templatePart) expandString(w *pairWriter, t templateTerm, s string) {
|
||||
if len(s) > t.truncate && t.truncate > 0 {
|
||||
s = s[:t.truncate]
|
||||
}
|
||||
tp.expandName(w, t.name, len(s) == 0)
|
||||
w.Escape(s, tp.allowReserved)
|
||||
}
|
||||
17
vendor/google.golang.org/api/internal/third_party/uritemplates/utils.go
generated
vendored
17
vendor/google.golang.org/api/internal/third_party/uritemplates/utils.go
generated
vendored
@@ -1,17 +0,0 @@
|
||||
// Copyright 2016 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 uritemplates
|
||||
|
||||
// Expand parses then expands a URI template with a set of values to produce
|
||||
// the resultant URI. Two forms of the result are returned: one with all the
|
||||
// elements escaped, and one with the elements unescaped.
|
||||
func Expand(path string, values map[string]string) (escaped, unescaped string, err error) {
|
||||
template, err := parse(path)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
escaped, unescaped = template.Expand(values)
|
||||
return escaped, unescaped, nil
|
||||
}
|
||||
234
vendor/google.golang.org/api/oauth2/v2/oauth2-api.json
generated
vendored
234
vendor/google.golang.org/api/oauth2/v2/oauth2-api.json
generated
vendored
@@ -1,234 +0,0 @@
|
||||
{
|
||||
"auth": {
|
||||
"oauth2": {
|
||||
"scopes": {
|
||||
"https://www.googleapis.com/auth/userinfo.email": {
|
||||
"description": "View your email address"
|
||||
},
|
||||
"https://www.googleapis.com/auth/userinfo.profile": {
|
||||
"description": "See your personal info, including any personal info you've made publicly available"
|
||||
},
|
||||
"openid": {
|
||||
"description": "Associate you with your personal info on Google"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"basePath": "/",
|
||||
"baseUrl": "https://www.googleapis.com/",
|
||||
"batchPath": "batch/oauth2/v2",
|
||||
"description": "Obtains end-user authorization grants for use with other Google APIs.",
|
||||
"discoveryVersion": "v1",
|
||||
"documentationLink": "https://developers.google.com/identity/protocols/oauth2/",
|
||||
"etag": "\"u9GIe6H63LSGq-9_t39K2Zx_EAc/VCyF6WfWVwIuhIs_gw3LA4B3w1E\"",
|
||||
"icons": {
|
||||
"x16": "https://www.gstatic.com/images/branding/product/1x/googleg_16dp.png",
|
||||
"x32": "https://www.gstatic.com/images/branding/product/1x/googleg_32dp.png"
|
||||
},
|
||||
"id": "oauth2:v2",
|
||||
"kind": "discovery#restDescription",
|
||||
"methods": {
|
||||
"tokeninfo": {
|
||||
"httpMethod": "POST",
|
||||
"id": "oauth2.tokeninfo",
|
||||
"parameters": {
|
||||
"access_token": {
|
||||
"location": "query",
|
||||
"type": "string"
|
||||
},
|
||||
"id_token": {
|
||||
"location": "query",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"path": "oauth2/v2/tokeninfo",
|
||||
"response": {
|
||||
"$ref": "Tokeninfo"
|
||||
}
|
||||
}
|
||||
},
|
||||
"name": "oauth2",
|
||||
"ownerDomain": "google.com",
|
||||
"ownerName": "Google",
|
||||
"parameters": {
|
||||
"alt": {
|
||||
"default": "json",
|
||||
"description": "Data format for the response.",
|
||||
"enum": [
|
||||
"json"
|
||||
],
|
||||
"enumDescriptions": [
|
||||
"Responses with Content-Type of application/json"
|
||||
],
|
||||
"location": "query",
|
||||
"type": "string"
|
||||
},
|
||||
"fields": {
|
||||
"description": "Selector specifying which fields to include in a partial response.",
|
||||
"location": "query",
|
||||
"type": "string"
|
||||
},
|
||||
"key": {
|
||||
"description": "API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.",
|
||||
"location": "query",
|
||||
"type": "string"
|
||||
},
|
||||
"oauth_token": {
|
||||
"description": "OAuth 2.0 token for the current user.",
|
||||
"location": "query",
|
||||
"type": "string"
|
||||
},
|
||||
"prettyPrint": {
|
||||
"default": "true",
|
||||
"description": "Returns response with indentations and line breaks.",
|
||||
"location": "query",
|
||||
"type": "boolean"
|
||||
},
|
||||
"quotaUser": {
|
||||
"description": "An opaque string that represents a user for quota purposes. Must not exceed 40 characters.",
|
||||
"location": "query",
|
||||
"type": "string"
|
||||
},
|
||||
"userIp": {
|
||||
"description": "Deprecated. Please use quotaUser instead.",
|
||||
"location": "query",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"protocol": "rest",
|
||||
"resources": {
|
||||
"userinfo": {
|
||||
"methods": {
|
||||
"get": {
|
||||
"httpMethod": "GET",
|
||||
"id": "oauth2.userinfo.get",
|
||||
"path": "oauth2/v2/userinfo",
|
||||
"response": {
|
||||
"$ref": "Userinfo"
|
||||
},
|
||||
"scopes": [
|
||||
"openid",
|
||||
"https://www.googleapis.com/auth/userinfo.email",
|
||||
"https://www.googleapis.com/auth/userinfo.profile"
|
||||
]
|
||||
}
|
||||
},
|
||||
"resources": {
|
||||
"v2": {
|
||||
"resources": {
|
||||
"me": {
|
||||
"methods": {
|
||||
"get": {
|
||||
"httpMethod": "GET",
|
||||
"id": "oauth2.userinfo.v2.me.get",
|
||||
"path": "userinfo/v2/me",
|
||||
"response": {
|
||||
"$ref": "Userinfo"
|
||||
},
|
||||
"scopes": [
|
||||
"openid",
|
||||
"https://www.googleapis.com/auth/userinfo.email",
|
||||
"https://www.googleapis.com/auth/userinfo.profile"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"revision": "20200213",
|
||||
"rootUrl": "https://www.googleapis.com/",
|
||||
"schemas": {
|
||||
"Tokeninfo": {
|
||||
"id": "Tokeninfo",
|
||||
"properties": {
|
||||
"audience": {
|
||||
"description": "Who is the intended audience for this token. In general the same as issued_to.",
|
||||
"type": "string"
|
||||
},
|
||||
"email": {
|
||||
"description": "The email address of the user. Present only if the email scope is present in the request.",
|
||||
"type": "string"
|
||||
},
|
||||
"expires_in": {
|
||||
"description": "The expiry time of the token, as number of seconds left until expiry.",
|
||||
"format": "int32",
|
||||
"type": "integer"
|
||||
},
|
||||
"issued_to": {
|
||||
"description": "To whom was the token issued to. In general the same as audience.",
|
||||
"type": "string"
|
||||
},
|
||||
"scope": {
|
||||
"description": "The space separated list of scopes granted to this token.",
|
||||
"type": "string"
|
||||
},
|
||||
"user_id": {
|
||||
"description": "The obfuscated user id.",
|
||||
"type": "string"
|
||||
},
|
||||
"verified_email": {
|
||||
"description": "Boolean flag which is true if the email address is verified. Present only if the email scope is present in the request.",
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
},
|
||||
"Userinfo": {
|
||||
"id": "Userinfo",
|
||||
"properties": {
|
||||
"email": {
|
||||
"description": "The user's email address.",
|
||||
"type": "string"
|
||||
},
|
||||
"family_name": {
|
||||
"description": "The user's last name.",
|
||||
"type": "string"
|
||||
},
|
||||
"gender": {
|
||||
"description": "The user's gender.",
|
||||
"type": "string"
|
||||
},
|
||||
"given_name": {
|
||||
"description": "The user's first name.",
|
||||
"type": "string"
|
||||
},
|
||||
"hd": {
|
||||
"description": "The hosted domain e.g. example.com if the user is Google apps user.",
|
||||
"type": "string"
|
||||
},
|
||||
"id": {
|
||||
"description": "The obfuscated ID of the user.",
|
||||
"type": "string"
|
||||
},
|
||||
"link": {
|
||||
"description": "URL of the profile page.",
|
||||
"type": "string"
|
||||
},
|
||||
"locale": {
|
||||
"description": "The user's preferred locale.",
|
||||
"type": "string"
|
||||
},
|
||||
"name": {
|
||||
"description": "The user's full name.",
|
||||
"type": "string"
|
||||
},
|
||||
"picture": {
|
||||
"description": "URL of the user's picture image.",
|
||||
"type": "string"
|
||||
},
|
||||
"verified_email": {
|
||||
"default": "true",
|
||||
"description": "Boolean flag which is true if the email address is verified. Always verified because we only return the user's primary email address.",
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"servicePath": "",
|
||||
"title": "Google OAuth2 API",
|
||||
"version": "v2"
|
||||
}
|
||||
684
vendor/google.golang.org/api/oauth2/v2/oauth2-gen.go
generated
vendored
684
vendor/google.golang.org/api/oauth2/v2/oauth2-gen.go
generated
vendored
@@ -1,684 +0,0 @@
|
||||
// Copyright 2021 Google LLC.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Code generated file. DO NOT EDIT.
|
||||
|
||||
// Package oauth2 provides access to the Google OAuth2 API.
|
||||
//
|
||||
// For product documentation, see: https://developers.google.com/identity/protocols/oauth2/
|
||||
//
|
||||
// Creating a client
|
||||
//
|
||||
// Usage example:
|
||||
//
|
||||
// import "google.golang.org/api/oauth2/v2"
|
||||
// ...
|
||||
// ctx := context.Background()
|
||||
// oauth2Service, err := oauth2.NewService(ctx)
|
||||
//
|
||||
// In this example, Google Application Default Credentials are used for authentication.
|
||||
//
|
||||
// For information on how to create and obtain Application Default Credentials, see https://developers.google.com/identity/protocols/application-default-credentials.
|
||||
//
|
||||
// Other authentication options
|
||||
//
|
||||
// By default, all available scopes (see "Constants") are used to authenticate. To restrict scopes, use option.WithScopes:
|
||||
//
|
||||
// oauth2Service, err := oauth2.NewService(ctx, option.WithScopes(oauth2.OpenIDScope))
|
||||
//
|
||||
// To use an API key for authentication (note: some APIs do not support API keys), use option.WithAPIKey:
|
||||
//
|
||||
// oauth2Service, err := oauth2.NewService(ctx, option.WithAPIKey("AIza..."))
|
||||
//
|
||||
// To use an OAuth token (e.g., a user token obtained via a three-legged OAuth flow), use option.WithTokenSource:
|
||||
//
|
||||
// config := &oauth2.Config{...}
|
||||
// // ...
|
||||
// token, err := config.Exchange(ctx, ...)
|
||||
// oauth2Service, err := oauth2.NewService(ctx, option.WithTokenSource(config.TokenSource(ctx, token)))
|
||||
//
|
||||
// See https://godoc.org/google.golang.org/api/option/ for details on options.
|
||||
package oauth2 // import "google.golang.org/api/oauth2/v2"
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
googleapi "google.golang.org/api/googleapi"
|
||||
gensupport "google.golang.org/api/internal/gensupport"
|
||||
option "google.golang.org/api/option"
|
||||
internaloption "google.golang.org/api/option/internaloption"
|
||||
htransport "google.golang.org/api/transport/http"
|
||||
)
|
||||
|
||||
// Always reference these packages, just in case the auto-generated code
|
||||
// below doesn't.
|
||||
var _ = bytes.NewBuffer
|
||||
var _ = strconv.Itoa
|
||||
var _ = fmt.Sprintf
|
||||
var _ = json.NewDecoder
|
||||
var _ = io.Copy
|
||||
var _ = url.Parse
|
||||
var _ = gensupport.MarshalJSON
|
||||
var _ = googleapi.Version
|
||||
var _ = errors.New
|
||||
var _ = strings.Replace
|
||||
var _ = context.Canceled
|
||||
var _ = internaloption.WithDefaultEndpoint
|
||||
|
||||
const apiId = "oauth2:v2"
|
||||
const apiName = "oauth2"
|
||||
const apiVersion = "v2"
|
||||
const basePath = "https://www.googleapis.com/"
|
||||
|
||||
// OAuth2 scopes used by this API.
|
||||
const (
|
||||
// View your email address
|
||||
UserinfoEmailScope = "https://www.googleapis.com/auth/userinfo.email"
|
||||
|
||||
// See your personal info, including any personal info you've made
|
||||
// publicly available
|
||||
UserinfoProfileScope = "https://www.googleapis.com/auth/userinfo.profile"
|
||||
|
||||
// Associate you with your personal info on Google
|
||||
OpenIDScope = "openid"
|
||||
)
|
||||
|
||||
// NewService creates a new Service.
|
||||
func NewService(ctx context.Context, opts ...option.ClientOption) (*Service, error) {
|
||||
scopesOption := option.WithScopes(
|
||||
"https://www.googleapis.com/auth/userinfo.email",
|
||||
"https://www.googleapis.com/auth/userinfo.profile",
|
||||
"openid",
|
||||
)
|
||||
// NOTE: prepend, so we don't override user-specified scopes.
|
||||
opts = append([]option.ClientOption{scopesOption}, opts...)
|
||||
opts = append(opts, internaloption.WithDefaultEndpoint(basePath))
|
||||
client, endpoint, err := htransport.NewClient(ctx, opts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s, err := New(client)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if endpoint != "" {
|
||||
s.BasePath = endpoint
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// New creates a new Service. It uses the provided http.Client for requests.
|
||||
//
|
||||
// Deprecated: please use NewService instead.
|
||||
// To provide a custom HTTP client, use option.WithHTTPClient.
|
||||
// If you are using google.golang.org/api/googleapis/transport.APIKey, use option.WithAPIKey with NewService instead.
|
||||
func New(client *http.Client) (*Service, error) {
|
||||
if client == nil {
|
||||
return nil, errors.New("client is nil")
|
||||
}
|
||||
s := &Service{client: client, BasePath: basePath}
|
||||
s.Userinfo = NewUserinfoService(s)
|
||||
return s, nil
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
client *http.Client
|
||||
BasePath string // API endpoint base URL
|
||||
UserAgent string // optional additional User-Agent fragment
|
||||
|
||||
Userinfo *UserinfoService
|
||||
}
|
||||
|
||||
func (s *Service) userAgent() string {
|
||||
if s.UserAgent == "" {
|
||||
return googleapi.UserAgent
|
||||
}
|
||||
return googleapi.UserAgent + " " + s.UserAgent
|
||||
}
|
||||
|
||||
func NewUserinfoService(s *Service) *UserinfoService {
|
||||
rs := &UserinfoService{s: s}
|
||||
rs.V2 = NewUserinfoV2Service(s)
|
||||
return rs
|
||||
}
|
||||
|
||||
type UserinfoService struct {
|
||||
s *Service
|
||||
|
||||
V2 *UserinfoV2Service
|
||||
}
|
||||
|
||||
func NewUserinfoV2Service(s *Service) *UserinfoV2Service {
|
||||
rs := &UserinfoV2Service{s: s}
|
||||
rs.Me = NewUserinfoV2MeService(s)
|
||||
return rs
|
||||
}
|
||||
|
||||
type UserinfoV2Service struct {
|
||||
s *Service
|
||||
|
||||
Me *UserinfoV2MeService
|
||||
}
|
||||
|
||||
func NewUserinfoV2MeService(s *Service) *UserinfoV2MeService {
|
||||
rs := &UserinfoV2MeService{s: s}
|
||||
return rs
|
||||
}
|
||||
|
||||
type UserinfoV2MeService struct {
|
||||
s *Service
|
||||
}
|
||||
|
||||
type Tokeninfo struct {
|
||||
// Audience: Who is the intended audience for this token. In general the
|
||||
// same as issued_to.
|
||||
Audience string `json:"audience,omitempty"`
|
||||
|
||||
// Email: The email address of the user. Present only if the email scope
|
||||
// is present in the request.
|
||||
Email string `json:"email,omitempty"`
|
||||
|
||||
// ExpiresIn: The expiry time of the token, as number of seconds left
|
||||
// until expiry.
|
||||
ExpiresIn int64 `json:"expires_in,omitempty"`
|
||||
|
||||
// IssuedTo: To whom was the token issued to. In general the same as
|
||||
// audience.
|
||||
IssuedTo string `json:"issued_to,omitempty"`
|
||||
|
||||
// Scope: The space separated list of scopes granted to this token.
|
||||
Scope string `json:"scope,omitempty"`
|
||||
|
||||
// UserId: The obfuscated user id.
|
||||
UserId string `json:"user_id,omitempty"`
|
||||
|
||||
// VerifiedEmail: Boolean flag which is true if the email address is
|
||||
// verified. Present only if the email scope is present in the request.
|
||||
VerifiedEmail bool `json:"verified_email,omitempty"`
|
||||
|
||||
// ServerResponse contains the HTTP response code and headers from the
|
||||
// server.
|
||||
googleapi.ServerResponse `json:"-"`
|
||||
|
||||
// ForceSendFields is a list of field names (e.g. "Audience") to
|
||||
// unconditionally include in API requests. By default, fields with
|
||||
// empty or default values are omitted from API requests. However, any
|
||||
// non-pointer, non-interface field appearing in ForceSendFields will be
|
||||
// sent to the server regardless of whether the field is empty or not.
|
||||
// This may be used to include empty fields in Patch requests.
|
||||
ForceSendFields []string `json:"-"`
|
||||
|
||||
// NullFields is a list of field names (e.g. "Audience") to include in
|
||||
// API requests with the JSON null value. By default, fields with empty
|
||||
// values are omitted from API requests. However, any field with an
|
||||
// empty value appearing in NullFields will be sent to the server as
|
||||
// null. It is an error if a field in this list has a non-empty value.
|
||||
// This may be used to include null fields in Patch requests.
|
||||
NullFields []string `json:"-"`
|
||||
}
|
||||
|
||||
func (s *Tokeninfo) MarshalJSON() ([]byte, error) {
|
||||
type NoMethod Tokeninfo
|
||||
raw := NoMethod(*s)
|
||||
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
|
||||
}
|
||||
|
||||
type Userinfo struct {
|
||||
// Email: The user's email address.
|
||||
Email string `json:"email,omitempty"`
|
||||
|
||||
// FamilyName: The user's last name.
|
||||
FamilyName string `json:"family_name,omitempty"`
|
||||
|
||||
// Gender: The user's gender.
|
||||
Gender string `json:"gender,omitempty"`
|
||||
|
||||
// GivenName: The user's first name.
|
||||
GivenName string `json:"given_name,omitempty"`
|
||||
|
||||
// Hd: The hosted domain e.g. example.com if the user is Google apps
|
||||
// user.
|
||||
Hd string `json:"hd,omitempty"`
|
||||
|
||||
// Id: The obfuscated ID of the user.
|
||||
Id string `json:"id,omitempty"`
|
||||
|
||||
// Link: URL of the profile page.
|
||||
Link string `json:"link,omitempty"`
|
||||
|
||||
// Locale: The user's preferred locale.
|
||||
Locale string `json:"locale,omitempty"`
|
||||
|
||||
// Name: The user's full name.
|
||||
Name string `json:"name,omitempty"`
|
||||
|
||||
// Picture: URL of the user's picture image.
|
||||
Picture string `json:"picture,omitempty"`
|
||||
|
||||
// VerifiedEmail: Boolean flag which is true if the email address is
|
||||
// verified. Always verified because we only return the user's primary
|
||||
// email address.
|
||||
//
|
||||
// Default: true
|
||||
VerifiedEmail *bool `json:"verified_email,omitempty"`
|
||||
|
||||
// ServerResponse contains the HTTP response code and headers from the
|
||||
// server.
|
||||
googleapi.ServerResponse `json:"-"`
|
||||
|
||||
// ForceSendFields is a list of field names (e.g. "Email") to
|
||||
// unconditionally include in API requests. By default, fields with
|
||||
// empty or default values are omitted from API requests. However, any
|
||||
// non-pointer, non-interface field appearing in ForceSendFields will be
|
||||
// sent to the server regardless of whether the field is empty or not.
|
||||
// This may be used to include empty fields in Patch requests.
|
||||
ForceSendFields []string `json:"-"`
|
||||
|
||||
// NullFields is a list of field names (e.g. "Email") to include in API
|
||||
// requests with the JSON null value. By default, fields with empty
|
||||
// values are omitted from API requests. However, any field with an
|
||||
// empty value appearing in NullFields will be sent to the server as
|
||||
// null. It is an error if a field in this list has a non-empty value.
|
||||
// This may be used to include null fields in Patch requests.
|
||||
NullFields []string `json:"-"`
|
||||
}
|
||||
|
||||
func (s *Userinfo) MarshalJSON() ([]byte, error) {
|
||||
type NoMethod Userinfo
|
||||
raw := NoMethod(*s)
|
||||
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
|
||||
}
|
||||
|
||||
// method id "oauth2.tokeninfo":
|
||||
|
||||
type TokeninfoCall struct {
|
||||
s *Service
|
||||
urlParams_ gensupport.URLParams
|
||||
ctx_ context.Context
|
||||
header_ http.Header
|
||||
}
|
||||
|
||||
// Tokeninfo:
|
||||
func (s *Service) Tokeninfo() *TokeninfoCall {
|
||||
c := &TokeninfoCall{s: s, urlParams_: make(gensupport.URLParams)}
|
||||
return c
|
||||
}
|
||||
|
||||
// AccessToken sets the optional parameter "access_token":
|
||||
func (c *TokeninfoCall) AccessToken(accessToken string) *TokeninfoCall {
|
||||
c.urlParams_.Set("access_token", accessToken)
|
||||
return c
|
||||
}
|
||||
|
||||
// IdToken sets the optional parameter "id_token":
|
||||
func (c *TokeninfoCall) IdToken(idToken string) *TokeninfoCall {
|
||||
c.urlParams_.Set("id_token", idToken)
|
||||
return c
|
||||
}
|
||||
|
||||
// Fields allows partial responses to be retrieved. See
|
||||
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
|
||||
// for more information.
|
||||
func (c *TokeninfoCall) Fields(s ...googleapi.Field) *TokeninfoCall {
|
||||
c.urlParams_.Set("fields", googleapi.CombineFields(s))
|
||||
return c
|
||||
}
|
||||
|
||||
// Context sets the context to be used in this call's Do method. Any
|
||||
// pending HTTP request will be aborted if the provided context is
|
||||
// canceled.
|
||||
func (c *TokeninfoCall) Context(ctx context.Context) *TokeninfoCall {
|
||||
c.ctx_ = ctx
|
||||
return c
|
||||
}
|
||||
|
||||
// Header returns an http.Header that can be modified by the caller to
|
||||
// add HTTP headers to the request.
|
||||
func (c *TokeninfoCall) Header() http.Header {
|
||||
if c.header_ == nil {
|
||||
c.header_ = make(http.Header)
|
||||
}
|
||||
return c.header_
|
||||
}
|
||||
|
||||
func (c *TokeninfoCall) doRequest(alt string) (*http.Response, error) {
|
||||
reqHeaders := make(http.Header)
|
||||
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20210930")
|
||||
for k, v := range c.header_ {
|
||||
reqHeaders[k] = v
|
||||
}
|
||||
reqHeaders.Set("User-Agent", c.s.userAgent())
|
||||
var body io.Reader = nil
|
||||
c.urlParams_.Set("alt", alt)
|
||||
c.urlParams_.Set("prettyPrint", "false")
|
||||
urls := googleapi.ResolveRelative(c.s.BasePath, "oauth2/v2/tokeninfo")
|
||||
urls += "?" + c.urlParams_.Encode()
|
||||
req, err := http.NewRequest("POST", urls, body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header = reqHeaders
|
||||
return gensupport.SendRequest(c.ctx_, c.s.client, req)
|
||||
}
|
||||
|
||||
// Do executes the "oauth2.tokeninfo" call.
|
||||
// Exactly one of *Tokeninfo or error will be non-nil. Any non-2xx
|
||||
// status code is an error. Response headers are in either
|
||||
// *Tokeninfo.ServerResponse.Header or (if a response was returned at
|
||||
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
|
||||
// to check whether the returned error was because
|
||||
// http.StatusNotModified was returned.
|
||||
func (c *TokeninfoCall) Do(opts ...googleapi.CallOption) (*Tokeninfo, error) {
|
||||
gensupport.SetOptions(c.urlParams_, opts...)
|
||||
res, err := c.doRequest("json")
|
||||
if res != nil && res.StatusCode == http.StatusNotModified {
|
||||
if res.Body != nil {
|
||||
res.Body.Close()
|
||||
}
|
||||
return nil, &googleapi.Error{
|
||||
Code: res.StatusCode,
|
||||
Header: res.Header,
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer googleapi.CloseBody(res)
|
||||
if err := googleapi.CheckResponse(res); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ret := &Tokeninfo{
|
||||
ServerResponse: googleapi.ServerResponse{
|
||||
Header: res.Header,
|
||||
HTTPStatusCode: res.StatusCode,
|
||||
},
|
||||
}
|
||||
target := &ret
|
||||
if err := gensupport.DecodeResponse(target, res); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ret, nil
|
||||
// {
|
||||
// "httpMethod": "POST",
|
||||
// "id": "oauth2.tokeninfo",
|
||||
// "parameters": {
|
||||
// "access_token": {
|
||||
// "location": "query",
|
||||
// "type": "string"
|
||||
// },
|
||||
// "id_token": {
|
||||
// "location": "query",
|
||||
// "type": "string"
|
||||
// }
|
||||
// },
|
||||
// "path": "oauth2/v2/tokeninfo",
|
||||
// "response": {
|
||||
// "$ref": "Tokeninfo"
|
||||
// }
|
||||
// }
|
||||
|
||||
}
|
||||
|
||||
// method id "oauth2.userinfo.get":
|
||||
|
||||
type UserinfoGetCall struct {
|
||||
s *Service
|
||||
urlParams_ gensupport.URLParams
|
||||
ifNoneMatch_ string
|
||||
ctx_ context.Context
|
||||
header_ http.Header
|
||||
}
|
||||
|
||||
// Get:
|
||||
func (r *UserinfoService) Get() *UserinfoGetCall {
|
||||
c := &UserinfoGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}
|
||||
return c
|
||||
}
|
||||
|
||||
// Fields allows partial responses to be retrieved. See
|
||||
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
|
||||
// for more information.
|
||||
func (c *UserinfoGetCall) Fields(s ...googleapi.Field) *UserinfoGetCall {
|
||||
c.urlParams_.Set("fields", googleapi.CombineFields(s))
|
||||
return c
|
||||
}
|
||||
|
||||
// IfNoneMatch sets the optional parameter which makes the operation
|
||||
// fail if the object's ETag matches the given value. This is useful for
|
||||
// getting updates only after the object has changed since the last
|
||||
// request. Use googleapi.IsNotModified to check whether the response
|
||||
// error from Do is the result of In-None-Match.
|
||||
func (c *UserinfoGetCall) IfNoneMatch(entityTag string) *UserinfoGetCall {
|
||||
c.ifNoneMatch_ = entityTag
|
||||
return c
|
||||
}
|
||||
|
||||
// Context sets the context to be used in this call's Do method. Any
|
||||
// pending HTTP request will be aborted if the provided context is
|
||||
// canceled.
|
||||
func (c *UserinfoGetCall) Context(ctx context.Context) *UserinfoGetCall {
|
||||
c.ctx_ = ctx
|
||||
return c
|
||||
}
|
||||
|
||||
// Header returns an http.Header that can be modified by the caller to
|
||||
// add HTTP headers to the request.
|
||||
func (c *UserinfoGetCall) Header() http.Header {
|
||||
if c.header_ == nil {
|
||||
c.header_ = make(http.Header)
|
||||
}
|
||||
return c.header_
|
||||
}
|
||||
|
||||
func (c *UserinfoGetCall) doRequest(alt string) (*http.Response, error) {
|
||||
reqHeaders := make(http.Header)
|
||||
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20210930")
|
||||
for k, v := range c.header_ {
|
||||
reqHeaders[k] = v
|
||||
}
|
||||
reqHeaders.Set("User-Agent", c.s.userAgent())
|
||||
if c.ifNoneMatch_ != "" {
|
||||
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
|
||||
}
|
||||
var body io.Reader = nil
|
||||
c.urlParams_.Set("alt", alt)
|
||||
c.urlParams_.Set("prettyPrint", "false")
|
||||
urls := googleapi.ResolveRelative(c.s.BasePath, "oauth2/v2/userinfo")
|
||||
urls += "?" + c.urlParams_.Encode()
|
||||
req, err := http.NewRequest("GET", urls, body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header = reqHeaders
|
||||
return gensupport.SendRequest(c.ctx_, c.s.client, req)
|
||||
}
|
||||
|
||||
// Do executes the "oauth2.userinfo.get" call.
|
||||
// Exactly one of *Userinfo or error will be non-nil. Any non-2xx status
|
||||
// code is an error. Response headers are in either
|
||||
// *Userinfo.ServerResponse.Header or (if a response was returned at
|
||||
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
|
||||
// to check whether the returned error was because
|
||||
// http.StatusNotModified was returned.
|
||||
func (c *UserinfoGetCall) Do(opts ...googleapi.CallOption) (*Userinfo, error) {
|
||||
gensupport.SetOptions(c.urlParams_, opts...)
|
||||
res, err := c.doRequest("json")
|
||||
if res != nil && res.StatusCode == http.StatusNotModified {
|
||||
if res.Body != nil {
|
||||
res.Body.Close()
|
||||
}
|
||||
return nil, &googleapi.Error{
|
||||
Code: res.StatusCode,
|
||||
Header: res.Header,
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer googleapi.CloseBody(res)
|
||||
if err := googleapi.CheckResponse(res); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ret := &Userinfo{
|
||||
ServerResponse: googleapi.ServerResponse{
|
||||
Header: res.Header,
|
||||
HTTPStatusCode: res.StatusCode,
|
||||
},
|
||||
}
|
||||
target := &ret
|
||||
if err := gensupport.DecodeResponse(target, res); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ret, nil
|
||||
// {
|
||||
// "httpMethod": "GET",
|
||||
// "id": "oauth2.userinfo.get",
|
||||
// "path": "oauth2/v2/userinfo",
|
||||
// "response": {
|
||||
// "$ref": "Userinfo"
|
||||
// },
|
||||
// "scopes": [
|
||||
// "openid",
|
||||
// "https://www.googleapis.com/auth/userinfo.email",
|
||||
// "https://www.googleapis.com/auth/userinfo.profile"
|
||||
// ]
|
||||
// }
|
||||
|
||||
}
|
||||
|
||||
// method id "oauth2.userinfo.v2.me.get":
|
||||
|
||||
type UserinfoV2MeGetCall struct {
|
||||
s *Service
|
||||
urlParams_ gensupport.URLParams
|
||||
ifNoneMatch_ string
|
||||
ctx_ context.Context
|
||||
header_ http.Header
|
||||
}
|
||||
|
||||
// Get:
|
||||
func (r *UserinfoV2MeService) Get() *UserinfoV2MeGetCall {
|
||||
c := &UserinfoV2MeGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}
|
||||
return c
|
||||
}
|
||||
|
||||
// Fields allows partial responses to be retrieved. See
|
||||
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
|
||||
// for more information.
|
||||
func (c *UserinfoV2MeGetCall) Fields(s ...googleapi.Field) *UserinfoV2MeGetCall {
|
||||
c.urlParams_.Set("fields", googleapi.CombineFields(s))
|
||||
return c
|
||||
}
|
||||
|
||||
// IfNoneMatch sets the optional parameter which makes the operation
|
||||
// fail if the object's ETag matches the given value. This is useful for
|
||||
// getting updates only after the object has changed since the last
|
||||
// request. Use googleapi.IsNotModified to check whether the response
|
||||
// error from Do is the result of In-None-Match.
|
||||
func (c *UserinfoV2MeGetCall) IfNoneMatch(entityTag string) *UserinfoV2MeGetCall {
|
||||
c.ifNoneMatch_ = entityTag
|
||||
return c
|
||||
}
|
||||
|
||||
// Context sets the context to be used in this call's Do method. Any
|
||||
// pending HTTP request will be aborted if the provided context is
|
||||
// canceled.
|
||||
func (c *UserinfoV2MeGetCall) Context(ctx context.Context) *UserinfoV2MeGetCall {
|
||||
c.ctx_ = ctx
|
||||
return c
|
||||
}
|
||||
|
||||
// Header returns an http.Header that can be modified by the caller to
|
||||
// add HTTP headers to the request.
|
||||
func (c *UserinfoV2MeGetCall) Header() http.Header {
|
||||
if c.header_ == nil {
|
||||
c.header_ = make(http.Header)
|
||||
}
|
||||
return c.header_
|
||||
}
|
||||
|
||||
func (c *UserinfoV2MeGetCall) doRequest(alt string) (*http.Response, error) {
|
||||
reqHeaders := make(http.Header)
|
||||
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20210930")
|
||||
for k, v := range c.header_ {
|
||||
reqHeaders[k] = v
|
||||
}
|
||||
reqHeaders.Set("User-Agent", c.s.userAgent())
|
||||
if c.ifNoneMatch_ != "" {
|
||||
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
|
||||
}
|
||||
var body io.Reader = nil
|
||||
c.urlParams_.Set("alt", alt)
|
||||
c.urlParams_.Set("prettyPrint", "false")
|
||||
urls := googleapi.ResolveRelative(c.s.BasePath, "userinfo/v2/me")
|
||||
urls += "?" + c.urlParams_.Encode()
|
||||
req, err := http.NewRequest("GET", urls, body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header = reqHeaders
|
||||
return gensupport.SendRequest(c.ctx_, c.s.client, req)
|
||||
}
|
||||
|
||||
// Do executes the "oauth2.userinfo.v2.me.get" call.
|
||||
// Exactly one of *Userinfo or error will be non-nil. Any non-2xx status
|
||||
// code is an error. Response headers are in either
|
||||
// *Userinfo.ServerResponse.Header or (if a response was returned at
|
||||
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
|
||||
// to check whether the returned error was because
|
||||
// http.StatusNotModified was returned.
|
||||
func (c *UserinfoV2MeGetCall) Do(opts ...googleapi.CallOption) (*Userinfo, error) {
|
||||
gensupport.SetOptions(c.urlParams_, opts...)
|
||||
res, err := c.doRequest("json")
|
||||
if res != nil && res.StatusCode == http.StatusNotModified {
|
||||
if res.Body != nil {
|
||||
res.Body.Close()
|
||||
}
|
||||
return nil, &googleapi.Error{
|
||||
Code: res.StatusCode,
|
||||
Header: res.Header,
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer googleapi.CloseBody(res)
|
||||
if err := googleapi.CheckResponse(res); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ret := &Userinfo{
|
||||
ServerResponse: googleapi.ServerResponse{
|
||||
Header: res.Header,
|
||||
HTTPStatusCode: res.StatusCode,
|
||||
},
|
||||
}
|
||||
target := &ret
|
||||
if err := gensupport.DecodeResponse(target, res); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ret, nil
|
||||
// {
|
||||
// "httpMethod": "GET",
|
||||
// "id": "oauth2.userinfo.v2.me.get",
|
||||
// "path": "userinfo/v2/me",
|
||||
// "response": {
|
||||
// "$ref": "Userinfo"
|
||||
// },
|
||||
// "scopes": [
|
||||
// "openid",
|
||||
// "https://www.googleapis.com/auth/userinfo.email",
|
||||
// "https://www.googleapis.com/auth/userinfo.profile"
|
||||
// ]
|
||||
// }
|
||||
|
||||
}
|
||||
24
vendor/google.golang.org/api/option/credentials_go19.go
generated
vendored
24
vendor/google.golang.org/api/option/credentials_go19.go
generated
vendored
@@ -1,24 +0,0 @@
|
||||
// Copyright 2018 Google LLC.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
//go:build go1.9
|
||||
// +build go1.9
|
||||
|
||||
package option
|
||||
|
||||
import (
|
||||
"golang.org/x/oauth2/google"
|
||||
"google.golang.org/api/internal"
|
||||
)
|
||||
|
||||
type withCreds google.Credentials
|
||||
|
||||
func (w *withCreds) Apply(o *internal.DialSettings) {
|
||||
o.Credentials = (*google.Credentials)(w)
|
||||
}
|
||||
|
||||
// WithCredentials returns a ClientOption that authenticates API calls.
|
||||
func WithCredentials(creds *google.Credentials) ClientOption {
|
||||
return (*withCreds)(creds)
|
||||
}
|
||||
23
vendor/google.golang.org/api/option/credentials_notgo19.go
generated
vendored
23
vendor/google.golang.org/api/option/credentials_notgo19.go
generated
vendored
@@ -1,23 +0,0 @@
|
||||
// Copyright 2018 Google LLC.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
//go:build !go1.9
|
||||
// +build !go1.9
|
||||
|
||||
package option
|
||||
|
||||
import (
|
||||
"golang.org/x/oauth2/google"
|
||||
"google.golang.org/api/internal"
|
||||
)
|
||||
|
||||
type withCreds google.DefaultCredentials
|
||||
|
||||
func (w *withCreds) Apply(o *internal.DialSettings) {
|
||||
o.Credentials = (*google.DefaultCredentials)(w)
|
||||
}
|
||||
|
||||
func WithCredentials(creds *google.DefaultCredentials) ClientOption {
|
||||
return (*withCreds)(creds)
|
||||
}
|
||||
136
vendor/google.golang.org/api/option/internaloption/internaloption.go
generated
vendored
136
vendor/google.golang.org/api/option/internaloption/internaloption.go
generated
vendored
@@ -1,136 +0,0 @@
|
||||
// Copyright 2020 Google LLC.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package internaloption contains options used internally by Google client code.
|
||||
package internaloption
|
||||
|
||||
import (
|
||||
"golang.org/x/oauth2/google"
|
||||
"google.golang.org/api/internal"
|
||||
"google.golang.org/api/option"
|
||||
)
|
||||
|
||||
type defaultEndpointOption string
|
||||
|
||||
func (o defaultEndpointOption) Apply(settings *internal.DialSettings) {
|
||||
settings.DefaultEndpoint = string(o)
|
||||
}
|
||||
|
||||
// WithDefaultEndpoint is an option that indicates the default endpoint.
|
||||
//
|
||||
// It should only be used internally by generated clients.
|
||||
//
|
||||
// This is similar to WithEndpoint, but allows us to determine whether the user has overridden the default endpoint.
|
||||
func WithDefaultEndpoint(url string) option.ClientOption {
|
||||
return defaultEndpointOption(url)
|
||||
}
|
||||
|
||||
type defaultMTLSEndpointOption string
|
||||
|
||||
func (o defaultMTLSEndpointOption) Apply(settings *internal.DialSettings) {
|
||||
settings.DefaultMTLSEndpoint = string(o)
|
||||
}
|
||||
|
||||
// WithDefaultMTLSEndpoint is an option that indicates the default mTLS endpoint.
|
||||
//
|
||||
// It should only be used internally by generated clients.
|
||||
func WithDefaultMTLSEndpoint(url string) option.ClientOption {
|
||||
return defaultMTLSEndpointOption(url)
|
||||
}
|
||||
|
||||
// SkipDialSettingsValidation bypasses validation on ClientOptions.
|
||||
//
|
||||
// It should only be used internally.
|
||||
func SkipDialSettingsValidation() option.ClientOption {
|
||||
return skipDialSettingsValidation{}
|
||||
}
|
||||
|
||||
type skipDialSettingsValidation struct{}
|
||||
|
||||
func (s skipDialSettingsValidation) Apply(settings *internal.DialSettings) {
|
||||
settings.SkipValidation = true
|
||||
}
|
||||
|
||||
// EnableDirectPath returns a ClientOption that overrides the default
|
||||
// attempt to use DirectPath.
|
||||
//
|
||||
// It should only be used internally by generated clients.
|
||||
// This is an EXPERIMENTAL API and may be changed or removed in the future.
|
||||
func EnableDirectPath(dp bool) option.ClientOption {
|
||||
return enableDirectPath(dp)
|
||||
}
|
||||
|
||||
type enableDirectPath bool
|
||||
|
||||
func (e enableDirectPath) Apply(o *internal.DialSettings) {
|
||||
o.EnableDirectPath = bool(e)
|
||||
}
|
||||
|
||||
// AllowNonDefaultServiceAccount returns a ClientOption that overrides the default
|
||||
// requirement for using the default service account for DirectPath.
|
||||
//
|
||||
// It should only be used internally by generated clients.
|
||||
// This is an EXPERIMENTAL API and may be changed or removed in the future.
|
||||
func AllowNonDefaultServiceAccount(nd bool) option.ClientOption {
|
||||
return allowNonDefaultServiceAccount(nd)
|
||||
}
|
||||
|
||||
type allowNonDefaultServiceAccount bool
|
||||
|
||||
func (a allowNonDefaultServiceAccount) Apply(o *internal.DialSettings) {
|
||||
o.AllowNonDefaultServiceAccount = bool(a)
|
||||
}
|
||||
|
||||
// WithDefaultAudience returns a ClientOption that specifies a default audience
|
||||
// to be used as the audience field ("aud") for the JWT token authentication.
|
||||
//
|
||||
// It should only be used internally by generated clients.
|
||||
func WithDefaultAudience(audience string) option.ClientOption {
|
||||
return withDefaultAudience(audience)
|
||||
}
|
||||
|
||||
type withDefaultAudience string
|
||||
|
||||
func (w withDefaultAudience) Apply(o *internal.DialSettings) {
|
||||
o.DefaultAudience = string(w)
|
||||
}
|
||||
|
||||
// WithDefaultScopes returns a ClientOption that overrides the default OAuth2
|
||||
// scopes to be used for a service.
|
||||
//
|
||||
// It should only be used internally by generated clients.
|
||||
func WithDefaultScopes(scope ...string) option.ClientOption {
|
||||
return withDefaultScopes(scope)
|
||||
}
|
||||
|
||||
type withDefaultScopes []string
|
||||
|
||||
func (w withDefaultScopes) Apply(o *internal.DialSettings) {
|
||||
o.DefaultScopes = make([]string, len(w))
|
||||
copy(o.DefaultScopes, w)
|
||||
}
|
||||
|
||||
// EnableJwtWithScope returns a ClientOption that specifies if scope can be used
|
||||
// with self-signed JWT.
|
||||
func EnableJwtWithScope() option.ClientOption {
|
||||
return enableJwtWithScope(true)
|
||||
}
|
||||
|
||||
type enableJwtWithScope bool
|
||||
|
||||
func (w enableJwtWithScope) Apply(o *internal.DialSettings) {
|
||||
o.EnableJwtWithScope = bool(w)
|
||||
}
|
||||
|
||||
// WithCredentials returns a client option to specify credentials which will be used to authenticate API calls.
|
||||
// This credential takes precedence over all other credential options.
|
||||
func WithCredentials(creds *google.Credentials) option.ClientOption {
|
||||
return (*withCreds)(creds)
|
||||
}
|
||||
|
||||
type withCreds google.Credentials
|
||||
|
||||
func (w *withCreds) Apply(o *internal.DialSettings) {
|
||||
o.InternalCredentials = (*google.Credentials)(w)
|
||||
}
|
||||
330
vendor/google.golang.org/api/option/option.go
generated
vendored
330
vendor/google.golang.org/api/option/option.go
generated
vendored
@@ -1,330 +0,0 @@
|
||||
// Copyright 2017 Google LLC.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package option contains options for Google API clients.
|
||||
package option
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"net/http"
|
||||
|
||||
"golang.org/x/oauth2"
|
||||
"google.golang.org/api/internal"
|
||||
"google.golang.org/api/internal/impersonate"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
// A ClientOption is an option for a Google API client.
|
||||
type ClientOption interface {
|
||||
Apply(*internal.DialSettings)
|
||||
}
|
||||
|
||||
// WithTokenSource returns a ClientOption that specifies an OAuth2 token
|
||||
// source to be used as the basis for authentication.
|
||||
func WithTokenSource(s oauth2.TokenSource) ClientOption {
|
||||
return withTokenSource{s}
|
||||
}
|
||||
|
||||
type withTokenSource struct{ ts oauth2.TokenSource }
|
||||
|
||||
func (w withTokenSource) Apply(o *internal.DialSettings) {
|
||||
o.TokenSource = w.ts
|
||||
}
|
||||
|
||||
type withCredFile string
|
||||
|
||||
func (w withCredFile) Apply(o *internal.DialSettings) {
|
||||
o.CredentialsFile = string(w)
|
||||
}
|
||||
|
||||
// WithCredentialsFile returns a ClientOption that authenticates
|
||||
// API calls with the given service account or refresh token JSON
|
||||
// credentials file.
|
||||
func WithCredentialsFile(filename string) ClientOption {
|
||||
return withCredFile(filename)
|
||||
}
|
||||
|
||||
// WithServiceAccountFile returns a ClientOption that uses a Google service
|
||||
// account credentials file to authenticate.
|
||||
//
|
||||
// Deprecated: Use WithCredentialsFile instead.
|
||||
func WithServiceAccountFile(filename string) ClientOption {
|
||||
return WithCredentialsFile(filename)
|
||||
}
|
||||
|
||||
// WithCredentialsJSON returns a ClientOption that authenticates
|
||||
// API calls with the given service account or refresh token JSON
|
||||
// credentials.
|
||||
func WithCredentialsJSON(p []byte) ClientOption {
|
||||
return withCredentialsJSON(p)
|
||||
}
|
||||
|
||||
type withCredentialsJSON []byte
|
||||
|
||||
func (w withCredentialsJSON) Apply(o *internal.DialSettings) {
|
||||
o.CredentialsJSON = make([]byte, len(w))
|
||||
copy(o.CredentialsJSON, w)
|
||||
}
|
||||
|
||||
// WithEndpoint returns a ClientOption that overrides the default endpoint
|
||||
// to be used for a service.
|
||||
func WithEndpoint(url string) ClientOption {
|
||||
return withEndpoint(url)
|
||||
}
|
||||
|
||||
type withEndpoint string
|
||||
|
||||
func (w withEndpoint) Apply(o *internal.DialSettings) {
|
||||
o.Endpoint = string(w)
|
||||
}
|
||||
|
||||
// WithScopes returns a ClientOption that overrides the default OAuth2 scopes
|
||||
// to be used for a service.
|
||||
func WithScopes(scope ...string) ClientOption {
|
||||
return withScopes(scope)
|
||||
}
|
||||
|
||||
type withScopes []string
|
||||
|
||||
func (w withScopes) Apply(o *internal.DialSettings) {
|
||||
o.Scopes = make([]string, len(w))
|
||||
copy(o.Scopes, w)
|
||||
}
|
||||
|
||||
// WithUserAgent returns a ClientOption that sets the User-Agent.
|
||||
func WithUserAgent(ua string) ClientOption {
|
||||
return withUA(ua)
|
||||
}
|
||||
|
||||
type withUA string
|
||||
|
||||
func (w withUA) Apply(o *internal.DialSettings) { o.UserAgent = string(w) }
|
||||
|
||||
// WithHTTPClient returns a ClientOption that specifies the HTTP client to use
|
||||
// as the basis of communications. This option may only be used with services
|
||||
// that support HTTP as their communication transport. When used, the
|
||||
// WithHTTPClient option takes precedent over all other supplied options.
|
||||
func WithHTTPClient(client *http.Client) ClientOption {
|
||||
return withHTTPClient{client}
|
||||
}
|
||||
|
||||
type withHTTPClient struct{ client *http.Client }
|
||||
|
||||
func (w withHTTPClient) Apply(o *internal.DialSettings) {
|
||||
o.HTTPClient = w.client
|
||||
}
|
||||
|
||||
// WithGRPCConn returns a ClientOption that specifies the gRPC client
|
||||
// connection to use as the basis of communications. This option may only be
|
||||
// used with services that support gRPC as their communication transport. When
|
||||
// used, the WithGRPCConn option takes precedent over all other supplied
|
||||
// options.
|
||||
func WithGRPCConn(conn *grpc.ClientConn) ClientOption {
|
||||
return withGRPCConn{conn}
|
||||
}
|
||||
|
||||
type withGRPCConn struct{ conn *grpc.ClientConn }
|
||||
|
||||
func (w withGRPCConn) Apply(o *internal.DialSettings) {
|
||||
o.GRPCConn = w.conn
|
||||
}
|
||||
|
||||
// WithGRPCDialOption returns a ClientOption that appends a new grpc.DialOption
|
||||
// to an underlying gRPC dial. It does not work with WithGRPCConn.
|
||||
func WithGRPCDialOption(opt grpc.DialOption) ClientOption {
|
||||
return withGRPCDialOption{opt}
|
||||
}
|
||||
|
||||
type withGRPCDialOption struct{ opt grpc.DialOption }
|
||||
|
||||
func (w withGRPCDialOption) Apply(o *internal.DialSettings) {
|
||||
o.GRPCDialOpts = append(o.GRPCDialOpts, w.opt)
|
||||
}
|
||||
|
||||
// WithGRPCConnectionPool returns a ClientOption that creates a pool of gRPC
|
||||
// connections that requests will be balanced between.
|
||||
//
|
||||
// This is an EXPERIMENTAL API and may be changed or removed in the future.
|
||||
func WithGRPCConnectionPool(size int) ClientOption {
|
||||
return withGRPCConnectionPool(size)
|
||||
}
|
||||
|
||||
type withGRPCConnectionPool int
|
||||
|
||||
func (w withGRPCConnectionPool) Apply(o *internal.DialSettings) {
|
||||
o.GRPCConnPoolSize = int(w)
|
||||
}
|
||||
|
||||
// WithAPIKey returns a ClientOption that specifies an API key to be used
|
||||
// as the basis for authentication.
|
||||
//
|
||||
// API Keys can only be used for JSON-over-HTTP APIs, including those under
|
||||
// the import path google.golang.org/api/....
|
||||
func WithAPIKey(apiKey string) ClientOption {
|
||||
return withAPIKey(apiKey)
|
||||
}
|
||||
|
||||
type withAPIKey string
|
||||
|
||||
func (w withAPIKey) Apply(o *internal.DialSettings) { o.APIKey = string(w) }
|
||||
|
||||
// WithAudiences returns a ClientOption that specifies an audience to be used
|
||||
// as the audience field ("aud") for the JWT token authentication.
|
||||
func WithAudiences(audience ...string) ClientOption {
|
||||
return withAudiences(audience)
|
||||
}
|
||||
|
||||
type withAudiences []string
|
||||
|
||||
func (w withAudiences) Apply(o *internal.DialSettings) {
|
||||
o.Audiences = make([]string, len(w))
|
||||
copy(o.Audiences, w)
|
||||
}
|
||||
|
||||
// WithoutAuthentication returns a ClientOption that specifies that no
|
||||
// authentication should be used. It is suitable only for testing and for
|
||||
// accessing public resources, like public Google Cloud Storage buckets.
|
||||
// It is an error to provide both WithoutAuthentication and any of WithAPIKey,
|
||||
// WithTokenSource, WithCredentialsFile or WithServiceAccountFile.
|
||||
func WithoutAuthentication() ClientOption {
|
||||
return withoutAuthentication{}
|
||||
}
|
||||
|
||||
type withoutAuthentication struct{}
|
||||
|
||||
func (w withoutAuthentication) Apply(o *internal.DialSettings) { o.NoAuth = true }
|
||||
|
||||
// WithQuotaProject returns a ClientOption that specifies the project used
|
||||
// for quota and billing purposes.
|
||||
//
|
||||
// For more information please read:
|
||||
// https://cloud.google.com/apis/docs/system-parameters
|
||||
func WithQuotaProject(quotaProject string) ClientOption {
|
||||
return withQuotaProject(quotaProject)
|
||||
}
|
||||
|
||||
type withQuotaProject string
|
||||
|
||||
func (w withQuotaProject) Apply(o *internal.DialSettings) {
|
||||
o.QuotaProject = string(w)
|
||||
}
|
||||
|
||||
// WithRequestReason returns a ClientOption that specifies a reason for
|
||||
// making the request, which is intended to be recorded in audit logging.
|
||||
// An example reason would be a support-case ticket number.
|
||||
//
|
||||
// For more information please read:
|
||||
// https://cloud.google.com/apis/docs/system-parameters
|
||||
func WithRequestReason(requestReason string) ClientOption {
|
||||
return withRequestReason(requestReason)
|
||||
}
|
||||
|
||||
type withRequestReason string
|
||||
|
||||
func (w withRequestReason) Apply(o *internal.DialSettings) {
|
||||
o.RequestReason = string(w)
|
||||
}
|
||||
|
||||
// WithTelemetryDisabled returns a ClientOption that disables default telemetry (OpenCensus)
|
||||
// settings on gRPC and HTTP clients.
|
||||
// An example reason would be to bind custom telemetry that overrides the defaults.
|
||||
func WithTelemetryDisabled() ClientOption {
|
||||
return withTelemetryDisabled{}
|
||||
}
|
||||
|
||||
type withTelemetryDisabled struct{}
|
||||
|
||||
func (w withTelemetryDisabled) Apply(o *internal.DialSettings) {
|
||||
o.TelemetryDisabled = true
|
||||
}
|
||||
|
||||
// ClientCertSource is a function that returns a TLS client certificate to be used
|
||||
// when opening TLS connections.
|
||||
//
|
||||
// It follows the same semantics as crypto/tls.Config.GetClientCertificate.
|
||||
//
|
||||
// This is an EXPERIMENTAL API and may be changed or removed in the future.
|
||||
type ClientCertSource = func(*tls.CertificateRequestInfo) (*tls.Certificate, error)
|
||||
|
||||
// WithClientCertSource returns a ClientOption that specifies a
|
||||
// callback function for obtaining a TLS client certificate.
|
||||
//
|
||||
// This option is used for supporting mTLS authentication, where the
|
||||
// server validates the client certifcate when establishing a connection.
|
||||
//
|
||||
// The callback function will be invoked whenever the server requests a
|
||||
// certificate from the client. Implementations of the callback function
|
||||
// should try to ensure that a valid certificate can be repeatedly returned
|
||||
// on demand for the entire life cycle of the transport client. If a nil
|
||||
// Certificate is returned (i.e. no Certificate can be obtained), an error
|
||||
// should be returned.
|
||||
//
|
||||
// This is an EXPERIMENTAL API and may be changed or removed in the future.
|
||||
func WithClientCertSource(s ClientCertSource) ClientOption {
|
||||
return withClientCertSource{s}
|
||||
}
|
||||
|
||||
type withClientCertSource struct{ s ClientCertSource }
|
||||
|
||||
func (w withClientCertSource) Apply(o *internal.DialSettings) {
|
||||
o.ClientCertSource = w.s
|
||||
}
|
||||
|
||||
// ImpersonateCredentials returns a ClientOption that will impersonate the
|
||||
// target service account.
|
||||
//
|
||||
// In order to impersonate the target service account
|
||||
// the base service account must have the Service Account Token Creator role,
|
||||
// roles/iam.serviceAccountTokenCreator, on the target service account.
|
||||
// See https://cloud.google.com/iam/docs/understanding-service-accounts.
|
||||
//
|
||||
// Optionally, delegates can be used during impersonation if the base service
|
||||
// account lacks the token creator role on the target. When using delegates,
|
||||
// each service account must be granted roles/iam.serviceAccountTokenCreator
|
||||
// on the next service account in the chain.
|
||||
//
|
||||
// For example, if a base service account of SA1 is trying to impersonate target
|
||||
// service account SA2 while using delegate service accounts DSA1 and DSA2,
|
||||
// the following must be true:
|
||||
//
|
||||
// 1. Base service account SA1 has roles/iam.serviceAccountTokenCreator on
|
||||
// DSA1.
|
||||
// 2. DSA1 has roles/iam.serviceAccountTokenCreator on DSA2.
|
||||
// 3. DSA2 has roles/iam.serviceAccountTokenCreator on target SA2.
|
||||
//
|
||||
// The resulting impersonated credential will either have the default scopes of
|
||||
// the client being instantiating or the scopes from WithScopes if provided.
|
||||
// Scopes are required for creating impersonated credentials, so if this option
|
||||
// is used while not using a NewClient/NewService function, WithScopes must also
|
||||
// be explicitly passed in as well.
|
||||
//
|
||||
// If the base credential is an authorized user and not a service account, or if
|
||||
// the option WithQuotaProject is set, the target service account must have a
|
||||
// role that grants the serviceusage.services.use permission such as
|
||||
// roles/serviceusage.serviceUsageConsumer.
|
||||
//
|
||||
// This is an EXPERIMENTAL API and may be changed or removed in the future.
|
||||
//
|
||||
// This option has been replaced by `impersonate` package:
|
||||
// `google.golang.org/api/impersonate`. Please use the `impersonate` package
|
||||
// instead.
|
||||
func ImpersonateCredentials(target string, delegates ...string) ClientOption {
|
||||
return impersonateServiceAccount{
|
||||
target: target,
|
||||
delegates: delegates,
|
||||
}
|
||||
}
|
||||
|
||||
type impersonateServiceAccount struct {
|
||||
target string
|
||||
delegates []string
|
||||
}
|
||||
|
||||
func (i impersonateServiceAccount) Apply(o *internal.DialSettings) {
|
||||
o.ImpersonationConfig = &impersonate.Config{
|
||||
Target: i.target,
|
||||
}
|
||||
o.ImpersonationConfig.Delegates = make([]string, len(i.delegates))
|
||||
copy(o.ImpersonationConfig.Delegates, i.delegates)
|
||||
}
|
||||
141
vendor/google.golang.org/api/transport/cert/default_cert.go
generated
vendored
141
vendor/google.golang.org/api/transport/cert/default_cert.go
generated
vendored
@@ -1,141 +0,0 @@
|
||||
// Copyright 2020 Google LLC.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package cert contains certificate tools for Google API clients.
|
||||
// This package is intended to be used with crypto/tls.Config.GetClientCertificate.
|
||||
//
|
||||
// The certificates can be used to satisfy Google's Endpoint Validation.
|
||||
// See https://cloud.google.com/endpoint-verification/docs/overview
|
||||
//
|
||||
// This package is not intended for use by end developers. Use the
|
||||
// google.golang.org/api/option package to configure API clients.
|
||||
package cert
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"os/exec"
|
||||
"os/user"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
metadataPath = ".secureConnect"
|
||||
metadataFile = "context_aware_metadata.json"
|
||||
)
|
||||
|
||||
// defaultCertData holds all the variables pertaining to
|
||||
// the default certficate source created by DefaultSource.
|
||||
type defaultCertData struct {
|
||||
once sync.Once
|
||||
source Source
|
||||
err error
|
||||
cachedCertMutex sync.Mutex
|
||||
cachedCert *tls.Certificate
|
||||
}
|
||||
|
||||
var (
|
||||
defaultCert defaultCertData
|
||||
)
|
||||
|
||||
// Source is a function that can be passed into crypto/tls.Config.GetClientCertificate.
|
||||
type Source func(*tls.CertificateRequestInfo) (*tls.Certificate, error)
|
||||
|
||||
// DefaultSource returns a certificate source that execs the command specified
|
||||
// in the file at ~/.secureConnect/context_aware_metadata.json
|
||||
//
|
||||
// If that file does not exist, a nil source is returned.
|
||||
func DefaultSource() (Source, error) {
|
||||
defaultCert.once.Do(func() {
|
||||
defaultCert.source, defaultCert.err = newSecureConnectSource()
|
||||
})
|
||||
return defaultCert.source, defaultCert.err
|
||||
}
|
||||
|
||||
type secureConnectSource struct {
|
||||
metadata secureConnectMetadata
|
||||
}
|
||||
|
||||
type secureConnectMetadata struct {
|
||||
Cmd []string `json:"cert_provider_command"`
|
||||
}
|
||||
|
||||
// newSecureConnectSource creates a secureConnectSource by reading the well-known file.
|
||||
func newSecureConnectSource() (Source, error) {
|
||||
user, err := user.Current()
|
||||
if err != nil {
|
||||
// Ignore.
|
||||
return nil, nil
|
||||
}
|
||||
filename := filepath.Join(user.HomeDir, metadataPath, metadataFile)
|
||||
file, err := ioutil.ReadFile(filename)
|
||||
if os.IsNotExist(err) {
|
||||
// Ignore.
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var metadata secureConnectMetadata
|
||||
if err := json.Unmarshal(file, &metadata); err != nil {
|
||||
return nil, fmt.Errorf("cert: could not parse JSON in %q: %v", filename, err)
|
||||
}
|
||||
if err := validateMetadata(metadata); err != nil {
|
||||
return nil, fmt.Errorf("cert: invalid config in %q: %v", filename, err)
|
||||
}
|
||||
return (&secureConnectSource{
|
||||
metadata: metadata,
|
||||
}).getClientCertificate, nil
|
||||
}
|
||||
|
||||
func validateMetadata(metadata secureConnectMetadata) error {
|
||||
if len(metadata.Cmd) == 0 {
|
||||
return errors.New("empty cert_provider_command")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *secureConnectSource) getClientCertificate(info *tls.CertificateRequestInfo) (*tls.Certificate, error) {
|
||||
defaultCert.cachedCertMutex.Lock()
|
||||
defer defaultCert.cachedCertMutex.Unlock()
|
||||
if defaultCert.cachedCert != nil && !isCertificateExpired(defaultCert.cachedCert) {
|
||||
return defaultCert.cachedCert, nil
|
||||
}
|
||||
// Expand OS environment variables in the cert provider command such as "$HOME".
|
||||
for i := 0; i < len(s.metadata.Cmd); i++ {
|
||||
s.metadata.Cmd[i] = os.ExpandEnv(s.metadata.Cmd[i])
|
||||
}
|
||||
command := s.metadata.Cmd
|
||||
data, err := exec.Command(command[0], command[1:]...).Output()
|
||||
if err != nil {
|
||||
// TODO(cbro): read stderr for error message? Might contain sensitive info.
|
||||
return nil, err
|
||||
}
|
||||
cert, err := tls.X509KeyPair(data, data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defaultCert.cachedCert = &cert
|
||||
return &cert, nil
|
||||
}
|
||||
|
||||
// isCertificateExpired returns true if the given cert is expired or invalid.
|
||||
func isCertificateExpired(cert *tls.Certificate) bool {
|
||||
if len(cert.Certificate) == 0 {
|
||||
return true
|
||||
}
|
||||
parsed, err := x509.ParseCertificate(cert.Certificate[0])
|
||||
if err != nil {
|
||||
return true
|
||||
}
|
||||
return time.Now().After(parsed.NotAfter)
|
||||
}
|
||||
26
vendor/google.golang.org/api/transport/http/configure_http2_go116.go
generated
vendored
26
vendor/google.golang.org/api/transport/http/configure_http2_go116.go
generated
vendored
@@ -1,26 +0,0 @@
|
||||
// Copyright 2021 Google LLC.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
//go:build go1.16
|
||||
// +build go1.16
|
||||
|
||||
package http
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"golang.org/x/net/http2"
|
||||
)
|
||||
|
||||
// configureHTTP2 configures the ReadIdleTimeout HTTP/2 option for the
|
||||
// transport. This allows broken idle connections to be pruned more quickly,
|
||||
// preventing the client from attempting to re-use connections that will no
|
||||
// longer work.
|
||||
func configureHTTP2(trans *http.Transport) {
|
||||
http2Trans, err := http2.ConfigureTransports(trans)
|
||||
if err == nil {
|
||||
http2Trans.ReadIdleTimeout = time.Second * 31
|
||||
}
|
||||
}
|
||||
17
vendor/google.golang.org/api/transport/http/configure_http2_not_go116.go
generated
vendored
17
vendor/google.golang.org/api/transport/http/configure_http2_not_go116.go
generated
vendored
@@ -1,17 +0,0 @@
|
||||
// Copyright 2021 Google LLC.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
//go:build !go1.16
|
||||
// +build !go1.16
|
||||
|
||||
package http
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// configureHTTP2 configures the ReadIdleTimeout HTTP/2 option for the
|
||||
// transport. The interface to do this is only available in Go 1.16 and up, so
|
||||
// this performs a no-op.
|
||||
func configureHTTP2(trans *http.Transport) {}
|
||||
21
vendor/google.golang.org/api/transport/http/default_transport_go113.go
generated
vendored
21
vendor/google.golang.org/api/transport/http/default_transport_go113.go
generated
vendored
@@ -1,21 +0,0 @@
|
||||
// Copyright 2020 Google LLC.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
//go:build go1.13
|
||||
// +build go1.13
|
||||
|
||||
package http
|
||||
|
||||
import "net/http"
|
||||
|
||||
// clonedTransport returns the given RoundTripper as a cloned *http.Transport.
|
||||
// It returns nil if the RoundTripper can't be cloned or coerced to
|
||||
// *http.Transport.
|
||||
func clonedTransport(rt http.RoundTripper) *http.Transport {
|
||||
t, ok := rt.(*http.Transport)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
return t.Clone()
|
||||
}
|
||||
16
vendor/google.golang.org/api/transport/http/default_transport_not_go113.go
generated
vendored
16
vendor/google.golang.org/api/transport/http/default_transport_not_go113.go
generated
vendored
@@ -1,16 +0,0 @@
|
||||
// Copyright 2020 Google LLC.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
//go:build !go1.13
|
||||
// +build !go1.13
|
||||
|
||||
package http
|
||||
|
||||
import "net/http"
|
||||
|
||||
// clonedTransport returns the given RoundTripper as a cloned *http.Transport.
|
||||
// For versions of Go <1.13, this is not supported, so return nil.
|
||||
func clonedTransport(rt http.RoundTripper) *http.Transport {
|
||||
return nil
|
||||
}
|
||||
212
vendor/google.golang.org/api/transport/http/dial.go
generated
vendored
212
vendor/google.golang.org/api/transport/http/dial.go
generated
vendored
@@ -1,212 +0,0 @@
|
||||
// Copyright 2015 Google LLC.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package http supports network connections to HTTP servers.
|
||||
// This package is not intended for use by end developers. Use the
|
||||
// google.golang.org/api/option package to configure API clients.
|
||||
package http
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"go.opencensus.io/plugin/ochttp"
|
||||
"golang.org/x/oauth2"
|
||||
"google.golang.org/api/googleapi/transport"
|
||||
"google.golang.org/api/internal"
|
||||
"google.golang.org/api/option"
|
||||
"google.golang.org/api/transport/cert"
|
||||
"google.golang.org/api/transport/http/internal/propagation"
|
||||
"google.golang.org/api/transport/internal/dca"
|
||||
)
|
||||
|
||||
// NewClient returns an HTTP client for use communicating with a Google cloud
|
||||
// service, configured with the given ClientOptions. It also returns the endpoint
|
||||
// for the service as specified in the options.
|
||||
func NewClient(ctx context.Context, opts ...option.ClientOption) (*http.Client, string, error) {
|
||||
settings, err := newSettings(opts)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
clientCertSource, endpoint, err := dca.GetClientCertificateSourceAndEndpoint(settings)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
// TODO(cbro): consider injecting the User-Agent even if an explicit HTTP client is provided?
|
||||
if settings.HTTPClient != nil {
|
||||
return settings.HTTPClient, endpoint, nil
|
||||
}
|
||||
trans, err := newTransport(ctx, defaultBaseTransport(ctx, clientCertSource), settings)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
return &http.Client{Transport: trans}, endpoint, nil
|
||||
}
|
||||
|
||||
// NewTransport creates an http.RoundTripper for use communicating with a Google
|
||||
// cloud service, configured with the given ClientOptions. Its RoundTrip method delegates to base.
|
||||
func NewTransport(ctx context.Context, base http.RoundTripper, opts ...option.ClientOption) (http.RoundTripper, error) {
|
||||
settings, err := newSettings(opts)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if settings.HTTPClient != nil {
|
||||
return nil, errors.New("transport/http: WithHTTPClient passed to NewTransport")
|
||||
}
|
||||
return newTransport(ctx, base, settings)
|
||||
}
|
||||
|
||||
func newTransport(ctx context.Context, base http.RoundTripper, settings *internal.DialSettings) (http.RoundTripper, error) {
|
||||
paramTransport := ¶meterTransport{
|
||||
base: base,
|
||||
userAgent: settings.UserAgent,
|
||||
quotaProject: settings.QuotaProject,
|
||||
requestReason: settings.RequestReason,
|
||||
}
|
||||
var trans http.RoundTripper = paramTransport
|
||||
trans = addOCTransport(trans, settings)
|
||||
switch {
|
||||
case settings.NoAuth:
|
||||
// Do nothing.
|
||||
case settings.APIKey != "":
|
||||
trans = &transport.APIKey{
|
||||
Transport: trans,
|
||||
Key: settings.APIKey,
|
||||
}
|
||||
default:
|
||||
creds, err := internal.Creds(ctx, settings)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if paramTransport.quotaProject == "" {
|
||||
paramTransport.quotaProject = internal.QuotaProjectFromCreds(creds)
|
||||
}
|
||||
|
||||
ts := creds.TokenSource
|
||||
if settings.ImpersonationConfig == nil && settings.TokenSource != nil {
|
||||
ts = settings.TokenSource
|
||||
}
|
||||
trans = &oauth2.Transport{
|
||||
Base: trans,
|
||||
Source: ts,
|
||||
}
|
||||
}
|
||||
return trans, nil
|
||||
}
|
||||
|
||||
func newSettings(opts []option.ClientOption) (*internal.DialSettings, error) {
|
||||
var o internal.DialSettings
|
||||
for _, opt := range opts {
|
||||
opt.Apply(&o)
|
||||
}
|
||||
if err := o.Validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if o.GRPCConn != nil {
|
||||
return nil, errors.New("unsupported gRPC connection specified")
|
||||
}
|
||||
return &o, nil
|
||||
}
|
||||
|
||||
type parameterTransport struct {
|
||||
userAgent string
|
||||
quotaProject string
|
||||
requestReason string
|
||||
|
||||
base http.RoundTripper
|
||||
}
|
||||
|
||||
func (t *parameterTransport) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||
rt := t.base
|
||||
if rt == nil {
|
||||
return nil, errors.New("transport: no Transport specified")
|
||||
}
|
||||
newReq := *req
|
||||
newReq.Header = make(http.Header)
|
||||
for k, vv := range req.Header {
|
||||
newReq.Header[k] = vv
|
||||
}
|
||||
if t.userAgent != "" {
|
||||
// TODO(cbro): append to existing User-Agent header?
|
||||
newReq.Header.Set("User-Agent", t.userAgent)
|
||||
}
|
||||
|
||||
// Attach system parameters into the header
|
||||
if t.quotaProject != "" {
|
||||
newReq.Header.Set("X-Goog-User-Project", t.quotaProject)
|
||||
}
|
||||
if t.requestReason != "" {
|
||||
newReq.Header.Set("X-Goog-Request-Reason", t.requestReason)
|
||||
}
|
||||
|
||||
return rt.RoundTrip(&newReq)
|
||||
}
|
||||
|
||||
// Set at init time by dial_appengine.go. If nil, we're not on App Engine.
|
||||
var appengineUrlfetchHook func(context.Context) http.RoundTripper
|
||||
|
||||
// defaultBaseTransport returns the base HTTP transport.
|
||||
// On App Engine, this is urlfetch.Transport.
|
||||
// Otherwise, use a default transport, taking most defaults from
|
||||
// http.DefaultTransport.
|
||||
// If TLSCertificate is available, set TLSClientConfig as well.
|
||||
func defaultBaseTransport(ctx context.Context, clientCertSource cert.Source) http.RoundTripper {
|
||||
if appengineUrlfetchHook != nil {
|
||||
return appengineUrlfetchHook(ctx)
|
||||
}
|
||||
|
||||
// Copy http.DefaultTransport except for MaxIdleConnsPerHost setting,
|
||||
// which is increased due to reported performance issues under load in the GCS
|
||||
// client. Transport.Clone is only available in Go 1.13 and up.
|
||||
trans := clonedTransport(http.DefaultTransport)
|
||||
if trans == nil {
|
||||
trans = fallbackBaseTransport()
|
||||
}
|
||||
trans.MaxIdleConnsPerHost = 100
|
||||
|
||||
if clientCertSource != nil {
|
||||
trans.TLSClientConfig = &tls.Config{
|
||||
GetClientCertificate: clientCertSource,
|
||||
}
|
||||
}
|
||||
|
||||
// If possible, configure http2 transport in order to use ReadIdleTimeout
|
||||
// setting. This can only be done in Go 1.16 and up.
|
||||
configureHTTP2(trans)
|
||||
|
||||
return trans
|
||||
}
|
||||
|
||||
// fallbackBaseTransport is used in <go1.13 as well as in the rare case if
|
||||
// http.DefaultTransport has been reassigned something that's not a
|
||||
// *http.Transport.
|
||||
func fallbackBaseTransport() *http.Transport {
|
||||
return &http.Transport{
|
||||
Proxy: http.ProxyFromEnvironment,
|
||||
DialContext: (&net.Dialer{
|
||||
Timeout: 30 * time.Second,
|
||||
KeepAlive: 30 * time.Second,
|
||||
DualStack: true,
|
||||
}).DialContext,
|
||||
MaxIdleConns: 100,
|
||||
MaxIdleConnsPerHost: 100,
|
||||
IdleConnTimeout: 90 * time.Second,
|
||||
TLSHandshakeTimeout: 10 * time.Second,
|
||||
ExpectContinueTimeout: 1 * time.Second,
|
||||
}
|
||||
}
|
||||
|
||||
func addOCTransport(trans http.RoundTripper, settings *internal.DialSettings) http.RoundTripper {
|
||||
if settings.TelemetryDisabled {
|
||||
return trans
|
||||
}
|
||||
return &ochttp.Transport{
|
||||
Base: trans,
|
||||
Propagation: &propagation.HTTPFormat{},
|
||||
}
|
||||
}
|
||||
21
vendor/google.golang.org/api/transport/http/dial_appengine.go
generated
vendored
21
vendor/google.golang.org/api/transport/http/dial_appengine.go
generated
vendored
@@ -1,21 +0,0 @@
|
||||
// Copyright 2016 Google LLC.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
//go:build appengine
|
||||
// +build appengine
|
||||
|
||||
package http
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"google.golang.org/appengine/urlfetch"
|
||||
)
|
||||
|
||||
func init() {
|
||||
appengineUrlfetchHook = func(ctx context.Context) http.RoundTripper {
|
||||
return &urlfetch.Transport{Context: ctx}
|
||||
}
|
||||
}
|
||||
87
vendor/google.golang.org/api/transport/http/internal/propagation/http.go
generated
vendored
87
vendor/google.golang.org/api/transport/http/internal/propagation/http.go
generated
vendored
@@ -1,87 +0,0 @@
|
||||
// Copyright 2018 Google LLC.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
//go:build go1.8
|
||||
// +build go1.8
|
||||
|
||||
// Package propagation implements X-Cloud-Trace-Context header propagation used
|
||||
// by Google Cloud products.
|
||||
package propagation
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"go.opencensus.io/trace"
|
||||
"go.opencensus.io/trace/propagation"
|
||||
)
|
||||
|
||||
const (
|
||||
httpHeaderMaxSize = 200
|
||||
httpHeader = `X-Cloud-Trace-Context`
|
||||
)
|
||||
|
||||
var _ propagation.HTTPFormat = (*HTTPFormat)(nil)
|
||||
|
||||
// HTTPFormat implements propagation.HTTPFormat to propagate
|
||||
// traces in HTTP headers for Google Cloud Platform and Stackdriver Trace.
|
||||
type HTTPFormat struct{}
|
||||
|
||||
// SpanContextFromRequest extracts a Stackdriver Trace span context from incoming requests.
|
||||
func (f *HTTPFormat) SpanContextFromRequest(req *http.Request) (sc trace.SpanContext, ok bool) {
|
||||
h := req.Header.Get(httpHeader)
|
||||
// See https://cloud.google.com/trace/docs/faq for the header HTTPFormat.
|
||||
// Return if the header is empty or missing, or if the header is unreasonably
|
||||
// large, to avoid making unnecessary copies of a large string.
|
||||
if h == "" || len(h) > httpHeaderMaxSize {
|
||||
return trace.SpanContext{}, false
|
||||
}
|
||||
|
||||
// Parse the trace id field.
|
||||
slash := strings.Index(h, `/`)
|
||||
if slash == -1 {
|
||||
return trace.SpanContext{}, false
|
||||
}
|
||||
tid, h := h[:slash], h[slash+1:]
|
||||
|
||||
buf, err := hex.DecodeString(tid)
|
||||
if err != nil {
|
||||
return trace.SpanContext{}, false
|
||||
}
|
||||
copy(sc.TraceID[:], buf)
|
||||
|
||||
// Parse the span id field.
|
||||
spanstr := h
|
||||
semicolon := strings.Index(h, `;`)
|
||||
if semicolon != -1 {
|
||||
spanstr, h = h[:semicolon], h[semicolon+1:]
|
||||
}
|
||||
sid, err := strconv.ParseUint(spanstr, 10, 64)
|
||||
if err != nil {
|
||||
return trace.SpanContext{}, false
|
||||
}
|
||||
binary.BigEndian.PutUint64(sc.SpanID[:], sid)
|
||||
|
||||
// Parse the options field, options field is optional.
|
||||
if !strings.HasPrefix(h, "o=") {
|
||||
return sc, true
|
||||
}
|
||||
o, err := strconv.ParseUint(h[2:], 10, 64)
|
||||
if err != nil {
|
||||
return trace.SpanContext{}, false
|
||||
}
|
||||
sc.TraceOptions = trace.TraceOptions(o)
|
||||
return sc, true
|
||||
}
|
||||
|
||||
// SpanContextToRequest modifies the given request to include a Stackdriver Trace header.
|
||||
func (f *HTTPFormat) SpanContextToRequest(sc trace.SpanContext, req *http.Request) {
|
||||
sid := binary.BigEndian.Uint64(sc.SpanID[:])
|
||||
header := fmt.Sprintf("%s/%d;o=%d", hex.EncodeToString(sc.TraceID[:]), sid, int64(sc.TraceOptions))
|
||||
req.Header.Set(httpHeader, header)
|
||||
}
|
||||
143
vendor/google.golang.org/api/transport/internal/dca/dca.go
generated
vendored
143
vendor/google.golang.org/api/transport/internal/dca/dca.go
generated
vendored
@@ -1,143 +0,0 @@
|
||||
// Copyright 2020 Google LLC.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package dca contains utils for implementing Device Certificate
|
||||
// Authentication according to https://google.aip.dev/auth/4114
|
||||
//
|
||||
// The overall logic for DCA is as follows:
|
||||
// 1. If both endpoint override and client certificate are specified, use them as is.
|
||||
// 2. If user does not specify client certificate, we will attempt to use default
|
||||
// client certificate.
|
||||
// 3. If user does not specify endpoint override, we will use defaultMtlsEndpoint if
|
||||
// client certificate is available and defaultEndpoint otherwise.
|
||||
//
|
||||
// Implications of the above logic:
|
||||
// 1. If the user specifies a non-mTLS endpoint override but client certificate is
|
||||
// available, we will pass along the cert anyway and let the server decide what to do.
|
||||
// 2. If the user specifies an mTLS endpoint override but client certificate is not
|
||||
// available, we will not fail-fast, but let backend throw error when connecting.
|
||||
//
|
||||
// We would like to avoid introducing client-side logic that parses whether the
|
||||
// endpoint override is an mTLS url, since the url pattern may change at anytime.
|
||||
//
|
||||
// This package is not intended for use by end developers. Use the
|
||||
// google.golang.org/api/option package to configure API clients.
|
||||
package dca
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"google.golang.org/api/internal"
|
||||
"google.golang.org/api/transport/cert"
|
||||
)
|
||||
|
||||
const (
|
||||
mTLSModeAlways = "always"
|
||||
mTLSModeNever = "never"
|
||||
mTLSModeAuto = "auto"
|
||||
)
|
||||
|
||||
// GetClientCertificateSourceAndEndpoint is a convenience function that invokes
|
||||
// getClientCertificateSource and getEndpoint sequentially and returns the client
|
||||
// cert source and endpoint as a tuple.
|
||||
func GetClientCertificateSourceAndEndpoint(settings *internal.DialSettings) (cert.Source, string, error) {
|
||||
clientCertSource, err := getClientCertificateSource(settings)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
endpoint, err := getEndpoint(settings, clientCertSource)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
return clientCertSource, endpoint, nil
|
||||
}
|
||||
|
||||
// getClientCertificateSource returns a default client certificate source, if
|
||||
// not provided by the user.
|
||||
//
|
||||
// A nil default source can be returned if the source does not exist. Any exceptions
|
||||
// encountered while initializing the default source will be reported as client
|
||||
// error (ex. corrupt metadata file).
|
||||
//
|
||||
// Important Note: For now, the environment variable GOOGLE_API_USE_CLIENT_CERTIFICATE
|
||||
// must be set to "true" to allow certificate to be used (including user provided
|
||||
// certificates). For details, see AIP-4114.
|
||||
func getClientCertificateSource(settings *internal.DialSettings) (cert.Source, error) {
|
||||
if !isClientCertificateEnabled() {
|
||||
return nil, nil
|
||||
} else if settings.ClientCertSource != nil {
|
||||
return settings.ClientCertSource, nil
|
||||
} else {
|
||||
return cert.DefaultSource()
|
||||
}
|
||||
}
|
||||
|
||||
func isClientCertificateEnabled() bool {
|
||||
useClientCert := os.Getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE")
|
||||
// TODO(andyrzhao): Update default to return "true" after DCA feature is fully released.
|
||||
return strings.ToLower(useClientCert) == "true"
|
||||
}
|
||||
|
||||
// getEndpoint returns the endpoint for the service, taking into account the
|
||||
// user-provided endpoint override "settings.Endpoint".
|
||||
//
|
||||
// If no endpoint override is specified, we will either return the default endpoint or
|
||||
// the default mTLS endpoint if a client certificate is available.
|
||||
//
|
||||
// You can override the default endpoint choice (mtls vs. regular) by setting the
|
||||
// GOOGLE_API_USE_MTLS_ENDPOINT environment variable.
|
||||
//
|
||||
// If the endpoint override is an address (host:port) rather than full base
|
||||
// URL (ex. https://...), then the user-provided address will be merged into
|
||||
// the default endpoint. For example, WithEndpoint("myhost:8000") and
|
||||
// WithDefaultEndpoint("https://foo.com/bar/baz") will return "https://myhost:8080/bar/baz"
|
||||
func getEndpoint(settings *internal.DialSettings, clientCertSource cert.Source) (string, error) {
|
||||
if settings.Endpoint == "" {
|
||||
mtlsMode := getMTLSMode()
|
||||
if mtlsMode == mTLSModeAlways || (clientCertSource != nil && mtlsMode == mTLSModeAuto) {
|
||||
return settings.DefaultMTLSEndpoint, nil
|
||||
}
|
||||
return settings.DefaultEndpoint, nil
|
||||
}
|
||||
if strings.Contains(settings.Endpoint, "://") {
|
||||
// User passed in a full URL path, use it verbatim.
|
||||
return settings.Endpoint, nil
|
||||
}
|
||||
if settings.DefaultEndpoint == "" {
|
||||
// If DefaultEndpoint is not configured, use the user provided endpoint verbatim.
|
||||
// This allows a naked "host[:port]" URL to be used with GRPC Direct Path.
|
||||
return settings.Endpoint, nil
|
||||
}
|
||||
|
||||
// Assume user-provided endpoint is host[:port], merge it with the default endpoint.
|
||||
return mergeEndpoints(settings.DefaultEndpoint, settings.Endpoint)
|
||||
}
|
||||
|
||||
func getMTLSMode() string {
|
||||
mode := os.Getenv("GOOGLE_API_USE_MTLS_ENDPOINT")
|
||||
if mode == "" {
|
||||
mode = os.Getenv("GOOGLE_API_USE_MTLS") // Deprecated.
|
||||
}
|
||||
if mode == "" {
|
||||
return mTLSModeAuto
|
||||
}
|
||||
return strings.ToLower(mode)
|
||||
}
|
||||
|
||||
func mergeEndpoints(baseURL, newHost string) (string, error) {
|
||||
u, err := url.Parse(fixScheme(baseURL))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return strings.Replace(baseURL, u.Host, newHost, 1), nil
|
||||
}
|
||||
|
||||
func fixScheme(baseURL string) string {
|
||||
if !strings.Contains(baseURL, "://") {
|
||||
return "https://" + baseURL
|
||||
}
|
||||
return baseURL
|
||||
}
|
||||
Reference in New Issue
Block a user