-
Notifications
You must be signed in to change notification settings - Fork 113
/
Copy pathnormalize.go
114 lines (95 loc) · 2.38 KB
/
normalize.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
107
108
109
110
111
112
113
114
package nostr
import (
"fmt"
"net/url"
"strings"
"github.com/ImVexed/fasturl"
)
// NormalizeURL normalizes the url and replaces http://, https:// schemes with ws://, wss://
// and normalizes the path.
func NormalizeURL(u string) string {
if u == "" {
return ""
}
u = strings.TrimSpace(u)
p, err := fasturl.ParseURL(u)
if err != nil {
return ""
}
// the fabulous case of localhost:1234 that considers "localhost" the protocol and "123" the host
if p.Port == "" && len(p.Protocol) > 5 {
p.Protocol, p.Host, p.Port = "", p.Protocol, p.Host
}
if p.Protocol == "" {
if p.Host == "localhost" || p.Host == "127.0.0.1" {
p.Protocol = "ws"
} else {
p.Protocol = "wss"
}
} else if p.Protocol == "https" {
p.Protocol = "wss"
} else if p.Protocol == "http" {
p.Protocol = "ws"
}
p.Host = strings.ToLower(p.Host)
p.Path = strings.TrimRight(p.Path, "/")
var buf strings.Builder
buf.Grow(
len(p.Protocol) + 3 + len(p.Host) + 1 + len(p.Port) + len(p.Path) + 1 + len(p.Query),
)
buf.WriteString(p.Protocol)
buf.WriteString("://")
buf.WriteString(p.Host)
if p.Port != "" {
buf.WriteByte(':')
buf.WriteString(p.Port)
}
buf.WriteString(p.Path)
if p.Query != "" {
buf.WriteByte('?')
buf.WriteString(p.Query)
}
return buf.String()
}
// NormalizeHTTPURL does normalization of http(s):// URLs according to rfc3986. Don't use for relay URLs.
func NormalizeHTTPURL(s string) (string, error) {
s = strings.TrimSpace(s)
if !strings.HasPrefix(s, "http") {
s = "https://" + s
}
u, err := url.Parse(s)
if err != nil {
return s, err
}
if u.Scheme == "" {
u, err = url.Parse("http://" + s)
if err != nil {
return s, err
}
}
if strings.HasPrefix(s, "//") {
s = "http:" + s
}
var p int
switch u.Scheme {
case "http":
p = 80
case "https":
p = 443
}
u.Host = strings.TrimSuffix(u.Host, fmt.Sprintf(":%d", p))
v := u.Query()
u.RawQuery = v.Encode()
u.RawQuery, _ = url.QueryUnescape(u.RawQuery)
h := u.String()
h = strings.TrimSuffix(h, "/")
return h, nil
}
// NormalizeOKMessage takes a string message that is to be sent in an `OK` or `CLOSED` command
// and prefixes it with "<prefix>: " if it doesn't already have an acceptable prefix.
func NormalizeOKMessage(reason string, prefix string) string {
if idx := strings.Index(reason, ": "); idx == -1 || strings.IndexByte(reason[0:idx], ' ') != -1 {
return prefix + ": " + reason
}
return reason
}