-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathcontroller.go
More file actions
474 lines (426 loc) · 12.9 KB
/
controller.go
File metadata and controls
474 lines (426 loc) · 12.9 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
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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
package kocha
import (
"bytes"
"encoding/json"
"encoding/xml"
"fmt"
"io"
"mime"
"net/http"
"net/url"
"os"
"path/filepath"
"reflect"
"strings"
"sync"
"github.com/pkg/errors"
)
var contextPool = &sync.Pool{
New: func() interface{} {
return &Context{}
},
}
// Controller is the interface that the request controller.
type Controller interface {
Getter
Poster
Putter
Deleter
Header
Patcher
}
// Getter interface is an interface representing a handler for HTTP GET request.
type Getter interface {
GET(c *Context) error
}
// Poster interface is an interface representing a handler for HTTP POST request.
type Poster interface {
POST(c *Context) error
}
// Putter interface is an interface representing a handler for HTTP PUT request.
type Putter interface {
PUT(c *Context) error
}
// Deleter interface is an interface representing a handler for HTTP DELETE request.
type Deleter interface {
DELETE(c *Context) error
}
// Header interface is an interface representing a handler for HTTP HEAD request.
type Header interface {
HEAD(c *Context) error
}
// Patcher interface is an interface representing a handler for HTTP PATCH request.
type Patcher interface {
PATCH(c *Context) error
}
type requestHandler func(c *Context) error
// DefaultController implements Controller interface.
// This can be used to save the trouble to implement all of the methods of
// Controller interface.
type DefaultController struct {
}
// GET implements Getter interface that renders the HTTP 405 Method Not Allowed.
func (dc *DefaultController) GET(c *Context) error {
return c.RenderError(http.StatusMethodNotAllowed, nil, nil)
}
// POST implements Poster interface that renders the HTTP 405 Method Not Allowed.
func (dc *DefaultController) POST(c *Context) error {
return c.RenderError(http.StatusMethodNotAllowed, nil, nil)
}
// PUT implements Putter interface that renders the HTTP 405 Method Not Allowed.
func (dc *DefaultController) PUT(c *Context) error {
return c.RenderError(http.StatusMethodNotAllowed, nil, nil)
}
// DELETE implements Deleter interface that renders the HTTP 405 Method Not Allowed.
func (dc *DefaultController) DELETE(c *Context) error {
return c.RenderError(http.StatusMethodNotAllowed, nil, nil)
}
// HEAD implements Header interface that renders the HTTP 405 Method Not Allowed.
func (dc *DefaultController) HEAD(c *Context) error {
return c.RenderError(http.StatusMethodNotAllowed, nil, nil)
}
// PATCH implements Patcher interface that renders the HTTP 405 Method Not Allowed.
func (dc *DefaultController) PATCH(c *Context) error {
return c.RenderError(http.StatusMethodNotAllowed, nil, nil)
}
type mimeTypeFormats map[string]string
// MimeTypeFormats is relation between mime type and file extension.
var MimeTypeFormats = mimeTypeFormats{
"application/json": "json",
"application/xml": "xml",
"text/html": "html",
"text/plain": "txt",
}
// Get returns the file extension from the mime type.
func (m mimeTypeFormats) Get(mimeType string) string {
return m[mimeType]
}
// Set set the file extension to the mime type.
func (m mimeTypeFormats) Set(mimeType, format string) {
m[mimeType] = format
}
// Del delete the mime type and file extension.
func (m mimeTypeFormats) Del(mimeType string) {
delete(m, mimeType)
}
// Context represents a context of each request.
type Context struct {
Name string // route name of the controller.
Layout string // layout name.
Format string // format of response.
Data interface{} // data for template.
Request *Request // request.
Response *Response // response.
Params *Params // parameters of form values.
Session Session // session.
Flash Flash // flash messages.
App *Application // an application.
// Errors represents the map of errors that related to the form values.
// A map key is field name, and value is slice of errors.
// Errors will be set by Context.Params.Bind().
Errors map[string][]*ParamError
}
func newContext() *Context {
c := contextPool.Get().(*Context)
c.reset()
return c
}
// Render renders a template.
//
// A data to used will be determined the according to the following rules.
//
// 1. If data of any map type is given, it will be merged to Context.Data if possible.
//
// 2. If data of another type is given, it will be set to Context.Data.
//
// 3. If data is nil, Context.Data as is.
//
// Render retrieve a template file from controller name and c.Response.ContentType.
// e.g. If controller name is "root" and ContentType is "application/xml", Render will
// try to retrieve the template file "root.xml".
// Also ContentType set to "text/html" if not specified.
func (c *Context) Render(data interface{}) error {
if err := c.setData(data); err != nil {
return errors.WithStack(err)
}
c.setContentTypeIfNotExists("text/html")
if err := c.setFormatFromContentTypeIfNotExists(); err != nil {
return errors.WithStack(err)
}
t, err := c.App.Template.Get(c.App.Config.AppName, c.Layout, c.Name, c.Format)
if err != nil {
return errors.WithStack(err)
}
buf := bufPool.Get().(*bytes.Buffer)
defer func() {
buf.Reset()
bufPool.Put(buf)
}()
if err := t.Execute(buf, c); err != nil {
return errors.Wrap(err, t.Name())
}
if err := c.render(buf); err != nil {
return errors.WithStack(err)
}
return nil
}
// RenderJSON renders the data as JSON.
//
// RenderJSON is similar to Render but data will be encoded to JSON.
// ContentType set to "application/json" if not specified.
func (c *Context) RenderJSON(data interface{}) error {
if err := c.setData(data); err != nil {
return errors.WithStack(err)
}
c.setContentTypeIfNotExists("application/json")
buf, err := json.Marshal(c.Data)
if err != nil {
return errors.WithStack(err)
}
if err := c.render(bytes.NewReader(buf)); err != nil {
return errors.WithStack(err)
}
return nil
}
// RenderXML renders the data as XML.
//
// RenderXML is similar to Render but data will be encoded to XML.
// ContentType set to "application/xml" if not specified.
func (c *Context) RenderXML(data interface{}) error {
if err := c.setData(data); err != nil {
return errors.WithStack(err)
}
c.setContentTypeIfNotExists("application/xml")
buf, err := xml.Marshal(c.Data)
if err != nil {
return errors.WithStack(err)
}
if err := c.render(bytes.NewReader(buf)); err != nil {
return errors.WithStack(err)
}
return nil
}
// RenderText renders the content.
//
// ContentType set to "text/plain" if not specified.
func (c *Context) RenderText(content string) error {
c.setContentTypeIfNotExists("text/plain")
if err := c.render(strings.NewReader(content)); err != nil {
return errors.WithStack(err)
}
return nil
}
// RenderError renders an error page with statusCode.
//
// RenderError is similar to Render, but there is the points where some different.
// If err is not nil, RenderError outputs the err to log using c.App.Logger.Error.
// RenderError retrieves a template file from statusCode and c.Response.ContentType.
// e.g. If statusCode is 500 and ContentType is "application/xml", RenderError will
// try to retrieve the template file "errors/500.xml".
// If failed to retrieve the template file, it returns result of text with statusCode.
// Also ContentType set to "text/html" if not specified.
func (c *Context) RenderError(statusCode int, err error, data interface{}) error {
if err != nil {
c.App.Logger.Errorf("%+v", errors.WithStack(err))
}
if err := c.setData(data); err != nil {
return errors.WithStack(err)
}
c.setContentTypeIfNotExists("text/html")
if err := c.setFormatFromContentTypeIfNotExists(); err != nil {
return errors.WithStack(err)
}
c.Response.StatusCode = statusCode
c.Name = errorTemplateName(statusCode)
t, err := c.App.Template.Get(c.App.Config.AppName, c.Layout, c.Name, c.Format)
if err != nil {
c.Response.ContentType = "text/plain"
if err := c.render(bytes.NewReader([]byte(http.StatusText(statusCode)))); err != nil {
return errors.WithStack(err)
}
return nil
}
buf := bufPool.Get().(*bytes.Buffer)
defer func() {
buf.Reset()
bufPool.Put(buf)
}()
if err := t.Execute(buf, c); err != nil {
return errors.Wrap(err, t.Name())
}
if err := c.render(buf); err != nil {
return errors.WithStack(err)
}
return nil
}
// SendFile sends a content.
//
// The path argument specifies an absolute or relative path.
// If absolute path, read the content from the path as it is.
// If relative path, First, Try to get the content from included resources and
// returns it if successful. Otherwise, Add AppPath and StaticDir to the prefix
// of the path and then will read the content from the path that.
// Also, set ContentType detect from content if c.Response.ContentType is empty.
func (c *Context) SendFile(path string) error {
var file io.ReadSeeker
path = filepath.FromSlash(path)
if rc := c.App.ResourceSet.Get(path); rc != nil {
switch b := rc.(type) {
case string:
file = strings.NewReader(b)
case []byte:
file = bytes.NewReader(b)
}
}
if file == nil {
if !filepath.IsAbs(path) {
path = filepath.Join(c.App.Config.AppPath, StaticDir, path)
}
if _, err := os.Stat(path); err != nil {
c.Response.StatusCode = http.StatusNotFound
if err := c.RenderText(""); err != nil {
return errors.WithStack(err)
}
return nil
}
f, err := os.Open(path)
if err != nil {
return errors.WithStack(err)
}
defer f.Close()
file = f
}
c.Response.ContentType = mime.TypeByExtension(filepath.Ext(path))
if c.Response.ContentType == "" {
ct, err := c.detectContentTypeByBody(file)
if err != nil {
return err
}
c.Response.ContentType = ct
}
if err := c.render(file); err != nil {
return errors.WithStack(err)
}
return nil
}
// Redirect renders result of redirect.
//
// If permanently is true, redirect to url with 301. (http.StatusMovedPermanently)
// Otherwise redirect to url with 302. (http.StatusFound)
func (c *Context) Redirect(url string, permanently bool) error {
if permanently {
c.Response.StatusCode = http.StatusMovedPermanently
} else {
c.Response.StatusCode = http.StatusFound
}
http.Redirect(c.Response, c.Request.Request, url, c.Response.StatusCode)
return nil
}
// Invoke is shorthand of c.App.Invoke.
func (c *Context) Invoke(unit Unit, newFunc func(), defaultFunc func()) {
c.App.Invoke(unit, newFunc, defaultFunc)
}
func (c *Context) render(r io.Reader) error {
c.Response.Header().Set("Content-Type", c.Response.ContentType)
c.Response.WriteHeader(c.Response.StatusCode)
_, err := io.Copy(c.Response, r)
return err
}
func (c *Context) detectContentTypeByBody(r io.Reader) (string, error) {
buf := make([]byte, 512)
if n, err := io.ReadFull(r, buf); err != nil {
if err != io.EOF && err != io.ErrUnexpectedEOF {
return "", err
}
buf = buf[:n]
}
if rs, ok := r.(io.Seeker); ok {
if _, err := rs.Seek(0, os.SEEK_SET); err != nil {
return "", err
}
}
return http.DetectContentType(buf), nil
}
func (c *Context) setContentTypeIfNotExists(contentType string) {
if c.Response.ContentType == "" {
c.Response.ContentType = contentType
}
}
func (c *Context) setData(data interface{}) error {
if data == nil {
return nil
}
srcType := reflect.TypeOf(data)
if c.Data == nil || srcType.Kind() != reflect.Map {
c.Data = data
return nil
}
destType := reflect.TypeOf(c.Data)
if sk, dk := srcType.Key(), destType.Key(); !sk.AssignableTo(dk) {
return fmt.Errorf("kocha: context: key of type %v is not assignable to type %v", sk, dk)
}
src := reflect.ValueOf(data)
dest := reflect.ValueOf(c.Data)
dtype := destType.Elem()
for _, k := range src.MapKeys() {
v := src.MapIndex(k)
if vtype := v.Type(); !vtype.AssignableTo(dtype) {
if !vtype.ConvertibleTo(dtype) {
return fmt.Errorf("kocha: context: value of type %v is not assignable to type %v", vtype, dtype)
}
v = v.Convert(dtype)
}
dest.SetMapIndex(k, v)
}
return nil
}
func (c *Context) setFormatFromContentTypeIfNotExists() error {
if c.Format != "" {
return nil
}
if c.Format = MimeTypeFormats.Get(c.Response.ContentType); c.Format == "" {
return fmt.Errorf("kocha: unknown Content-Type: %v", c.Response.ContentType)
}
return nil
}
func (c *Context) newParams() *Params {
if c.Request.Form == nil {
c.Request.Form = url.Values{}
}
return newParams(c, c.Request.Form, "")
}
func (c *Context) reset() {
c.Name = ""
c.Format = ""
c.Data = nil
c.Params = nil
c.Session = nil
c.Flash = nil
}
func (c *Context) reuse() {
c.Params.reuse()
c.Request.reuse()
contextPool.Put(c)
}
// StaticServe is generic controller for serve a static file.
type StaticServe struct {
*DefaultController
}
func (ss *StaticServe) GET(c *Context) error {
path, err := url.Parse(c.Params.Get("path"))
if err != nil {
return c.RenderError(http.StatusBadRequest, err, nil)
}
return c.SendFile(path.Path)
}
var internalServerErrorController = &ErrorController{
StatusCode: http.StatusInternalServerError,
}
// ErrorController is generic controller for error response.
type ErrorController struct {
*DefaultController
StatusCode int
}
func (ec *ErrorController) GET(c *Context) error {
return c.RenderError(ec.StatusCode, nil, nil)
}