webdavuploader.go 1.9 KB

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