Skip to content

Instantly share code, notes, and snippets.

@techjanitor
Created May 9, 2015 04:08
Show Gist options
  • Save techjanitor/993172582e48d19093a3 to your computer and use it in GitHub Desktop.
Save techjanitor/993172582e48d19093a3 to your computer and use it in GitHub Desktop.
Upload a file to Google Cloud Storage
package main
import (
"errors"
"fmt"
"golang.org/x/oauth2"
"golang.org/x/oauth2/jwt"
storage "google.golang.org/api/storage/v1"
"os"
)
// Authenticate to Google Cloud Storage and return handler
func getGCS() (service *storage.Service, err error) {
// OAuth2 info from GCS console
authconf := &jwt.Config{
Email: "whatever@email.com",
PrivateKey: []byte("key"),
Scopes: []string{storage.DevstorageRead_writeScope},
TokenURL: "https://accounts.google.com/o/oauth2/token",
}
client := authconf.Client(oauth2.NoContext)
service, err = storage.New(client)
if err != nil {
return nil, errors.New("problem saving file to gcs")
}
return
}
// Upload a file to Google Cloud Storage
func UploadGCS(filepath, filename string) (err error) {
service, err := getGCS()
if err != nil {
return
}
file, err := os.Open(filepath)
if err != nil {
return errors.New("problem opening file for gcs")
}
defer file.Close()
object := &storage.Object{
Name: filename,
CacheControl: "public, max-age=31536000",
}
_, err = service.Objects.Insert(config.Settings.Google.Bucket, object).Media(file).Do()
if err != nil {
return
}
return
}
// Delete a file from Google Cloud Storage
func DeleteGCS(object string) (err error) {
service, err := getGCS()
if err != nil {
return
}
err = service.Objects.Delete(config.Settings.Google.Bucket, object).Do()
if err != nil {
return errors.New("problem deleting gcs file")
}
return
}
@Fatiri
Copy link

Fatiri commented Apr 15, 2020

config.Settings.Google.Bucket

this config have declaration or import from ?
ty

@techjanitor
Copy link
Author

@Fatiri it's just a string, the name of the gcs bucket

@djigoio
Copy link

djigoio commented Apr 15, 2021

storage "google.golang.org/api/storage/v1" package is now deprecated, https://pkg.go.dev/cloud.google.com/go/storage should be used here.

@djigoio
Copy link

djigoio commented Apr 15, 2021

storage "google.golang.org/api/storage/v1" package is now deprecated, https://pkg.go.dev/cloud.google.com/go/storage should be used here.

An updated revision, in case you came looking for the same thing as I did!
https://medium.com/google-cloud/golang-copy-to-gcs-check-bucket-58721285788e

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment