-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathparse.go
65 lines (58 loc) · 1.67 KB
/
parse.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
package gcsemu
import (
"net/url"
"regexp"
)
const (
// example: "/storage/v1/b/my-bucket/o/2013-tax-returns.pdf" (for a file) or "/storage/v1/b/my-bucket/o" (for a bucket)
gcsObjectPathPattern = "/storage/v1/b/([^\\/]+)/o(?:/(.+))?"
// example: "//b/my-bucket/o/2013-tax-returns.pdf" (for a file) or "/b/my-bucket/o" (for a bucket)
gcsObjectPathPattern2 = "/b/([^\\/]+)/o(?:/(.+))?"
// example: "/storage/v1/b/my-bucket
gcsBucketPathPattern = "/storage/v1/b(?:/([^\\/]+))?"
// example: "/my-bucket/2013-tax-returns.pdf" (for a file)
gcsStoragePathPattern = "/([^\\/]+)/(.+)"
)
var (
gcsObjectPathRegex = regexp.MustCompile(gcsObjectPathPattern)
gcsObjectPathRegex2 = regexp.MustCompile(gcsObjectPathPattern2)
gcsBucketPathRegex = regexp.MustCompile(gcsBucketPathPattern)
gcsStoragePathRegex = regexp.MustCompile(gcsStoragePathPattern)
)
// GcsParams represent a parsed GCS url.
type GcsParams struct {
Bucket string
Object string
IsPublic bool
}
// ParseGcsUrl parses a GCS url.
func ParseGcsUrl(u *url.URL) (*GcsParams, bool) {
if g, ok := parseGcsUrl(gcsObjectPathRegex, u); ok {
return g, true
}
if g, ok := parseGcsUrl(gcsBucketPathRegex, u); ok {
return g, true
}
if g, ok := parseGcsUrl(gcsObjectPathRegex2, u); ok {
return g, true
}
if g, ok := parseGcsUrl(gcsStoragePathRegex, u); ok {
g.IsPublic = true
return g, true
}
return nil, false
}
func parseGcsUrl(re *regexp.Regexp, u *url.URL) (*GcsParams, bool) {
submatches := re.FindStringSubmatch(u.Path)
if submatches == nil {
return nil, false
}
g := &GcsParams{}
if len(submatches) > 1 {
g.Bucket = submatches[1]
}
if len(submatches) > 2 {
g.Object = submatches[2]
}
return g, true
}