-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontext.go
122 lines (104 loc) · 2.35 KB
/
context.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
115
116
117
118
119
120
121
122
package h2o
import (
"context"
"net"
"net/http"
"path"
"strings"
"text/template"
"github.com/go-playground/form"
"github.com/unrolled/render"
validator "gopkg.in/go-playground/validator.v9"
)
// K key type
type K string
// H hash
type H map[string]interface{}
// Context context
type Context struct {
Writer http.ResponseWriter
Request *http.Request
vars map[string]string
val *validator.Validate
dec *form.Decoder
rdr *render.Render
}
// Set set
func (p *Context) Set(k string, v interface{}) {
p.Request = p.Request.WithContext(
context.WithValue(p.Request.Context(), K(k), v),
)
}
// Get get
func (p *Context) Get(k string) interface{} {
return p.Request.Context().Value(K(k))
}
// Redirect redirect
func (p *Context) Redirect(code int, url string) {
http.Redirect(p.Writer, p.Request, url, code)
}
// SetHeader set header
func (p *Context) SetHeader(k, v string) {
p.Request.Header.Set(k, v)
}
// GetHeader get header
func (p *Context) GetHeader(k string) string {
return p.Request.Header.Get(k)
}
// Param the value of the URL param.
func (p *Context) Param(k string) string {
return p.vars[k]
}
// ClientIP client ip
func (p *Context) ClientIP() string {
// -------------
if ip := strings.TrimSpace(p.GetHeader("X-Real-Ip")); ip != "" {
return ip
}
// -------------
ip := p.GetHeader("X-Forwarded-For")
if idx := strings.IndexByte(ip, ','); idx >= 0 {
ip = ip[0:idx]
}
ip = strings.TrimSpace(ip)
if ip != "" {
return ip
}
// -------------
if ip, _, err := net.SplitHostPort(strings.TrimSpace(p.Request.RemoteAddr)); err == nil {
return ip
}
// -----------
return ""
}
// JSON write json
func (p *Context) JSON(s int, v interface{}) error {
return p.rdr.JSON(p.Writer, s, v)
}
// XML write xml
func (p *Context) XML(s int, v interface{}) error {
return p.rdr.XML(p.Writer, s, v)
}
// HTML write html
func (p *Context) HTML(s int, t string, v interface{}) error {
return p.rdr.HTML(p.Writer, s, t, v)
}
// TEXT parse text template
func (p *Context) TEXT(s int, n string, v interface{}) error {
t, e := template.ParseFiles(path.Join("templates", n))
if e != nil {
return e
}
return t.Execute(p.Writer, v)
}
// Bind binds the passed struct pointer
func (p *Context) Bind(v interface{}) error {
e := p.Request.ParseForm()
if e == nil {
e = p.dec.Decode(v, p.Request.Form)
}
if e == nil {
e = p.val.Struct(v)
}
return e
}