-
Notifications
You must be signed in to change notification settings - Fork 239
/
detect_s3.go
76 lines (62 loc) · 2.12 KB
/
detect_s3.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
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package getter
import (
"fmt"
"net/url"
"strings"
)
// S3Detector implements Detector to detect S3 URLs and turn
// them into URLs that the S3 getter can understand.
type S3Detector struct{}
func (d *S3Detector) Detect(src, _ string) (string, bool, error) {
if len(src) == 0 {
return "", false, nil
}
if strings.Contains(src, ".amazonaws.com/") {
return d.detectHTTP(src)
}
return "", false, nil
}
func (d *S3Detector) detectHTTP(src string) (string, bool, error) {
parts := strings.Split(src, "/")
if len(parts) < 2 {
return "", false, fmt.Errorf(
"URL is not a valid S3 URL")
}
hostParts := strings.Split(parts[0], ".")
if len(hostParts) == 3 {
return d.detectPathStyle(hostParts[0], parts[1:])
} else if len(hostParts) == 4 {
return d.detectVhostStyle(hostParts[1], hostParts[0], parts[1:])
} else if len(hostParts) == 5 && hostParts[1] == "s3" {
return d.detectNewVhostStyle(hostParts[2], hostParts[0], parts[1:])
} else {
return "", false, fmt.Errorf(
"URL is not a valid S3 URL")
}
}
func (d *S3Detector) detectPathStyle(region string, parts []string) (string, bool, error) {
urlStr := fmt.Sprintf("https://%s.amazonaws.com/%s", region, strings.Join(parts, "/"))
url, err := url.Parse(urlStr)
if err != nil {
return "", false, fmt.Errorf("error parsing S3 URL: %s", err)
}
return "s3::" + url.String(), true, nil
}
func (d *S3Detector) detectVhostStyle(region, bucket string, parts []string) (string, bool, error) {
urlStr := fmt.Sprintf("https://%s.amazonaws.com/%s/%s", region, bucket, strings.Join(parts, "/"))
url, err := url.Parse(urlStr)
if err != nil {
return "", false, fmt.Errorf("error parsing S3 URL: %s", err)
}
return "s3::" + url.String(), true, nil
}
func (d *S3Detector) detectNewVhostStyle(region, bucket string, parts []string) (string, bool, error) {
urlStr := fmt.Sprintf("https://s3.%s.amazonaws.com/%s/%s", region, bucket, strings.Join(parts, "/"))
url, err := url.Parse(urlStr)
if err != nil {
return "", false, fmt.Errorf("error parsing S3 URL: %s", err)
}
return "s3::" + url.String(), true, nil
}