webdavuploader.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. }).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) PublicURL(filename string) string {
  33. if strings.Contains(u.public_url, "${file}") {
  34. return strings.Replace(u.public_url, "${file}", filename, -1)
  35. }
  36. publicURL, _ := url.Parse(u.public_url)
  37. publicURL.Path = path.Join(publicURL.Path, filename)
  38. return publicURL.String()
  39. }
  40. func (u *WebdavUploader) Upload(ctx context.Context, pa string) (string, error) {
  41. url, _ := url.Parse(u.url)
  42. filename := util.GetRandomString(20) + ".png"
  43. url.Path = path.Join(url.Path, filename)
  44. imgData, err := ioutil.ReadFile(pa)
  45. if err != nil {
  46. return "", err
  47. }
  48. req, err := http.NewRequest("PUT", url.String(), bytes.NewReader(imgData))
  49. if err != nil {
  50. return "", err
  51. }
  52. if u.username != "" {
  53. req.SetBasicAuth(u.username, u.password)
  54. }
  55. res, err := netClient.Do(req)
  56. if err != nil {
  57. return "", err
  58. }
  59. if res.StatusCode != http.StatusCreated {
  60. body, _ := ioutil.ReadAll(res.Body)
  61. return "", fmt.Errorf("Failed to upload image. Returned statuscode %v body %s", res.StatusCode, body)
  62. }
  63. if u.public_url != "" {
  64. return u.PublicURL(filename), nil
  65. }
  66. return url.String(), nil
  67. }
  68. func NewWebdavImageUploader(url, username, password, public_url string) (*WebdavUploader, error) {
  69. return &WebdavUploader{
  70. url: url,
  71. username: username,
  72. password: password,
  73. public_url: public_url,
  74. }, nil
  75. }