webdavuploader.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. req, err := http.NewRequest("PUT", url.String(), bytes.NewReader(imgData))
  38. if u.username != "" {
  39. req.SetBasicAuth(u.username, u.password)
  40. }
  41. res, err := netClient.Do(req)
  42. if err != nil {
  43. return "", err
  44. }
  45. if res.StatusCode != http.StatusCreated {
  46. body, _ := ioutil.ReadAll(res.Body)
  47. return "", fmt.Errorf("Failed to upload image. Returned statuscode %v body %s", res.StatusCode, body)
  48. }
  49. if u.public_url != "" {
  50. publicURL, _ := url.Parse(u.public_url)
  51. publicURL.Path = path.Join(publicURL.Path, filename)
  52. return publicURL.String(), nil
  53. }
  54. return url.String(), nil
  55. }
  56. func NewWebdavImageUploader(url, username, password, public_url string) (*WebdavUploader, error) {
  57. return &WebdavUploader{
  58. url: url,
  59. username: username,
  60. password: password,
  61. public_url: public_url,
  62. }, nil
  63. }