Files
fn-serverless/vendor/google.golang.org/api/GettingStarted.md
Reed Allman 51ff7caeb2 Bye bye openapi (#1081)
* add DateTime sans mgo

* change all uses of strfmt.DateTime to common.DateTime, remove test strfmt usage

* remove api tests, system-test dep on api test

multiple reasons to remove the api tests:

* awkward dependency with fn_go meant generating bindings on a branched fn to
vendor those to test new stuff. this is at a minimum not at all intuitive,
worth it, nor a fun way to spend the finite amount of time we have to live.
* api tests only tested a subset of functionality that the server/ api tests
already test, and we risk having tests where one tests some thing and the
other doesn't. let's not. we have too many test suites as it is, and these
pretty much only test that we updated the fn_go bindings, which is actually a
hassle as noted above and the cli will pretty quickly figure out anyway.
* fn_go relies on openapi, which relies on mgo, which is deprecated and we'd
like to remove as a dependency. openapi is a _huge_ dep built in a NIH
fashion, that cannot simply remove the mgo dep as users may be using it.
we've now stolen their date time and otherwise killed usage of it in fn core,
for fn_go it still exists but that's less of a problem.

* update deps

removals:

* easyjson
* mgo
* go-openapi
* mapstructure
* fn_go
* purell
* go-validator

also, had to lock docker. we shouldn't use docker on master anyway, they
strongly advise against that. had no luck with latest version rev, so i locked
it to what we were using before. until next time.

the rest is just playing dep roulette, those end up removing a ton tho

* fix exec test to work

* account for john le cache
2018-06-21 11:09:16 -07:00

4.6 KiB

Getting Started with the Google APIs for Go

Getting Started

This is a quick walk-through of how to get started with the Google APIs for Go.

Background

The first thing to understand is that the Google API libraries are auto-generated for each language, including Go, so they may not feel like 100% natural for any language. The Go versions are pretty natural, but please forgive any small non-idiomatic things. (Suggestions welcome, though!)

Installing

Pick an API and a version of that API to install. You can find the complete list by looking at the directories here.

For example, let's install the urlshortener's version 1 API:

$ go get -u google.golang.org/api/urlshortener/v1

Now it's ready for use in your code.

Using

Once you've installed a library, you import it like this:

package main

import (
    "golang.org/x/net/context"
    "golang.org/x/oauth2"
    "golang.org/x/oauth2/google"
    "google.golang.org/api/urlshortener/v1"
)

The package name, if you don't override it on your import line, is the name of the API without the version number. In the case above, just urlshortener.

Instantiating

Each API has a New function taking an *http.Client and returning an API-specific *Service.

You create the service like:

    svc, err := urlshortener.New(httpClient)

OAuth HTTP Client

The HTTP client you pass in to the service must be one that automatically adds Google-supported Authorization information to the requests.

There are several ways to do authentication. They will all involve the package golang.org/x/oauth2 in some way.

3-legged OAuth

For 3-legged OAuth (your application redirecting a user through a website to get a token giving your application access to that user's resources), you will need to create an oauth2.Config,

    var config = &oauth2.Config{
        ClientID:     "", // from https://console.developers.google.com/project/<your-project-id>/apiui/credential
        ClientSecret: "", // from https://console.developers.google.com/project/<your-project-id>/apiui/credential
        Endpoint:     google.Endpoint,
        Scopes:       []string{urlshortener.UrlshortenerScope},
    }

... and then use the AuthCodeURL, Exchange, and Client methods on it. For an example, see: https://godoc.org/golang.org/x/oauth2#example-Config

For the redirect URL, see https://developers.google.com/identity/protocols/OAuth2InstalledApp#choosingredirecturi

Service Accounts

To use a Google service account, or the GCE metadata service, see the golang.org/x/oauth2/google package. In particular, see google.DefaultClient.

Using API Keys

Some APIs require passing API keys from your application. To do this, you can use transport.APIKey:

    ctx := context.WithValue(context.Background(), oauth2.HTTPClient, &http.Client{
        Transport: &transport.APIKey{Key: developerKey},
    })
    oauthConfig := &oauth2.Config{ .... }
    var token *oauth2.Token = .... // via cache, or oauthConfig.Exchange
    httpClient := oauthConfig.Client(ctx, token)
    svc, err := urlshortener.New(httpClient)
    ...

Using the Service

Each service contains zero or more methods and zero or more sub-services. The sub-services related to a specific type of "Resource".

Those sub-services then contain their own methods.

For instance, the urlshortener API has just the "Url" sub-service:

    url, err := svc.Url.Get(shortURL).Do()
    if err != nil {
        ...
    }
    fmt.Printf("The URL %s goes to %s\n", shortURL, url.LongUrl)

For a more complete example, see urlshortener.go in the examples directory. (the examples use some functions in main.go in the same directory)

Error Handling

Most errors returned by the Do methods of these clients will be of type googleapi.Error. Use a type assertion to obtain the HTTP status code and other properties of the error:

    url, err := svc.Url.Get(shortURL).Do()
    if err != nil {
        if e, ok := err.(*googleapi.Error); ok && e.Code == http.StatusNotFound {
            ...
        }
    }