forked from grafana/grafana
-
Notifications
You must be signed in to change notification settings - Fork 0
/
imguploader.go
92 lines (75 loc) · 2.14 KB
/
imguploader.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
84
85
86
87
88
89
90
91
92
package imguploader
import (
"fmt"
"regexp"
"github.com/grafana/grafana/pkg/setting"
)
type ImageUploader interface {
Upload(path string) (string, error)
}
type NopImageUploader struct {
}
func (NopImageUploader) Upload(path string) (string, error) {
return "", nil
}
func NewImageUploader() (ImageUploader, error) {
switch setting.ImageUploadProvider {
case "s3":
s3sec, err := setting.Cfg.GetSection("external_image_storage.s3")
if err != nil {
return nil, err
}
bucketUrl := s3sec.Key("bucket_url").MustString("")
accessKey := s3sec.Key("access_key").MustString("")
secretKey := s3sec.Key("secret_key").MustString("")
info, err := getRegionAndBucketFromUrl(bucketUrl)
if err != nil {
return nil, err
}
return NewS3Uploader(info.region, info.bucket, "public-read", accessKey, secretKey), nil
case "webdav":
webdavSec, err := setting.Cfg.GetSection("external_image_storage.webdav")
if err != nil {
return nil, err
}
url := webdavSec.Key("url").String()
if url == "" {
return nil, fmt.Errorf("Could not find url key for image.uploader.webdav")
}
public_url := webdavSec.Key("public_url").String()
username := webdavSec.Key("username").String()
password := webdavSec.Key("password").String()
return NewWebdavImageUploader(url, username, password, public_url)
}
return NopImageUploader{}, nil
}
type s3Info struct {
region string
bucket string
}
func getRegionAndBucketFromUrl(url string) (*s3Info, error) {
info := &s3Info{}
urlRegex := regexp.MustCompile(`https?:\/\/(.*)\.s3(-([^.]+))?\.amazonaws\.com\/?`)
matches := urlRegex.FindStringSubmatch(url)
if len(matches) > 0 {
info.bucket = matches[1]
if matches[3] != "" {
info.region = matches[3]
} else {
info.region = "us-east-1"
}
return info, nil
}
urlRegex2 := regexp.MustCompile(`https?:\/\/s3(-([^.]+))?\.amazonaws\.com\/(.*)?`)
matches2 := urlRegex2.FindStringSubmatch(url)
if len(matches2) > 0 {
info.bucket = matches2[3]
if matches2[2] != "" {
info.region = matches2[2]
} else {
info.region = "us-east-1"
}
return info, nil
}
return nil, fmt.Errorf("Could not find bucket setting for image.uploader.s3")
}