Skip to content

Instantly share code, notes, and snippets.

@orian
Created August 15, 2014 17:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save orian/96b5140b66363f4dee65 to your computer and use it in GitHub Desktop.
Save orian/96b5140b66363f4dee65 to your computer and use it in GitHub Desktop.
Modified version of https://developers.google.com/drive/web/quickstart/quickstart-go app, so it caches access token.
package main
import (
"fmt"
"log"
"os"
"net/http"
"code.google.com/p/google-api-go-client/drive/v2"
"code.google.com/p/goauth2/oauth"
)
// Settings for authorization.
var config = &oauth.Config{
ClientId: "YOUR_CLIENT_ID",
ClientSecret: "YOUR_CLIENT_SECRET",
Scope: "https://www.googleapis.com/auth/drive",
RedirectURL: "urn:ietf:wg:oauth:2.0:oob",
AuthURL: "https://accounts.google.com/o/oauth2/auth",
TokenURL: "https://accounts.google.com/o/oauth2/token",
}
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
fmt.Scanln(&code)
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()
cache.PutToken(token)
} 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