2
2
mirror of https://github.com/octoleo/restic.git synced 2024-12-26 04:17:29 +00:00
restic/backend/s3/config.go

82 lines
1.7 KiB
Go
Raw Normal View History

2015-12-28 14:51:24 +00:00
package s3
import (
"errors"
2015-12-28 17:23:02 +00:00
"net/url"
2015-12-28 14:51:24 +00:00
"strings"
)
// Config contains all configuration necessary to connect to an s3 compatible
// server.
type Config struct {
2015-12-28 23:27:29 +00:00
Endpoint string
UseHTTP bool
2015-12-28 14:51:24 +00:00
KeyID, Secret string
Bucket string
}
// ParseConfig parses the string s and extracts the s3 config. The two
// supported configuration formats are s3://host/bucketname and
// s3:host:bucketname. The host can also be a valid s3 region name.
func ParseConfig(s string) (interface{}, error) {
if strings.HasPrefix(s, "s3://") {
s = s[5:]
data := strings.SplitN(s, "/", 2)
if len(data) != 2 {
return nil, errors.New("s3: invalid format, host/region or bucket name not found")
}
cfg := Config{
2015-12-28 23:27:29 +00:00
Endpoint: data[0],
Bucket: data[1],
2015-12-28 14:51:24 +00:00
}
return cfg, nil
}
2015-12-28 17:23:02 +00:00
data := strings.SplitN(s, ":", 2)
if len(data) != 2 {
2015-12-28 14:51:24 +00:00
return nil, errors.New("s3: invalid format")
}
if data[0] != "s3" {
return nil, errors.New(`s3: config does not start with "s3"`)
}
2015-12-28 17:23:02 +00:00
s = data[1]
cfg := Config{}
rest := strings.Split(s, "/")
if len(rest) < 2 {
return nil, errors.New("s3: region or bucket not found")
}
if len(rest) == 2 {
// assume that just a region name and a bucket has been specified, in
// the format region/bucket
2015-12-28 23:27:29 +00:00
cfg.Endpoint = rest[0]
2015-12-28 17:23:02 +00:00
cfg.Bucket = rest[1]
} else {
// assume that a URL has been specified, parse it and use the path as
// the bucket name.
url, err := url.Parse(s)
if err != nil {
return nil, err
}
if url.Path == "" {
return nil, errors.New("s3: bucket name not found")
}
2015-12-28 23:27:29 +00:00
cfg.Endpoint = url.Host
if url.Scheme == "http" {
cfg.UseHTTP = true
}
2015-12-28 17:23:02 +00:00
2015-12-28 23:27:29 +00:00
cfg.Bucket = url.Path[1:]
2015-12-28 14:51:24 +00:00
}
return cfg, nil
}