forked from razonyang/clevergo-examples
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcontext.go
196 lines (169 loc) · 4.84 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
package clevergo
import (
"encoding/json"
"encoding/xml"
"fmt"
"github.com/clevergo/router"
"github.com/clevergo/sessions"
"github.com/valyala/fasthttp"
"html/template"
"sync"
)
var contextPool = &sync.Pool{
New: func() interface{} {
return &Context{}
},
}
// Context of request.
//
// It contains the router, session and params.
type Context struct {
router *Router
*fasthttp.RequestCtx
Params *router.Params
Session *sessions.Session
}
// NewContext returns a Context instance.
//
// Firstly, it will try to get Context instance from contextPool.
// If failed to get Context from contextPool,
// returns a new Context instance.
func NewContext(r *Router, ctx *fasthttp.RequestCtx, rps *router.Params) *Context {
if context, ok := contextPool.Get().(*Context); ok {
context.router = r
context.RequestCtx = ctx
context.Params = rps
return context
}
return &Context{
router: r,
RequestCtx: ctx,
Params: rps,
}
}
// Close Context.
//
// Context should be closed after finishing request,
// and at this moment, put the context into contextPool.
func (ctx *Context) Close() {
ctx.Session = nil
contextPool.Put(ctx)
}
// SessionStore returns the session store of router.
func (ctx *Context) SessionStore() sessions.Store {
return ctx.router.sessionStore
}
// Logger returns logger.
//
// Returns the router's logger if the logger is non-nil.
// Otherwise, returns the default logger of ctx.
func (ctx *Context) Logger() fasthttp.Logger {
if ctx.router.logger != nil {
return ctx.router.logger
}
return ctx.RequestCtx.Logger()
}
const (
// contentTypeHTML HTML's ContentType
contentTypeHTML = "text/html; charset=utf-8"
// contentTypeJSON JSON's ContentType
contentTypeJSON = "application/json; charset=utf-8"
// contentTypeJSONP JSONP's ContentType
contentTypeJSONP = "application/javascript; charset=utf-8"
// contentTypeXML XML's ContentType
contentTypeXML = "application/xml; charset=utf-8"
)
// SetContentTypeToHTML set Content-Type to HTML.
func (ctx *Context) SetContentTypeToHTML() {
ctx.Response.Header.Set("Content-Type", contentTypeHTML)
}
// SetContentTypeToJSON set Content-Type to JSON.
func (ctx *Context) SetContentTypeToJSON() {
ctx.Response.Header.Set("Content-Type", contentTypeJSON)
}
// SetContentTypeToJSONP set Content-Type to JSONP.
func (ctx *Context) SetContentTypeToJSONP() {
ctx.Response.Header.Set("Content-Type", contentTypeJSONP)
}
// SetContentTypeToXML set Content-Type to XML.
func (ctx *Context) SetContentTypeToXML() {
ctx.Response.Header.Set("Content-Type", contentTypeXML)
}
// JSON responses JSON data to client.
func (ctx *Context) JSON(v interface{}) {
json, err := json.Marshal(v)
if err != nil {
fmt.Fprint(ctx, err.Error())
return
}
ctx.SetContentTypeToJSON()
ctx.Response.SetBody(json)
}
// JSONWithCode responses JSON data and custom status code to client.
func (ctx *Context) JSONWithCode(code int, v interface{}) {
ctx.Response.SetStatusCode(code)
ctx.JSON(v)
}
// JSONP responses JSONP data to client.
func (ctx *Context) JSONP(v interface{}, callback []byte) {
json, err := json.Marshal(v)
if err != nil {
fmt.Fprint(ctx, err.Error())
return
}
ctx.SetContentTypeToJSONP()
jsonp := append(callback, "("...)
jsonp = append(jsonp, json...)
jsonp = append(jsonp, ")"...)
ctx.Response.SetBody(jsonp)
}
// JSONPWithCode responses JSONP data and custom status code to client.
func (ctx *Context) JSONPWithCode(code int, v interface{}, callback []byte) {
ctx.Response.SetStatusCode(code)
ctx.JSONP(v, callback)
}
// XML responses XML data to client.
func (ctx *Context) XML(v interface{}, headers ...string) {
xmlBytes, err := xml.MarshalIndent(v, "", ` `)
if err != nil {
fmt.Fprint(ctx, err.Error())
return
}
header := xml.Header
if len(headers) > 0 {
header = headers[0]
}
var bytes []byte
bytes = append(bytes, header...)
bytes = append(bytes, xmlBytes...)
ctx.SetContentTypeToXML()
ctx.Response.SetBody(bytes)
}
// XMLWithCode responses XML data and custom status code to client.
func (ctx *Context) XMLWithCode(code int, v interface{}, headers ...string) {
ctx.Response.SetStatusCode(code)
ctx.XML(v, headers...)
}
// HTML responses HTML data to client.
func (ctx *Context) HTML(body string) {
ctx.SetContentTypeToHTML()
ctx.Response.SetBodyString(body)
}
// HTMLWithCode responses HTML data and custom status code to client.
func (ctx *Context) HTMLWithCode(code int, body string) {
ctx.Response.SetStatusCode(code)
ctx.HTML(body)
}
// Text responses text data to client using fmt.Fprint().
func (ctx *Context) Text(a ...interface{}) {
fmt.Fprint(ctx, a...)
}
// Textf responses text data to client using fmt.Fprintf().
func (ctx *Context) Textf(format string, a ...interface{}) {
fmt.Fprintf(ctx, format, a...)
}
// Render for rendering a template.
func (ctx *Context) Render(tpl *template.Template, data interface{}) {
ctx.SetContentTypeToHTML()
tpl.Execute(ctx, data)
}