-
Notifications
You must be signed in to change notification settings - Fork 3
/
group.go
220 lines (180 loc) · 5.02 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
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
// Package fire is an idiomatic micro-framework for building Ember.js compatible
// APIs with Go.
package fire
import (
"context"
"errors"
"fmt"
"net/http"
"strings"
"time"
"github.com/256dpi/jsonapi/v2"
"github.com/256dpi/serve"
"github.com/256dpi/xo"
"github.com/256dpi/fire/coal"
"github.com/256dpi/fire/stick"
)
// 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 {
reporter func(error)
controllers map[string]*Controller
actions map[string]*GroupAction
}
// NewGroup creates and returns a new group.
func NewGroup(reporter func(error)) *Group {
return &Group{
reporter: reporter,
controllers: make(map[string]*Controller),
actions: make(map[string]*GroupAction),
}
}
// Add will add controllers to the group.
func (g *Group) Add(controllers ...*Controller) {
for _, controller := range controllers {
// prepare controller
controller.prepare()
// get name
name := coal.GetMeta(controller.Model).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 only be
// run when no controller matches the request.
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 = serve.MustByteSize("8M")
}
// set default timeout
if a.Action.Timeout == 0 {
a.Action.Timeout = 30 * time.Second
}
// 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 a 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, tc := xo.CreateTracer(r.Context(), "fire/Group.Endpoint")
defer tracer.End()
r = r.WithContext(tc)
// recover any panic
defer xo.Recover(func(err error) {
// record error
tracer.Record(err)
// report error if possible or rethrow
if g.reporter != nil {
g.reporter(err)
}
// write internal server error
_ = jsonapi.WriteError(w, jsonapi.InternalServerError(""))
})
// continue any previous aborts
defer xo.Resume(func(err error) {
// directly write jsonapi errors
var jsonapiError *jsonapi.Error
if errors.As(err, &jsonapiError) {
_ = jsonapi.WriteError(w, jsonapiError)
return
}
// record error
tracer.Record(err)
// report error if possible
if g.reporter != nil {
g.reporter(err)
}
// write internal server error
_ = 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 == "" {
xo.Abort(jsonapi.NotFound("resource not found"))
}
// split path
s := strings.Split(path, "/")
// prepare context
ctx := &Context{
Context: r.Context(),
Data: stick.Map{},
HTTPRequest: r,
ResponseWriter: w,
Group: g,
Tracer: tracer,
}
// get controller
controller, ok := g.controllers[s[0]]
if ok {
// set controller
ctx.Controller = controller
// handle request
controller.handle(prefix, ctx, nil, true)
return
}
// get action
action, ok := g.actions[s[0]]
if ok {
// check if action is allowed
if stick.Contains(action.Action.Methods, r.Method) {
// 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 xo.IsSafe(err) {
xo.Abort(&jsonapi.Error{
Status: http.StatusUnauthorized,
Detail: err.Error(),
})
} else if err != nil {
xo.Abort(err)
}
}
// limit request body size
serve.LimitBody(ctx.ResponseWriter, ctx.HTTPRequest, action.Action.BodyLimit)
// create context
ct, cancel := context.WithTimeout(ctx.Context, action.Action.Timeout)
defer cancel()
// replace context
ctx.Context = ct
// call action with context
xo.AbortIf(action.Action.Handler(ctx))
return
}
}
// otherwise, return error
xo.Abort(jsonapi.NotFound("resource not found"))
})
}