restic/backend/s3/config.go

73 lines
1.7 KiB
Go
Raw Normal View History

2015-12-28 15:51:24 +01:00
package s3
import (
"errors"
2015-12-28 18:23:02 +01:00
"net/url"
2015-12-28 15:51:24 +01:00
"strings"
)
// Config contains all configuration necessary to connect to an s3 compatible
// server.
type Config struct {
2015-12-29 00:27:29 +01:00
Endpoint string
UseHTTP bool
2015-12-28 15:51:24 +01:00
KeyID, Secret string
Bucket string
Prefix string
2015-12-28 15:51:24 +01:00
}
const defaultPrefix = "restic"
2015-12-28 15:51:24 +01:00
// ParseConfig parses the string s and extracts the s3 config. The two
// supported configuration formats are s3://host/bucketname/prefix and
// s3:host:bucketname/prefix. The host can also be a valid s3 region
// name. If no prefix is given the prefix "restic" will be used.
2015-12-28 15:51:24 +01:00
func ParseConfig(s string) (interface{}, error) {
var path []string
cfg := Config{}
2016-02-14 16:01:14 +01:00
switch {
case strings.HasPrefix(s, "s3://"):
2015-12-28 15:51:24 +01:00
s = s[5:]
path = strings.SplitN(s, "/", 3)
cfg.Endpoint = path[0]
path = path[1:]
2016-02-14 16:01:14 +01:00
case strings.HasPrefix(s, "s3:http"):
s = s[3:]
// assume that a URL has been specified, parse it and
// use the host as the endpoint and the path as the
// bucket name and prefix
2015-12-28 18:23:02 +01:00
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-29 00:27:29 +01:00
cfg.Endpoint = url.Host
if url.Scheme == "http" {
cfg.UseHTTP = true
}
path = strings.SplitN(url.Path[1:], "/", 2)
2016-02-14 16:01:14 +01:00
case strings.HasPrefix(s, "s3:"):
s = s[3:]
path = strings.SplitN(s, "/", 3)
cfg.Endpoint = path[0]
path = path[1:]
2016-02-14 16:01:14 +01:00
default:
return nil, errors.New("s3: invalid format")
}
if len(path) < 1 {
return nil, errors.New("s3: invalid format, host/region or bucket name not found")
}
cfg.Bucket = path[0]
if len(path) > 1 {
cfg.Prefix = strings.TrimRight(path[1], "/")
} else {
cfg.Prefix = defaultPrefix
2015-12-28 15:51:24 +01:00
}
return cfg, nil
}