Skip to content

Instantly share code, notes, and snippets.

@chischaschos
Last active August 29, 2015 14:07
Show Gist options
  • Select an option

  • Save chischaschos/901e40b72ff34e32a2c9 to your computer and use it in GitHub Desktop.

Select an option

Save chischaschos/901e40b72ff34e32a2c9 to your computer and use it in GitHub Desktop.

Revisions

  1. chischaschos renamed this gist Oct 8, 2014. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. chischaschos created this gist Oct 8, 2014.
    93 changes: 93 additions & 0 deletions gcs_list_bucket
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,93 @@
    package main

    import (
    "strings"

    "fmt"
    "io/ioutil"
    "net/http"
    "net/url"

    "code.google.com/p/goauth2/oauth/jwt"
    "code.google.com/p/google-api-go-client/googleapi"
    "code.google.com/p/google-api-go-client/storage/v1beta2"
    )

    func main() {
    iss := "[email protected]"
    scope := "https://www.googleapis.com/auth/devstorage.read_only"

    pemKeyBytes, _ := ioutil.ReadFile("pkey.pem")

    t := jwt.NewToken(iss, scope, pemKeyBytes)

    transport, transError := jwt.NewTransport(t)

    if transError != nil {
    panic(transError)
    }

    client := transport.Client()
    service, err := storage.New(client)

    if err != nil {
    panic(err)
    }

    // List all buckets in a project.
    if res, err := service.Buckets.List("projectid").Do(); err == nil {
    fmt.Println("Buckets:")
    for _, item := range res.Items {
    fmt.Println(item.Id)
    }
    fmt.Println()
    } else {
    fmt.Println(service, "Buckets.List failed: %v", err)
    }

    bucket := "aabucket"

    if res, err := service.Objects.List(bucket).Do(); err == nil {
    fmt.Println("Objects:")
    for _, item := range res.Items {
    fmt.Println(item.Name)
    }
    fmt.Println()
    } else {
    fmt.Println(service, "Objects.List failed: %v", err)
    }

    filename := "filename"

    if obj, err := service.Objects.Get(bucket, filename).Do(); err == nil {
    fmt.Println("Object:")
    fmt.Println(obj.Name == filename)

    urltemplate := "https://www.googleapis.com/storage/v1beta2/b/{bucket}/o/{object}?alt=media"

    req, _ := http.NewRequest("GET", urltemplate, nil)
    fmt.Println(req.URL)
    req.URL.Path = strings.Replace(req.URL.Path, "{bucket}", url.QueryEscape(bucket), 1)
    req.URL.Path = strings.Replace(req.URL.Path, "{object}", url.QueryEscape(filename), 1)
    googleapi.SetOpaque(req.URL)
    fmt.Println(req.URL)

    resp, getErr := client.Do(req)

    if getErr != nil {
    panic(getErr)
    }

    bodyBytes, readErr := ioutil.ReadAll(resp.Body)

    if readErr != nil {
    panic(readErr)
    }

    fmt.Println(string(bodyBytes))

    } else {
    fmt.Println(service, "Objects.Get failed: %v", err)
    }

    }