forked from grafana/grafana
-
Notifications
You must be signed in to change notification settings - Fork 0
/
webdavuploader.go
83 lines (69 loc) · 1.64 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package imguploader
import (
"bytes"
"context"
"fmt"
"io/ioutil"
"net"
"net/http"
"net/url"
"path"
"time"
"github.com/grafana/grafana/pkg/util"
)
type WebdavUploader struct {
url string
username string
password string
public_url string
}
var netTransport = &http.Transport{
Proxy: http.ProxyFromEnvironment,
Dial: (&net.Dialer{
Timeout: 60 * time.Second,
DualStack: true,
}).Dial,
TLSHandshakeTimeout: 5 * time.Second,
}
var netClient = &http.Client{
Timeout: time.Second * 60,
Transport: netTransport,
}
func (u *WebdavUploader) Upload(ctx context.Context, pa string) (string, error) {
url, _ := url.Parse(u.url)
filename := util.GetRandomString(20) + ".png"
url.Path = path.Join(url.Path, filename)
imgData, err := ioutil.ReadFile(pa)
if err != nil {
return "", err
}
req, err := http.NewRequest("PUT", url.String(), bytes.NewReader(imgData))
if err != nil {
return "", err
}
if u.username != "" {
req.SetBasicAuth(u.username, u.password)
}
res, err := netClient.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)
}
if u.public_url != "" {
publicURL, _ := url.Parse(u.public_url)
publicURL.Path = path.Join(publicURL.Path, filename)
return publicURL.String(), nil
}
return url.String(), nil
}
func NewWebdavImageUploader(url, username, password, public_url string) (*WebdavUploader, error) {
return &WebdavUploader{
url: url,
username: username,
password: password,
public_url: public_url,
}, nil
}