-
Notifications
You must be signed in to change notification settings - Fork 3
/
group.go
192 lines (158 loc) · 4.61 KB
/
group.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
// Package fire is an idiomatic micro-framework for building Ember.js compatible
// APIs with Go.
package fire
import (
"fmt"
"net/http"
"strings"
"github.com/256dpi/jsonapi"
"github.com/256dpi/stack"
)
// GroupAction defines a group action.
type GroupAction struct {
// Authorizers authorize the group action and are run before the action.
// Returned errors will cause the abortion of the request with an
// unauthorized status by default.
Authorizers []*Callback
// Action is the action that should be executed.
Action *Action
}
// A Group manages access to multiple controllers and their interconnections.
type Group struct {
controllers map[string]*Controller
actions map[string]*GroupAction
// The function gets invoked by the controller with critical errors.
Reporter func(error)
}
// NewGroup creates and returns a new group.
func NewGroup() *Group {
return &Group{
controllers: make(map[string]*Controller),
actions: make(map[string]*GroupAction),
}
}
// Add will add a controller to the group.
func (g *Group) Add(controllers ...*Controller) {
for _, controller := range controllers {
// prepare controller
controller.prepare()
// get name
name := controller.Model.Meta().PluralName
// check existence
if g.controllers[name] != nil {
panic(fmt.Sprintf(`fire: controller with name "%s" already exists`, name))
}
// create entry in controller map
g.controllers[name] = controller
}
}
// Handle allows to add an action as a group action. Group actions will be run
// when no controller matches the request.
//
// Note: The passed context is more or less empty.
func (g *Group) Handle(name string, a *GroupAction) {
if name == "" {
panic(fmt.Sprintf(`fire: invalid group action "%s"`, name))
}
// set default body limit
if a.Action.BodyLimit == 0 {
a.Action.BodyLimit = DataSize("8M")
}
// check existence
if g.actions[name] != nil {
panic(fmt.Sprintf(`fire: action with name "%s" already exists`, name))
}
// add action
g.actions[name] = a
}
// Endpoint will return an http handler that serves requests for this group. The
// specified prefix is used to parse the requests and generate urls for the
// resources.
func (g *Group) Endpoint(prefix string) http.Handler {
// trim prefix
prefix = strings.Trim(prefix, "/")
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// create tracer
tracer := NewTracerFromRequest(r, "fire/Group.Endpoint")
defer tracer.Finish(true)
// continue any previous aborts
defer stack.Resume(func(err error) {
// directly write jsonapi errors
if jsonapiError, ok := err.(*jsonapi.Error); ok {
_ = jsonapi.WriteError(w, jsonapiError)
return
}
// set critical error on last span
tracer.Tag("error", true)
tracer.Log("error", err.Error())
tracer.Log("stack", stack.Trace())
// report critical errors if possible
if g.Reporter != nil {
g.Reporter(err)
}
// ignore errors caused by writing critical errors
_ = jsonapi.WriteError(w, jsonapi.InternalServerError(""))
})
// trim path
path := strings.Trim(r.URL.Path, "/")
path = strings.TrimPrefix(path, prefix)
path = strings.Trim(path, "/")
// check path
if path == "" {
stack.Abort(jsonapi.NotFound("resource not found"))
}
// split path
s := strings.Split(path, "/")
// prepare context
ctx := &Context{
Data: Map{},
HTTPRequest: r,
ResponseWriter: w,
Group: g,
Tracer: tracer,
}
// get controller
controller, ok := g.controllers[s[0]]
if ok {
// set controller
ctx.Controller = controller
// call controller with context
controller.generalHandler(prefix, ctx)
return
}
// get action
action, ok := g.actions[s[0]]
if ok {
// check if action is allowed
if Contains(action.Action.Methods, r.Method) {
// check if action matches the context
if action.Action.Callback.Matcher(ctx) {
// run authorizers and handle errors
for _, cb := range action.Authorizers {
// check if callback should be run
if !cb.Matcher(ctx) {
continue
}
// call callback
err := cb.Handler(ctx)
if IsSafe(err) {
stack.Abort(&jsonapi.Error{
Status: http.StatusUnauthorized,
Detail: err.Error(),
})
} else if err != nil {
stack.Abort(err)
}
}
// limit request body size
LimitBody(ctx.ResponseWriter, ctx.HTTPRequest, int64(action.Action.BodyLimit))
// call action with context
stack.AbortIf(action.Action.Callback.Handler(ctx))
return
}
}
}
// otherwise return error
stack.Abort(jsonapi.NotFound("resource not found"))
})
}