-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathcontext.go
292 lines (245 loc) · 7.21 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
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
package hfw
import (
"bufio"
"context"
"errors"
"fmt"
"net"
"net/http"
"strconv"
"strings"
"time"
logger "github.com/hsyan2008/go-logger"
"github.com/hsyan2008/hfw/common"
"github.com/hsyan2008/hfw/session"
"github.com/hsyan2008/hfw/signal"
)
//HTTPContext ..
//渲染模板的数据放Data
//Json里的数据放Response
//Layout的功能未实现 TODO
type HTTPContext struct {
Ctx context.Context `json:"-"`
cancel context.CancelFunc `json:"-"`
isCanceled bool `json:"-"`
HTTPStatus int `json:"-"`
ResponseWriter http.ResponseWriter `json:"-"`
Request *http.Request `json:"-"`
Session *session.Session `json:"-"`
Layout string `json:"-"`
//对应的struct名称,大小写一致
Controller string `json:"-"`
//对应的struct方法的名称,大小写一致
Action string `json:"-"`
Path string `json:"-"`
IsZip bool `json:"-"`
//404和500页面被自动更改content-type,导致压缩后有问题,暂时不压缩
IsError bool `json:"-"`
//html文本
Template string `json:"-"`
//模板文件
TemplateFile string `json:"-"`
//主要用于模板渲染
Data map[string]interface{} `json:"-"`
FuncMap map[string]interface{} `json:"-"`
IsJSON bool `json:"-"`
//返回的json是否包含Header
HasHeader bool `json:"-"`
//是否只返回Response.Results里的数据
IsOnlyResults bool `json:"-"`
common.Response `json:"response"`
Header interface{} `json:"header"`
//如果是下载文件,不执行After和Finish
IsCloseRender bool `json:"-"`
hijacked bool
*logger.Logger
}
func initCtx(w http.ResponseWriter, r *http.Request) *HTTPContext {
signal.GetSignalContext().WgAdd()
httpCtx := &HTTPContext{}
httpCtx.Ctx, httpCtx.cancel = context.WithCancel(signal.GetSignalContext().Ctx)
httpCtx.HTTPStatus = http.StatusOK
httpCtx.ResponseWriter = w
httpCtx.Request = r
httpCtx.Data = make(map[string]interface{})
httpCtx.FuncMap = make(map[string]interface{})
httpCtx.Logger = logger.NewLogger()
httpCtx.SetTraceID(common.GetTraceIDFromRequest(r))
return httpCtx
}
func NewHTTPContext() *HTTPContext {
signal.GetSignalContext().WgAdd()
httpCtx := &HTTPContext{}
httpCtx.Ctx, httpCtx.cancel = context.WithCancel(signal.GetSignalContext().Ctx)
httpCtx.Logger = logger.NewLogger()
httpCtx.SetTraceID(common.GetPureUUID())
return httpCtx
}
func NewHTTPContextWithCtx(ctx *HTTPContext) *HTTPContext {
signal.GetSignalContext().WgAdd()
httpCtx := &HTTPContext{}
httpCtx.Ctx, httpCtx.cancel = context.WithCancel(ctx.Ctx)
httpCtx.Logger = logger.NewLogger()
if ctx == nil || ctx.Logger == nil {
httpCtx.SetTraceID(common.GetPureUUID())
} else {
httpCtx.SetTraceID(common.GetPureUUID(ctx.GetTraceID()))
httpCtx.SetPrefix(ctx.GetPrefix())
}
return httpCtx
}
func NewHTTPContextWithGrpcIncomingCtx(ctx context.Context) *HTTPContext {
if h, ok := ctx.(*HTTPContext); ok {
return h
}
signal.GetSignalContext().WgAdd()
httpCtx := &HTTPContext{}
httpCtx.Ctx, httpCtx.cancel = context.WithCancel(ctx)
httpCtx.Logger = logger.NewLogger()
traceID := common.GetTraceIDFromIncomingContext(ctx)
httpCtx.SetTraceID(traceID)
return httpCtx
}
func NewHTTPContextWithGrpcOutgoingCtx(ctx context.Context) *HTTPContext {
if h, ok := ctx.(*HTTPContext); ok {
return h
}
signal.GetSignalContext().WgAdd()
httpCtx := &HTTPContext{}
httpCtx.Ctx, httpCtx.cancel = context.WithCancel(ctx)
httpCtx.Logger = logger.NewLogger()
traceID := common.GetTraceIDFromOutgoingContext(ctx)
httpCtx.SetTraceID(traceID)
return httpCtx
}
//因为历史原因,不能去掉Ctx,故手动实现context.Context
func (httpCtx *HTTPContext) Deadline() (deadline time.Time, ok bool) {
return httpCtx.Ctx.Deadline()
}
func (httpCtx *HTTPContext) Done() <-chan struct{} {
return httpCtx.Ctx.Done()
}
func (httpCtx *HTTPContext) Err() error {
return httpCtx.Ctx.Err()
}
func (httpCtx *HTTPContext) Value(key interface{}) interface{} {
return httpCtx.Ctx.Value(key)
}
func (httpCtx *HTTPContext) Cancel() {
if httpCtx.isCanceled {
return
}
httpCtx.isCanceled = true
signal.GetSignalContext().WgDone()
httpCtx.cancel()
//不能赋值nil,否则导致打印log报错
// httpCtx.Logger = nil
}
//GetForm 优先post和put,然后get
func (httpCtx *HTTPContext) GetForm(key string) string {
return strings.TrimSpace(httpCtx.Request.FormValue(key))
}
//GetFormInt 优先post和put,然后get,转为int
func (httpCtx *HTTPContext) GetFormInt(key string) int {
n, _ := strconv.Atoi(httpCtx.GetForm(key))
return n
}
//ErrStopRun ..
var ErrStopRun = errors.New("user stop run")
//StopRun ..
func (httpCtx *HTTPContext) StopRun() {
// logger.Debug("StopRun")
panic(ErrStopRun)
}
//Redirect ..
func (httpCtx *HTTPContext) Redirect(url string) {
http.Redirect(httpCtx.ResponseWriter, httpCtx.Request, url, http.StatusFound)
httpCtx.StopRun()
}
//ThrowCheck
func (httpCtx *HTTPContext) ThrowCheck(errNo int64, i interface{}) {
if i == nil || errNo == 0 {
return
}
var errMsg string
switch e := i.(type) {
case *common.RespErr:
errNo = e.ErrNo()
errMsg = e.ErrMsg()
httpCtx.Output(2, fmt.Sprintf("[ThrowCheck] %s", e.Error()))
default:
errMsg = fmt.Sprintf("%v", e)
httpCtx.Output(2, fmt.Sprintf("[ThrowCheck] No:%d Msg:%v", errNo, errMsg))
}
httpCtx.ErrNo = errNo
httpCtx.ErrMsg = common.GetErrorMap(errNo)
if len(httpCtx.ErrMsg) == 0 {
httpCtx.ErrMsg = errMsg
}
if httpCtx.ErrNo < Config.ErrorBase && Config.AppID > 0 {
httpCtx.ErrNo = Config.AppID*Config.ErrorBase + httpCtx.ErrNo
}
httpCtx.StopRun()
}
//CheckErr
func (httpCtx *HTTPContext) CheckErr(errNo int64, i interface{}) (int64, string) {
var errMsg string
if i == nil || errNo == 0 {
return 0, errMsg
}
switch e := i.(type) {
case *common.RespErr:
errNo = e.ErrNo()
errMsg = e.ErrMsg()
httpCtx.Output(2, fmt.Sprintf("[CheckErr] %s", e.Error()))
default:
errMsg = fmt.Sprintf("%v", e)
httpCtx.Output(2, fmt.Sprintf("[CheckErr] No:%d Msg:%v", errNo, errMsg))
}
httpCtx.ErrMsg = common.GetErrorMap(errNo)
if httpCtx.ErrMsg != "" {
errMsg = httpCtx.ErrMsg
}
if errNo < Config.ErrorBase && Config.AppID > 0 {
errNo = Config.AppID*Config.ErrorBase + errNo
}
return errNo, errMsg
}
//SetDownloadMode ..
func (httpCtx *HTTPContext) SetDownloadMode(filename string) {
httpCtx.ResponseWriter.Header().Set("Content-Disposition", fmt.Sprintf(`attachment;filename="%s"`, filename))
httpCtx.IsCloseRender = true
}
func (httpCtx *HTTPContext) GetCookie(key string) (s string) {
cookie, _ := httpCtx.Request.Cookie(key)
if cookie != nil {
return cookie.Value
}
return
}
func (httpCtx *HTTPContext) SetCookie(key, value string) {
cookie := &http.Cookie{
Name: key,
Value: value,
Path: "/",
HttpOnly: true,
Secure: httpCtx.Request.URL.Scheme == "https",
}
http.SetCookie(httpCtx.ResponseWriter, cookie)
}
func (httpCtx *HTTPContext) Hijack() (conn net.Conn, bufrw *bufio.ReadWriter, err error) {
hj, ok := httpCtx.ResponseWriter.(http.Hijacker)
if !ok {
httpCtx.Warn("webserver doesn't support hijacking")
httpCtx.HTTPStatus = http.StatusInternalServerError
return
}
conn, bufrw, err = hj.Hijack()
if err != nil {
httpCtx.Warn("Hijack:", err)
httpCtx.HTTPStatus = http.StatusInternalServerError
return
}
httpCtx.hijacked = true
return
}