webdavuploader.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. }).Dial,
  25. TLSHandshakeTimeout: 5 * time.Second,
  26. }
  27. var netClient = &http.Client{
  28. Timeout: time.Second * 60,
  29. Transport: netTransport,
  30. }
  31. func (u *WebdavUploader) Upload(ctx context.Context, pa string) (string, error) {
  32. url, _ := url.Parse(u.url)
  33. filename := util.GetRandomString(20) + ".png"
  34. url.Path = path.Join(url.Path, filename)
  35. imgData, err := ioutil.ReadFile(pa)
  36. req, err := http.NewRequest("PUT", url.String(), bytes.NewReader(imgData))
  37. if u.username != "" {
  38. req.SetBasicAuth(u.username, u.password)
  39. }
  40. res, err := netClient.Do(req)
  41. if err != nil {
  42. return "", err
  43. }
  44. if res.StatusCode != http.StatusCreated {
  45. body, _ := ioutil.ReadAll(res.Body)
  46. return "", fmt.Errorf("Failed to upload image. Returned statuscode %v body %s", res.StatusCode, body)
  47. }
  48. if u.public_url != "" {
  49. publicURL, _ := url.Parse(u.public_url)
  50. publicURL.Path = path.Join(publicURL.Path, filename)
  51. return publicURL.String(), nil
  52. }
  53. return url.String(), nil
  54. }
  55. func NewWebdavImageUploader(url, username, password, public_url string) (*WebdavUploader, error) {
  56. return &WebdavUploader{
  57. url: url,
  58. username: username,
  59. password: password,
  60. public_url: public_url,
  61. }, nil
  62. }