Created
May 9, 2015 04:08
-
-
Save techjanitor/993172582e48d19093a3 to your computer and use it in GitHub Desktop.
Upload a file to Google Cloud Storage
This file contains hidden or 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 ( | |
"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 | |
} |
@Fatiri it's just a string, the name of the gcs bucket
storage "google.golang.org/api/storage/v1" package is now deprecated, https://pkg.go.dev/cloud.google.com/go/storage should be used here.
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
config.Settings.Google.Bucket
this config have declaration or import from ?
ty