-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathurl.go
78 lines (66 loc) · 1.3 KB
/
url.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
// Copyright (c) 2015-2020, go_eddystone authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package eddystone
import (
"errors"
"strings"
)
var urlSchemePrefix = []string{
"http://www.",
"https://www.",
"http://",
"https://",
}
var urlEncoding = []string{
".com/",
".org/",
".edu/",
".net/",
".info/",
".biz/",
".gov/",
".com",
".org",
".edu",
".net",
".info",
".biz",
".gov",
}
func encodeURL(u string) (byte, []byte, error) {
prefix := byte(0x02) // http://
for i, v := range urlSchemePrefix {
if strings.HasPrefix(u, v) {
prefix = byte(i)
u = u[len(v):]
break
}
}
for i, v := range urlEncoding {
u = strings.Replace(u, v, string(byte(i)), -1)
}
if len(u) > 17 {
return 0x00, nil, errors.New("url too long")
}
return prefix, []byte(u), nil
}
func decodeURL(prefix byte, encodedURL []byte) (string, error) {
if int(prefix) >= len(urlSchemePrefix) {
return "", errors.New("invaild prefix")
}
s := urlSchemePrefix[prefix]
for _, b := range encodedURL {
switch {
case 0x00 <= b && b <= 0x13:
s += urlEncoding[b]
case 0x0e <= b && b <= 0x20:
fallthrough
case 0x7f <= b && b <= 0xff:
return "", errors.New("invalid byte")
default:
s += string(b)
}
}
return s, nil
}