-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathurl_test.go
106 lines (90 loc) · 2.35 KB
/
url_test.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package examples
import (
"testing"
"github.com/a-h/lexical/input"
"github.com/a-h/lexical/parse"
)
func TestURLParsing(t *testing.T) {
tests := []struct {
input string
expectedMatch bool
expectedValue URL
}{
{
input: "example.com",
expectedMatch: true,
expectedValue: URL{
Host: "example.com",
},
},
{
input: "example.co.uk/",
expectedMatch: true,
expectedValue: URL{
Host: "example.co.uk",
Path: "/",
},
},
{
input: "example.com:80/path",
expectedMatch: true,
expectedValue: URL{
Host: "example.com:80",
Path: "/path",
},
},
}
for _, test := range tests {
ip := input.NewFromString(test.input)
result := url(ip)
if result.Success != test.expectedMatch {
t.Errorf("for input '%v', expected success '%v', but was %v", test.input, test.expectedMatch, result.Success)
}
if result.Item != test.expectedValue {
t.Errorf("for input '%v', expected sucess '%v', but was %v", test.input, test.expectedValue, result.Item)
}
}
}
type URL struct {
Host string
Path string
}
var head = parse.Any(parse.Letter, parse.ZeroToNine)
var tailCharacter = parse.Any(parse.Letter, parse.ZeroToNine, parse.Rune('-'))
var tail = parse.Many(parse.WithStringConcatCombiner, 0, 63, tailCharacter)
var host = parse.All(parse.WithStringConcatCombiner, head, tail)
var singleTLD = parse.All(parse.WithStringConcatCombiner,
parse.Rune('.'),
parse.Many(parse.WithStringConcatCombiner, 0, 3, head),
)
var allTLDs = parse.Many(parse.WithStringConcatCombiner, 1, 2, singleTLD)
var port = parse.Many(parse.WithStringConcatCombiner, 0, 1,
parse.All(parse.WithStringConcatCombiner,
parse.Rune(':'),
parse.Many(parse.WithStringConcatCombiner, 1, 5, parse.ZeroToNine),
),
)
var domain = parse.All(parse.WithStringConcatCombiner,
host,
allTLDs,
port,
)
var path = parse.All(parse.WithStringConcatCombiner,
parse.Rune('/'),
parse.Many(parse.WithStringConcatCombiner,
0, // minimum match count
65536, // maximum match count
parse.AnyRune()),
)
var optionalPath = parse.Optional(parse.WithStringConcatCombiner, path)
func urlParser(results []interface{}) (rv interface{}, ok bool) {
host, _ := results[0].(string)
path, _ := results[1].(string)
ok = true
url := URL{
Host: host,
Path: path,
}
return url, ok
}
var url = parse.All(urlParser, domain, optionalPath)