gcpuploader.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package imguploader
  2. import (
  3. "cloud.google.com/go/storage"
  4. "fmt"
  5. "github.com/grafana/grafana/pkg/log"
  6. "github.com/grafana/grafana/pkg/util"
  7. "golang.org/x/net/context"
  8. "google.golang.org/api/option"
  9. "io/ioutil"
  10. )
  11. type GCPUploader struct {
  12. keyFile string
  13. bucket string
  14. log log.Logger
  15. }
  16. func NewGCPUploader(keyFile, bucket string) *GCPUploader {
  17. return &GCPUploader{
  18. keyFile: keyFile,
  19. bucket: bucket,
  20. log: log.New("gcpuploader"),
  21. }
  22. }
  23. func (u *GCPUploader) Upload(imageDiskPath string) (string, error) {
  24. ctx := context.Background()
  25. client, err := storage.NewClient(ctx, option.WithServiceAccountFile(u.keyFile))
  26. if err != nil {
  27. return "", err
  28. }
  29. key := util.GetRandomString(20) + ".png"
  30. log.Debug("Uploading image to GCP bucket = %s key = %s", u.bucket, key)
  31. file, err := ioutil.ReadFile(imageDiskPath)
  32. if err != nil {
  33. return "", err
  34. }
  35. wc := client.Bucket(u.bucket).Object(key).NewWriter(ctx)
  36. wc.ContentType = "image/png"
  37. wc.ACL = []storage.ACLRule{{Entity: storage.AllUsers, Role: storage.RoleReader}}
  38. if _, err := wc.Write(file); err != nil {
  39. return "", err
  40. }
  41. if err := wc.Close(); err != nil {
  42. return "", err
  43. }
  44. return fmt.Sprintf("https://storage.googleapis.com/%s/%s", u.bucket, key), nil
  45. }