Created
August 13, 2014 15:29
-
-
Save johnwesonga/f597b1f6b4e83ff51036 to your computer and use it in GitHub Desktop.
Access Google Cloud storage buckets and objects using Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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