Skip to content

Instantly share code, notes, and snippets.

@alxschwarz
Forked from techjanitor/gcs.go
Created February 17, 2017 12:57
Show Gist options
  • Save alxschwarz/00068aa4b3b4cfe070809da74f609626 to your computer and use it in GitHub Desktop.
Save alxschwarz/00068aa4b3b4cfe070809da74f609626 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: "[email protected]",
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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment