This repository has been archived by the owner on Oct 29, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
url.go
112 lines (93 loc) · 1.91 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
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
package rewrite
import (
"bytes"
"net/url"
)
type UrlRewriter struct {
hostRelative bool
fromHost string
pathDepth int
to *url.URL
}
func NewUrlRewriter(from, to string) *UrlRewriter {
f, err := url.Parse(from)
if err != nil {
// TODO - ugh.
panic(err)
}
t, err := url.Parse(to)
if err != nil {
// TODO
panic(err)
}
return &UrlRewriter{
fromHost: f.Host,
to: t,
}
}
// NewRelativeUrlRewriter turns urls that match from's
// hostname into relative urls
func NewRelativeUrlRewriter(from string) *UrlRewriter {
f, err := url.Parse(from)
if err != nil {
// TODO - ugh.
panic(err)
}
return &UrlRewriter{
fromHost: f.Host,
to: &url.URL{},
}
}
func (urw *UrlRewriter) RewriteString(p string) string {
return string(urw.Rewrite([]byte(p)))
}
func (urw *UrlRewriter) Rewrite(p []byte) []byte {
// call to rewrite with empty slice is a no-op
if len(p) == 0 {
return nil
}
u, err := urw.to.Parse(string(p))
if err != nil {
return p
}
if u.Host == urw.fromHost {
u.Host = urw.to.Host
if u.Scheme != urw.to.Scheme {
u.Scheme = urw.to.Scheme
}
}
// if we're rewriting to relative urls, ensure
// empty rewrites to root
// if urw.to.Host == "" && u.Path == "" {
// u.Path = "/"
// }
// relative urls should be "directory relative"
if u.Host == "" {
u.Path = "." + u.Path
}
if urw.hostRelative {
u.Scheme = ""
// rel := u.String()
return append(urw.pathPrefix(), []byte(u.String())[2:]...)
}
return []byte(u.String())
}
func NewHostRelativeUrlRewriter(from string) *UrlRewriter {
f, err := url.Parse(from)
if err != nil {
// TODO - ugh.
panic(err)
}
if f.Path == "" {
f.Path = "/"
}
return &UrlRewriter{
fromHost: f.Host,
hostRelative: true,
pathDepth: bytes.Count([]byte(f.Path), []byte{'/'}),
to: f,
}
}
func (urw *UrlRewriter) pathPrefix() []byte {
return bytes.Repeat([]byte("../"), urw.pathDepth)
}