/
identification.go
83 lines (67 loc) · 2 KB
/
identification.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
77
78
79
80
81
82
83
package urlidentification
import (
"errors"
// "fmt"
"net/url"
"strings"
)
const (
Unidentifiable = iota
Absolute = iota
NetworkPathReference = iota
RelativeReferenceWithAbsolutePath = iota
RelativePathReference = iota
)
// I based my nomenclature on this SO answer: http://stackoverflow.com/a/17407082/242404
func hasNoScheme(url *url.URL) bool {
return url.Scheme == ""
}
func hasHost(url *url.URL) bool {
return url.Host != ""
}
func hasNoHost(url *url.URL) bool {
return !hasHost(url)
}
func startsWithDoubleSlash(url *url.URL) bool {
return strings.HasPrefix(url.String(), "//")
}
func startsWithSlash(url *url.URL) bool {
return strings.HasPrefix(url.String(), "/")
}
func pathStartsWithSingleSlash(url *url.URL) bool {
return startsWithSlash(url) && !startsWithDoubleSlash(url)
}
// Exported functions:
func IsAbsoluteURL(url *url.URL) bool {
return url.IsAbs()
}
func IsNetworkPathReferenceURL(url *url.URL) bool {
return hasNoScheme(url) && hasHost(url) && startsWithDoubleSlash(url)
}
// Returns whether the URL looks like /subdir/page.html
func IsRelativeReferenceWithAbsolutePathURL(url *url.URL) bool {
return hasNoHost(url) && pathStartsWithSingleSlash(url)
}
func IsRelativePathReferenceURL(url *url.URL) bool {
return hasNoScheme(url) && hasNoHost(url) && !strings.HasPrefix(url.Path, "/")
}
func Identify(url *url.URL) (int, error) {
if IsAbsoluteURL(url) {
return Absolute, nil
} else if IsNetworkPathReferenceURL(url) {
return NetworkPathReference, nil
} else if IsRelativeReferenceWithAbsolutePathURL(url) {
return RelativeReferenceWithAbsolutePath, nil
} else if IsRelativePathReferenceURL(url) {
return RelativePathReference, nil
} else {
return Unidentifiable, errors.New("urlidentification: URL pattern is Unidentifiable")
}
}
func IdentifyURLString(urlString string) (int, error) {
parsedURL, err := url.Parse(urlString)
if err != nil {
return Unidentifiable, err
}
return Identify(parsedURL)
}