Skip to content

Instantly share code, notes, and snippets.

@orian
Created August 19, 2014 12:21
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save orian/6a0d7883ca3678cb30ea to your computer and use it in GitHub Desktop.
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
}
// AllFiles fetches and displays all files
func AllFiles(d *drive.Service) ([]*drive.File, error) {
var fs []*drive.File
pageToken := ""
for {
q := d.Files.List()
// If we have a pageToken set, apply it to the query
if pageToken != "" {
q = q.PageToken(pageToken)
}
r, err := q.Do()
if err != nil {
fmt.Printf("An error occurred: %v\n", err)
return fs, err
}
fs = append(fs, r.Items...)
pageToken = r.NextPageToken
if pageToken == "" {
break
}
}
return fs, nil
}
// 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)
}
files, err := AllFiles(svc)
for _,f := range files {
fmt.Printf("File: %s\n", f.Title)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment