forked from grafana/grafana
-
Notifications
You must be signed in to change notification settings - Fork 0
/
webdavuploader.go
51 lines (40 loc) · 1.01 KB
/
webdavuploader.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package imguploader
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"path"
"github.com/grafana/grafana/pkg/util"
)
type WebdavUploader struct {
url string
username string
password string
}
func (u *WebdavUploader) Upload(pa string) (string, error) {
url, _ := url.Parse(u.url)
url.Path = path.Join(url.Path, util.GetRandomString(20)+".png")
imgData, err := ioutil.ReadFile(pa)
req, err := http.NewRequest("PUT", url.String(), bytes.NewReader(imgData))
if u.username != "" {
req.SetBasicAuth(u.username, u.password)
}
res, err := http.DefaultClient.Do(req)
if err != nil {
return "", err
}
if res.StatusCode != http.StatusCreated {
body, _ := ioutil.ReadAll(res.Body)
return "", fmt.Errorf("Failed to upload image. Returned statuscode %v body %s", res.StatusCode, body)
}
return url.String(), nil
}
func NewWebdavImageUploader(url, username, passwrod string) (*WebdavUploader, error) {
return &WebdavUploader{
url: url,
username: username,
password: passwrod,
}, nil
}