/
uri.go
64 lines (58 loc) · 1.08 KB
/
uri.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
package uniquefile
import (
"net/url"
"strings"
)
const (
FileScheme = "file"
)
// URI defines a resource that can be queried to obtain its indicators.
type URI struct {
Scheme string
Hostname string
Path string
Query string
}
func (u *URI) FromString(s string) error {
ur, err := url.Parse(s)
if err != nil {
return err
}
u.FromURL(ur)
return nil
}
func (u *URI) FromURL(ur *url.URL) {
u.Scheme = ur.Scheme
if u.Scheme == "" {
u.Scheme = FileScheme
}
u.Hostname = ur.Host
if ur.Opaque != "" {
u.Path = ur.Opaque
} else {
u.Path = ur.EscapedPath()
}
u.Query = ur.Query().Encode()
}
func (u *URI) String() string {
parts := [...]string{
u.Scheme,
":",
"", // maybe two slashes
u.Hostname,
"", // maybe slash
u.Path,
"", // maybe ?
u.Query,
}
if u.Query != "" && !strings.HasPrefix(u.Query, "?") {
parts[len(parts)-2] = "?"
}
if u.Hostname != "" {
parts[2] = "//"
if u.Path != "" && !strings.HasPrefix(u.Path, "/") {
parts[4] = "/"
}
}
return strings.Join(parts[:], "")
}