/
controller.go
115 lines (89 loc) · 2 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
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
package controllers
import (
"net/http"
"reflect"
"strings"
"aahframework.org/aah.v0"
"github.com/train-cat/api-train/app/rest"
"github.com/train-cat/api-train/app/validators"
"gopkg.in/go-playground/validator.v9"
)
// Controller extend aah.Context
type Controller struct {
*aah.Context
}
func (c *Controller) serverError(err error) bool {
if err == nil {
return false
}
c.Log().Error(err)
c.Reply().InternalServerError().JSON(aah.Error{})
return true
}
func (c *Controller) validatePost(input interface{}) bool {
errs := validators.Struct(input)
if errs != nil {
c.badRequestResponse(errs)
return false
}
return true
}
func (c *Controller) get(s rest.Hateoasable, err error) {
if c.serverError(err) ||
c.notFound(s) ||
c.serverError(c.hateoas(s)) {
return
}
c.Reply().Ok().JSON(s)
}
func (c *Controller) needRole(role string) {
abort := false
if c.Subject() == nil {
c.unauthorizedResponse()
abort = true
}
if !c.Subject().HasRole(role) {
c.forbiddenResponse()
abort = true
}
if abort {
c.Abort()
}
}
func (c *Controller) notFound(s interface{}) bool {
if !reflect.ValueOf(s).IsNil() {
return false
}
c.notFoundResponse()
return true
}
// === shortcut response ===
func (c *Controller) unauthorizedResponse() {
c.Reply().Unauthorized().JSON(aah.Data{
"message": "access denied",
})
}
func (c *Controller) forbiddenResponse() {
c.Reply().Forbidden().JSON(aah.Data{
"message": "access denied",
})
}
func (c *Controller) notFoundResponse() {
c.Reply().NotFound().JSON(aah.Error{
Code: http.StatusNotFound,
Message: "Not Found",
})
}
func (c *Controller) badRequestResponse(errs error) {
m := map[string]string{}
for _, err := range errs.(validator.ValidationErrors) {
// TODO improve method to get field name
field := strings.ToLower(err.Field())
m[field] = err.Translate(nil)
}
c.Reply().BadRequest().JSON(m)
}
// === end shortcut response ===
func (c *Controller) hateoas(s rest.Hateoasable) error {
return s.GenerateHateoas(c.Context)
}