Skip to content

Instantly share code, notes, and snippets.

@johnwesonga
Created August 13, 2014 15:29
Show Gist options
  • Save johnwesonga/f597b1f6b4e83ff51036 to your computer and use it in GitHub Desktop.
Save johnwesonga/f597b1f6b4e83ff51036 to your computer and use it in GitHub Desktop.
Access Google Cloud storage buckets and objects using Go
package main
import (
gs "camlistore.org/pkg/googlestorage"
"code.google.com/p/goauth2/oauth"
"fmt"
"log"
)
const (
clientId = "" //get this from cloud console > credentials
clientSecret = "" //get this from cloud console > credentials
bucket = "test"
code = ""
)
var config = &oauth.Config{
ClientId: clientId,
ClientSecret: clientSecret,
Scope: gs.Scope,
AuthURL: gs.AuthURL,
TokenURL: gs.TokenURL,
RedirectURL: gs.RedirectURL,
TokenCache: oauth.CacheFile("cache.json"),
}
func GetorSetToken() string {
transport := &oauth.Transport{Config: config}
token, err := config.TokenCache.Token()
if err != nil {
if code == "" {
url := config.AuthCodeURL("")
fmt.Print("Visit this URL to get a code, then run again with -code=YOUR_CODE\n\n")
fmt.Println(url)
return ""
}
token, err = transport.Exchange(code)
if err != nil {
log.Fatal("Exchange:", err)
}
// (The Exchange method will automatically cache the token.)
fmt.Printf("Token is cached in %v\n", config.TokenCache)
}
transport.Token = token
return transport.Token.RefreshToken
}
func main() {
refreshToken := GetorSetToken()
ts := gs.MakeOauthTransport(clientId, clientSecret, refreshToken)
gsClient := gs.NewClient(ts)
bucketObjects, err := gsClient.EnumerateObjects(bucket, "", 10)
if err != nil {
log.Fatal(err)
}
for _, v := range bucketObjects {
fmt.Printf("Key: %v Size: %v \n", v.Key, v.Size)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment