-
Notifications
You must be signed in to change notification settings - Fork 0
/
redirect.go
53 lines (47 loc) · 997 Bytes
/
redirect.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
package mux
import (
"strconv"
"strings"
"unicode/utf8"
"google.golang.org/genproto/googleapis/api/httpbody"
)
const typeLocation = "Location"
// Redirect response http body with redirect
func Redirect(url string) *httpbody.HttpBody {
return &httpbody.HttpBody{
ContentType: typeLocation,
Data: []byte(hexEscapeNonASCII(url)),
}
}
var htmlReplacer = strings.NewReplacer(
"&", "&",
"<", "<",
">", ">",
// """ is shorter than """.
`"`, """,
// "'" is shorter than "'" and apos was not in HTML until HTML5.
"'", "'",
)
func hexEscapeNonASCII(s string) string {
newLen := 0
for i := 0; i < len(s); i++ {
if s[i] >= utf8.RuneSelf {
newLen += 3
} else {
newLen++
}
}
if newLen == len(s) {
return s
}
b := make([]byte, 0, newLen)
for i := 0; i < len(s); i++ {
if s[i] >= utf8.RuneSelf {
b = append(b, '%')
b = strconv.AppendInt(b, int64(s[i]), 16)
} else {
b = append(b, s[i])
}
}
return string(b)
}