-
Notifications
You must be signed in to change notification settings - Fork 0
/
responder.go
386 lines (320 loc) · 9.27 KB
/
responder.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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
package respond
import (
"encoding/xml"
"errors"
"fmt"
"html/template"
"io"
"net/http"
"github.com/gookit/easytpl"
"github.com/gookit/goutil"
"github.com/gookit/goutil/errorx"
"github.com/gookit/goutil/netutil/httpctype"
"github.com/gookit/goutil/netutil/httpreq"
)
// Options for the Responder
type Options struct {
Debug bool
JSONIndent bool
JSONPrefix string
XMLIndent bool
XMLPrefix string
// template render options, please see easytpl.Options
TplLayout string
TplDelims easytpl.TplDelims
TplFuncMap template.FuncMap
TplViewsDir string
TplSuffixes []string
// supported content types for response, you can change it.
ContentBinary, ContentHTML, ContentXML, ContentText, ContentJSON, ContentJSONP string
// ContentType default content type value. use for Responder.Auto() method
ContentType string
// Charset default content data charset
Charset string
// AddCharset on response content
AddCharset bool
}
// OptionFn option function
type OptionFn func(opts *Options)
// Responder definition
type Responder struct {
opts *Options
// view renderer
renderer *easytpl.Renderer
// mark init is completed
initialized bool
}
/*************************************************************
* create and initialize
*************************************************************/
// New responder instance
func New(fns ...OptionFn) *Responder {
r := &Responder{
opts: &Options{
ContentXML: ContentXML,
ContentText: ContentText,
ContentHTML: ContentHTML,
ContentJSON: ContentJSON,
ContentJSONP: ContentJSONP,
ContentBinary: ContentBinary,
AddCharset: true,
Charset: defaultCharset,
XMLPrefix: defaultXMLPrefix,
TplDelims: easytpl.TplDelims{Left: "{{", Right: "}}"},
TplSuffixes: []string{"tpl", "html"},
},
}
// apply config options
for _, fn := range fns {
fn(r.opts)
}
return r
}
func NewInited(opFns ...OptionFn) *Responder {
return New(opFns...).Initialize()
}
// NewInitialized create new instance and initialization it.
func NewInitialized(opFns ...OptionFn) *Responder {
return New(opFns...).Initialize()
}
// Initialize the responder
func (r *Responder) Initialize() *Responder {
if r.initialized {
return r
}
if r.opts.AddCharset {
r.appendCharset()
}
opts := r.opts
// init view renderer
v := easytpl.NewRenderer()
v.Debug = opts.Debug
v.Delims = opts.TplDelims
v.Layout = opts.TplLayout
v.FuncMap = opts.TplFuncMap
v.ViewsDir = opts.TplViewsDir
v.MustInit()
r.renderer = v
r.initialized = true
return r
}
// append charset for all content types
func (r *Responder) appendCharset() {
if len(r.opts.Charset) == 0 {
return
}
r.opts.ContentBinary += "; " + r.opts.Charset
r.opts.ContentHTML += "; " + r.opts.Charset
r.opts.ContentXML += "; " + r.opts.Charset
r.opts.ContentText += "; " + r.opts.Charset
r.opts.ContentJSON += "; " + r.opts.Charset
r.opts.ContentJSONP += "; " + r.opts.Charset
}
// LoadTemplateGlob load templates by glob
//
// Usage:
//
// LoadTemplateGlob("views/*")
// LoadTemplateGlob("views/**/*")
func (r *Responder) LoadTemplateGlob(pattern string) {
r.renderer.LoadByGlob(pattern)
}
// LoadTemplateFiles load template files.
// Usage:
//
// LoadTemplateFiles("path/file1.tpl", "path/file2.tpl")
func (r *Responder) LoadTemplateFiles(files ...string) {
r.renderer.LoadFiles(files...)
}
/*************************************************************
* render and response HTML
*************************************************************/
// HTML render HTML template file to http.ResponseWriter
//
// NOTE: layout only available on enable the view layout
func (r *Responder) HTML(w http.ResponseWriter, status int, template string, v any, layout ...string) error {
w.Header().Set(ContentType, r.opts.ContentHTML)
w.WriteHeader(status)
return r.renderer.Render(w, template, v, layout...)
}
// HTMLString render HTML template string to http.ResponseWriter
func (r *Responder) HTMLString(w http.ResponseWriter, status int, tplContent string, v any) error {
w.Header().Set(ContentType, r.opts.ContentHTML)
w.WriteHeader(status)
t := template.Must(template.New("temp").Parse(tplContent))
if err := t.Execute(w, v); err != nil {
// return err
panic(err)
}
return nil
}
// HTMLText output raw HTML contents response(content-type=html/text)
func (r *Responder) HTMLText(w http.ResponseWriter, status int, html string) error {
w.Header().Set(ContentType, r.opts.ContentHTML)
w.WriteHeader(status)
_, err := w.Write([]byte(html))
return err
}
/*************************************************************
* respond data
*************************************************************/
// Auto response data by request accepted header
func (r *Responder) Auto(w http.ResponseWriter, req *http.Request, data any, tplName ...string) error {
resContentType := w.Header().Get(httpctype.Key)
outTypeList := []string{resContentType}
if resContentType == "" {
// check the request accepted header
accepted := req.Header.Get("Accepted")
if len(accepted) > 0 {
outTypeList = httpreq.ParseAccept(accepted)
} else {
// fallback to default content type
if len(r.opts.ContentType) == 0 {
return errorx.E("no content type for response")
}
outTypeList = []string{r.opts.ContentType}
}
}
var lastVal string
for _, val := range outTypeList {
if len(val) == 0 {
continue
}
switch val {
case "application/json":
return r.JSON(w, http.StatusOK, data)
case "application/xml":
return r.XML(w, http.StatusOK, data)
case "text/html":
if len(tplName) > 0 {
return r.HTML(w, http.StatusOK, tplName[0], data)
}
return errorx.Ef("no template name for HTML response")
case "text/plain":
return r.Text(w, http.StatusOK, goutil.String(data))
}
lastVal = val
break
}
return errorx.Ef("unsupported content type %q for response", lastVal)
}
// Empty alias method of the NoContent()
func (r *Responder) Empty(w http.ResponseWriter) error {
return r.NoContent(w)
}
// NoContent serve success but no content response
func (r *Responder) NoContent(w http.ResponseWriter) error {
w.WriteHeader(http.StatusNoContent)
return nil
}
// Content serve success but no content response
func (r *Responder) Content(w http.ResponseWriter, status int, v []byte, contentType string) error {
w.WriteHeader(status)
w.Header().Set(ContentType, contentType)
_, err := w.Write(v)
return err
}
// Data is the generic function called by XML, JSON, Data, HTML, and can be called by custom implementations.
func (r *Responder) Data(w http.ResponseWriter, status int, v any, contentType string) error {
w.WriteHeader(status)
_, err := w.Write(v.([]byte))
return err
}
// String alias method of the Text()
func (r *Responder) String(w http.ResponseWriter, status int, v string) error {
return r.Text(w, status, v)
}
// Text serve string content as text/plain response
func (r *Responder) Text(w http.ResponseWriter, status int, v string) error {
w.WriteHeader(status)
w.Header().Set(ContentType, r.opts.ContentText)
_, err := w.Write([]byte(v))
return err
}
// JSON serve string content as json response
func (r *Responder) JSON(w http.ResponseWriter, status int, v any) error {
w.Header().Set(ContentType, r.opts.ContentJSON)
w.WriteHeader(status)
bs, err := jsonMarshal(v, r.opts.JSONIndent, false)
if err != nil {
return err
}
if r.opts.JSONPrefix != "" {
_, err = w.Write([]byte(r.opts.JSONPrefix))
if err != nil {
return err
}
}
_, err = w.Write(bs)
return err
}
// JSONP serve data as JSONP response
func (r *Responder) JSONP(w http.ResponseWriter, status int, callback string, v any) error {
w.Header().Set(ContentType, r.opts.ContentJSONP)
w.WriteHeader(status)
bs, err := jsonMarshal(v, false, false)
if err != nil {
return err
}
if callback == "" {
return errors.New("renderer: callback can not bet empty")
}
_, _ = w.Write([]byte(callback + "("))
_, err = w.Write(bs)
_, _ = w.Write([]byte(");"))
return err
}
// XML serve data as XML response
func (r *Responder) XML(w http.ResponseWriter, status int, v any) (err error) {
w.Header().Set(ContentType, r.opts.ContentXML)
w.WriteHeader(status)
var bs []byte
if r.opts.XMLIndent {
bs, err = xml.MarshalIndent(v, "", " ")
} else {
bs, err = xml.Marshal(v)
}
if err != nil {
return err
}
if r.opts.XMLPrefix != "" {
_, err = w.Write([]byte(r.opts.XMLPrefix))
if err != nil {
return err
}
}
_, err = w.Write(bs)
return err
}
// Binary serve data as Binary response.
// Usage:
//
// var reader io.Reader
// reader, _ = os.Open("./README.md")
// r.Binary(w, http.StatusOK, reader, "readme.md", true)
func (r *Responder) Binary(w http.ResponseWriter, status int, in io.Reader, outName string, inline bool) error {
bs, err := io.ReadAll(in)
if err != nil {
return err
}
dispositionType := dispositionAttachment
if inline {
dispositionType = dispositionInline
}
w.Header().Set(ContentType, r.opts.ContentBinary)
w.Header().Set(ContentDisposition, fmt.Sprintf("%s; filename=%s", dispositionType, outName))
w.WriteHeader(status)
_, err = w.Write(bs)
return err
}
/*************************************************************
* helper methods
*************************************************************/
// Options get readonly options
func (r *Responder) Options() Options {
return *r.opts
}
// Renderer get template renderer
func (r *Responder) Renderer() *easytpl.Renderer {
return r.renderer
}