-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontext.go
More file actions
304 lines (273 loc) · 6.56 KB
/
context.go
File metadata and controls
304 lines (273 loc) · 6.56 KB
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
package middleware
import (
"encoding/json"
"errors"
"fmt"
"html/template"
"io/ioutil"
"net/http"
"strings"
"time"
)
// Context 上下文数据结构
type Context struct {
Request *http.Request
Response http.ResponseWriter
body []byte
tpl *template.Template
restProcessors []func(model interface{}) interface{}
writeable bool
code int
Message I18n
EnableI18n bool
pathParams map[string]string
}
type I18n struct {
Cn map[string]string
En map[string]string
}
func (c *Context) GetPathParam(key string) string {
value, ok := c.pathParams[key]
if ok {
return value
}
return ""
}
// GetBody 获取请求体
func (c *Context) GetBody() []byte {
if len(c.body) > 0 {
return c.body
}
data, err := ioutil.ReadAll(c.Request.Body)
c.body = data
if err == nil && len(data) > 0 {
c.body = data
return c.body
}
return nil
}
// GetJSON 获取body中
//
// json类型数据体
func (c *Context) GetJSON() (map[string]interface{}, error) {
res := make(map[string]interface{})
if len(c.GetBody()) > 0 {
err := json.Unmarshal(c.GetBody(), &res)
return res, err
}
return res, nil
}
// GetJsonParamStr 获取json对象中key对应的字符串
//
// 没有该key则返回""
func GetJsonParamStr(key string, jsonObj map[string]interface{}) string {
val, hasVal := jsonObj[key]
if !hasVal {
return ""
}
return strings.TrimSpace(fmt.Sprintf("%v", val))
}
// GetQueryParam 获取query参数
func (c *Context) GetQueryParam(key string) string {
return c.Request.URL.Query().Get(key)
}
// GetUri 获取去除querystring之后的请求路径
//
// 以 / 为开头
func (c *Context) GetUri() string {
return c.Request.URL.Path
}
// WriteJSON 返回json类型数据
func (c *Context) WriteJSON(data interface{}) {
res, err := json.Marshal(data)
if err != nil {
mLogger.ErrorF("json marshal error : %v", err.Error())
return
}
c.OK(ApplicationJson, res)
}
// 获取content-type值
func (c *Context) GetContentType() string {
return c.Request.Header.Get(ContentType)
}
// 获取header对应值
func (c *Context) GetHeader(key string) string {
return c.Request.Header.Get(key)
}
// 获取cookie值
func (c *Context) GetCookie(key string) string {
cook, err := c.Request.Cookie(key)
if err != nil {
return ""
}
return cook.Value
}
// 设置cookie值
func (c *Context) SetCookie(cookie *http.Cookie) {
http.SetCookie(c.Response, cookie)
}
// 获取locale设置
func (c *Context) Locale() string {
return c.GetCookie("locale")
}
// 302跳转
func (c *Context) Redirect(path string) error {
if !c.writeable {
return errors.New("禁止重复写入response")
}
c.writeable = false
c.code = http.StatusFound
http.Redirect(c.Response, c.Request, path, http.StatusFound)
return nil
}
func (c *Context) ProxyPass(path string, timeoutSeconds int) {
client := http.Client{
Timeout: time.Second * time.Duration(timeoutSeconds),
}
req, _ := http.NewRequest(strings.ToUpper(c.GetMethod()), path, c.Request.Body)
req.Header = c.Request.Header.Clone()
resp, err := client.Do(req)
if err != nil {
c.Error(500, err.Error())
return
}
for k, _ := range resp.Header {
c.SetHeader(k, resp.Header.Get(k))
}
bodyStr := ""
body, err := ioutil.ReadAll(resp.Body)
if err == nil {
bodyStr = string(body)
}
c.Error(resp.StatusCode, bodyStr)
return
}
// 返回http: 200
func (c *Context) OK(contentType string, content []byte) {
if !c.writeable {
mLogger.Error("禁止重复写入response")
return
}
c.writeable = false
if len(contentType) > 0 {
c.SetHeader(ContentType, contentType)
}
c.SetHeader("server", "framework")
c.code = 200
_, err := c.Response.Write(content)
if err != nil {
mLogger.ErrorF("context response Ok error : %v", err.Error())
return
}
}
// 返回对应http编码
func (c *Context) Code(static int) {
if !c.writeable {
mLogger.Error("禁止重复写入response")
return
}
c.writeable = false
c.SetHeader("server", "framework")
c.code = static
c.Response.WriteHeader(static)
return
}
// 返回http错误响应
//
// 请自行设定 contentType
func (c *Context) Error(static int, htmlStr string) {
if !c.writeable {
mLogger.Error("禁止重复写入response")
return
}
c.writeable = false
c.SetHeader("server", "framework")
c.code = static
c.Response.WriteHeader(static)
_, _ = c.Response.Write([]byte(htmlStr))
return
}
// 设置httpheader值
func (c *Context) SetHeader(key string, value string) {
c.Response.Header().Set(key, value)
}
// DelHeader 删除httpheader对应值
func (c *Context) DelHeader(key string) {
c.Response.Header().Del(key)
}
func newContext(w http.ResponseWriter, r *http.Request) Context {
return Context{
EnableI18n: false,
writeable: true,
Response: w,
Request: r,
pathParams: map[string]string{},
}
}
// GetMethod 获取http方法
func (c *Context) GetMethod() string {
return c.Request.Method
}
// JSON 返回json数据
func (c *Context) JSON(jsonStr string) {
c.OK(ApplicationJson, []byte(jsonStr))
}
// RemoteAddr 获取http请求address
func (c *Context) RemoteAddr() string {
xForward := c.Request.Header.Get("x-forwarded-for")
if len(xForward) > 0 {
return xForward
}
realIp := c.Request.Header.Get("X-Real-IP")
if len(realIp) > 0 {
return realIp
}
return c.Request.RemoteAddr
}
// http文件服务
func (c *Context) ServeFile(filePath string) {
if !c.writeable {
return
}
http.ServeFile(c.Response, c.Request, filePath)
c.writeable = false
return
}
// 设置最后修改时间
func (c *Context) SetLastModified(modtime time.Time) {
w := c.Response
if !isZeroTime(modtime) {
w.Header().Set("Last-Modified", modtime.UTC().Format(TimeFormat))
}
}
// 写入未修改
func (c *Context) WriteNotModified() error {
// RFC 7232 section 4.1:
// a sender SHOULD NOT generate representation metadata other than the
// above listed fields unless said metadata exists for the purpose of
// guiding cache updates (e.g., Last-Modified might be useful if the
// response does not have an ETag field).
if !c.writeable {
return errors.New("禁止重复写入response")
}
c.writeable = false
w := c.Response
h := w.Header()
delete(h, "Content-Type")
delete(h, "Content-Length")
if h.Get("Etag") != "" {
delete(h, "Last-Modified")
}
w.WriteHeader(StatusNotModified)
return nil
}
func (c *Context) AddCacheHeader(cacheSeconds int) {
c.SetHeader("Cache-Control", fmt.Sprintf("max-age=%v", cacheSeconds))
}
// 下载二进制文件
func (c *Context) DownloadContent(fileName string, data []byte) {
c.SetHeader("Content-disposition", fmt.Sprintf("attachment;filename=%s", fileName))
c.code = 200
_, _ = c.Response.Write(data)
return
}