webdavuploader.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package imguploader
  2. import (
  3. "bytes"
  4. "context"
  5. "fmt"
  6. "io/ioutil"
  7. "net"
  8. "net/http"
  9. "net/url"
  10. "path"
  11. "time"
  12. "github.com/grafana/grafana/pkg/util"
  13. )
  14. type WebdavUploader struct {
  15. url string
  16. username string
  17. password string
  18. public_url string
  19. }
  20. var netTransport = &http.Transport{
  21. Proxy: http.ProxyFromEnvironment,
  22. Dial: (&net.Dialer{
  23. Timeout: 60 * time.Second,
  24. DualStack: true,
  25. }).Dial,
  26. TLSHandshakeTimeout: 5 * time.Second,
  27. }
  28. var netClient = &http.Client{
  29. Timeout: time.Second * 60,
  30. Transport: netTransport,
  31. }
  32. func (u *WebdavUploader) Upload(ctx context.Context, pa string) (string, error) {
  33. url, _ := url.Parse(u.url)
  34. filename := util.GetRandomString(20) + ".png"
  35. url.Path = path.Join(url.Path, filename)
  36. imgData, err := ioutil.ReadFile(pa)
  37. if err != nil {
  38. return "", err
  39. }
  40. req, err := http.NewRequest("PUT", url.String(), bytes.NewReader(imgData))
  41. if err != nil {
  42. return "", err
  43. }
  44. if u.username != "" {
  45. req.SetBasicAuth(u.username, u.password)
  46. }
  47. res, err := netClient.Do(req)
  48. if err != nil {
  49. return "", err
  50. }
  51. if res.StatusCode != http.StatusCreated {
  52. body, _ := ioutil.ReadAll(res.Body)
  53. return "", fmt.Errorf("Failed to upload image. Returned statuscode %v body %s", res.StatusCode, body)
  54. }
  55. if u.public_url != "" {
  56. publicURL, _ := url.Parse(u.public_url)
  57. publicURL.Path = path.Join(publicURL.Path, filename)
  58. return publicURL.String(), nil
  59. }
  60. return url.String(), nil
  61. }
  62. func NewWebdavImageUploader(url, username, password, public_url string) (*WebdavUploader, error) {
  63. return &WebdavUploader{
  64. url: url,
  65. username: username,
  66. password: password,
  67. public_url: public_url,
  68. }, nil
  69. }