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