Skip to content

Instantly share code, notes, and snippets.

@orian orian/quickstart.go
Created Aug 15, 2014

What would you like to do?
Modified version of app, so it caches access token.
package main
import (
// Settings for authorization.
var config = &oauth.Config{
Scope: "",
RedirectURL: "urn:ietf:wg:oauth:2.0:oob",
AuthURL: "",
TokenURL: "",
func GetNewToken() (*oauth.Token, *oauth.Transport) {
// Generate a URL to visit for authorization.
authUrl := config.AuthCodeURL("state")
log.Printf("Go to the following link in your browser: %v\n", authUrl)
// Read the code, and exchange it for a token.
log.Printf("Enter verification code: ")
var code string
t := &oauth.Transport{
Config: config,
Transport: http.DefaultTransport,
token, err := t.Exchange(code)
if err != nil {
log.Fatalf("An error occurred exchanging the code: %v\n", err)
return token, t
// Uploads a file to Google Drive
func main() {
var cache oauth.Cache = oauth.CacheFile("access_token.json")
token, err := cache.Token()
var t *oauth.Transport
if err != nil {
log.Printf("Need a new token. Cannot load old one.")
token, t = GetNewToken()
} else {
t = &oauth.Transport{
Config: config,
Token: token,
Transport: http.DefaultTransport,
// Create a new authorized Drive client.
svc, err := drive.New(t.Client())
if err != nil {
log.Fatalf("An error occurred creating Drive client: %v\n", err)
// Define the metadata for the file we are going to create.
f := &drive.File{
Title: "My Document",
Description: "My test document",
// Read the file data that we are going to upload.
m, err := os.Open("document.txt")
if err != nil {
log.Fatalf("An error occurred reading the document: %v\n", err)
// Make the API request to upload metadata and file data.
r, err := svc.Files.Insert(f).Media(m).Do()
if err != nil {
log.Fatalf("An error occurred uploading the document: %v\n", err)
log.Printf("Created: ID=%v, Title=%v\n", r.Id, r.Title)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.