-
Notifications
You must be signed in to change notification settings - Fork 10
/
ctx_func.go
89 lines (78 loc) · 1.88 KB
/
ctx_func.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
package twig
import (
"net"
"net/http"
"reflect"
"strings"
"unsafe"
)
func WriteContentType(w http.ResponseWriter, val string) {
header := w.Header()
if header.Get(HeaderContentType) == "" {
header.Set(HeaderContentType, val)
}
}
func WriteHeaderCode(w http.ResponseWriter, code int) {
w.WriteHeader(code)
}
func IsTLS(r *http.Request) bool {
return r.TLS != nil
}
func Byte(w http.ResponseWriter, code int, contentType string, bs []byte) (err error) {
WriteContentType(w, contentType)
w.WriteHeader(code)
_, err = w.Write(bs)
return
}
func unsafeToBytes(s string) []byte {
strHeader := (*reflect.StringHeader)(unsafe.Pointer(&s))
return *(*[]byte)(unsafe.Pointer(&reflect.SliceHeader{
Data: strHeader.Data,
Len: strHeader.Len,
Cap: strHeader.Len,
}))
}
func String(w http.ResponseWriter, code int, str string) (err error) {
WriteContentType(w, MIMETextPlainCharsetUTF8)
WriteHeaderCode(w, code)
_, err = w.Write(unsafeToBytes(str))
return
}
func IsWebSocket(r *http.Request) bool {
upgrade := r.Header.Get(HeaderUpgrade)
return strings.ToLower(upgrade) == "websocket"
}
func IsXMLHTTPRequest(r *http.Request) bool {
return strings.Contains(
r.Header.Get(HeaderXRequestedWith),
XMLHttpRequest,
)
}
func Scheme(r *http.Request) string {
if IsTLS(r) {
return "https"
}
if scheme := r.Header.Get(HeaderXForwardedProto); scheme != "" {
return scheme
}
if scheme := r.Header.Get(HeaderXForwardedProtocol); scheme != "" {
return scheme
}
if ssl := r.Header.Get(HeaderXForwardedSsl); ssl == "on" {
return "https"
}
if scheme := r.Header.Get(HeaderXUrlScheme); scheme != "" {
return scheme
}
return "http"
}
func RealIP(r *http.Request) string {
if ip := r.Header.Get(HeaderXForwardedFor); ip != "" {
return strings.Split(ip, ", ")[0]
}
if ip := r.Header.Get(HeaderXRealIP); ip != "" {
return ip
}
ra, _, _ := net.SplitHostPort(r.RemoteAddr)
return ra
}