-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcontroller.go
69 lines (56 loc) · 1.91 KB
/
controller.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
package jantar
import (
"github.com/tsurai/jantar/context"
"net/http"
"reflect"
)
// IController describes a Controller
type IController interface {
setInternal(rw http.ResponseWriter, r *http.Request, name string, action string)
Render()
}
// Controller implements core functionalities of the IController interface
type Controller struct {
name string
action string
Respw http.ResponseWriter
Req *http.Request
RenderArgs map[string]interface{}
}
func newController(t reflect.Type, respw http.ResponseWriter, req *http.Request, name string, action string) IController {
c := reflect.New(t).Interface().(IController)
c.setInternal(respw, req, name, action)
return c
}
func getControllerType(handler interface{}) reflect.Type {
t := reflect.TypeOf(handler)
if t.Kind() == reflect.Func && t.NumIn() != 0 && t.In(0).Implements(reflect.TypeOf((*IController)(nil)).Elem()) {
return t.In(0).Elem()
}
return nil
}
func (c *Controller) setInternal(respw http.ResponseWriter, req *http.Request, name string, action string) {
c.name = name
c.action = action
c.Respw = respw
c.Req = req
c.RenderArgs = context.RenderArgs(req)
}
func (c *Controller) UrlParam() map[string]string {
return context.Get(c.Req, "_UrlParam").(map[string]string)
}
// Redirect redirects the current request to a given named route using args to complete url variables
func (c *Controller) Redirect(to string, args ...interface{}) {
router := GetModule(ModuleRouter).(*router)
url := router.getReverseURL(to, args)
c.Respw.Header().Set("Location", url)
c.Respw.WriteHeader(302)
}
// Render gets the template for the calling action and renders it
func (c *Controller) Render() {
tm := GetModule(ModuleTemplateManager).(*TemplateManager)
if err := tm.RenderTemplate(c.Respw, c.Req, c.name+"/"+c.action+".html", c.RenderArgs); err != nil {
Log.Warning(err.Error())
http.Error(c.Respw, "500 internal server error", 500)
}
}