gcsuploader.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package imguploader
  2. import (
  3. "context"
  4. "fmt"
  5. "io/ioutil"
  6. "net/http"
  7. "os"
  8. "path"
  9. "github.com/grafana/grafana/pkg/log"
  10. "github.com/grafana/grafana/pkg/util"
  11. "golang.org/x/oauth2/google"
  12. )
  13. const (
  14. tokenUrl string = "https://www.googleapis.com/auth/devstorage.read_write"
  15. uploadUrl string = "https://www.googleapis.com/upload/storage/v1/b/%s/o?uploadType=media&name=%s&predefinedAcl=publicRead"
  16. )
  17. type GCSUploader struct {
  18. keyFile string
  19. bucket string
  20. path string
  21. log log.Logger
  22. }
  23. func NewGCSUploader(keyFile, bucket, path string) *GCSUploader {
  24. return &GCSUploader{
  25. keyFile: keyFile,
  26. bucket: bucket,
  27. path: path,
  28. log: log.New("gcsuploader"),
  29. }
  30. }
  31. func (u *GCSUploader) Upload(ctx context.Context, imageDiskPath string) (string, error) {
  32. fileName := util.GetRandomString(20) + ".png"
  33. key := path.Join(u.path, fileName)
  34. u.log.Debug("Opening key file ", u.keyFile)
  35. data, err := ioutil.ReadFile(u.keyFile)
  36. if err != nil {
  37. return "", err
  38. }
  39. u.log.Debug("Creating JWT conf")
  40. conf, err := google.JWTConfigFromJSON(data, tokenUrl)
  41. if err != nil {
  42. return "", err
  43. }
  44. u.log.Debug("Creating HTTP client")
  45. client := conf.Client(ctx)
  46. err = u.uploadFile(client, imageDiskPath, key)
  47. if err != nil {
  48. return "", err
  49. }
  50. return fmt.Sprintf("https://storage.googleapis.com/%s/%s", u.bucket, key), nil
  51. }
  52. func (u *GCSUploader) uploadFile(client *http.Client, imageDiskPath, key string) error {
  53. u.log.Debug("Opening image file ", imageDiskPath)
  54. fileReader, err := os.Open(imageDiskPath)
  55. if err != nil {
  56. return err
  57. }
  58. reqUrl := fmt.Sprintf(uploadUrl, u.bucket, key)
  59. u.log.Debug("Request URL: ", reqUrl)
  60. req, err := http.NewRequest("POST", reqUrl, fileReader)
  61. if err != nil {
  62. return err
  63. }
  64. req.Header.Add("Content-Type", "image/png")
  65. u.log.Debug("Sending POST request to GCS")
  66. resp, err := client.Do(req)
  67. if err != nil {
  68. return err
  69. }
  70. if resp.StatusCode != 200 {
  71. return fmt.Errorf("GCS response status code %d", resp.StatusCode)
  72. }
  73. return nil
  74. }