webdavuploader.go 1.2 KB

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