...
1 package internal
2
3 import (
4 "net/url"
5 "regexp"
6 "strings"
7 )
8
9 const (
10 defaultHTTPPort = ":80"
11 defaultHTTPSPort = ":443"
12 )
13
14
15 var rxPort = regexp.MustCompile(`(:\d+)/?$`)
16 var rxDupSlashes = regexp.MustCompile(`/{2,}`)
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31 func NormalizeURL(u *url.URL) {
32 lowercaseScheme(u)
33 lowercaseHost(u)
34 removeDefaultPort(u)
35 removeDuplicateSlashes(u)
36
37 u.RawPath = ""
38 u.RawFragment = ""
39 }
40
41 func lowercaseScheme(u *url.URL) {
42 if len(u.Scheme) > 0 {
43 u.Scheme = strings.ToLower(u.Scheme)
44 }
45 }
46
47 func lowercaseHost(u *url.URL) {
48 if len(u.Host) > 0 {
49 u.Host = strings.ToLower(u.Host)
50 }
51 }
52
53 func removeDefaultPort(u *url.URL) {
54 if len(u.Host) > 0 {
55 scheme := strings.ToLower(u.Scheme)
56 u.Host = rxPort.ReplaceAllStringFunc(u.Host, func(val string) string {
57 if (scheme == "http" && val == defaultHTTPPort) || (scheme == "https" && val == defaultHTTPSPort) {
58 return ""
59 }
60 return val
61 })
62 }
63 }
64
65 func removeDuplicateSlashes(u *url.URL) {
66 if len(u.Path) > 0 {
67 u.Path = rxDupSlashes.ReplaceAllString(u.Path, "/")
68 }
69 }
70
View as plain text