-
Notifications
You must be signed in to change notification settings - Fork 5
/
route.go
685 lines (610 loc) · 17.1 KB
/
route.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
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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
package fir
import (
"context"
"fmt"
"html/template"
"net/http"
"strconv"
"strings"
"sync"
"github.com/goccy/go-json"
"github.com/gorilla/websocket"
"github.com/livefir/fir/internal/dom"
firErrors "github.com/livefir/fir/internal/errors"
"github.com/livefir/fir/internal/eventstate"
"github.com/livefir/fir/internal/logger"
"github.com/livefir/fir/pubsub"
servertiming "github.com/mitchellh/go-server-timing"
)
// RouteOption is a function that sets route options
type RouteOption func(*routeOpt)
// RouteOptions is a slice of RouteOption
type RouteOptions []RouteOption
// RouteFunc is a function that handles a route
type RouteFunc func() RouteOptions
// Route is an interface that represents a route
type Route interface{ Options() RouteOptions }
// OnEventFunc is a function that handles an http event request
type OnEventFunc func(ctx RouteContext) error
// ID sets the route unique identifier. This is used to identify the route in pubsub.
func ID(id string) RouteOption {
return func(opt *routeOpt) {
opt.id = id
}
}
// Layout sets the layout for the route's template engine
func Layout(layout string) RouteOption {
return func(opt *routeOpt) {
opt.layout = layout
}
}
// Content sets the content for the route
func Content(content string) RouteOption {
return func(opt *routeOpt) {
opt.content = content
}
}
// LayoutContentName sets the name of the template which contains the content.
/*
{{define "layout"}}
{{ define "content" }}
{{ end }}
{{end}}
Here "content" is the default layout content name
*/
func LayoutContentName(name string) RouteOption {
return func(opt *routeOpt) {
opt.layoutContentName = name
}
}
// ErrorLayout sets the layout for the route's template engine
func ErrorLayout(layout string) RouteOption {
return func(opt *routeOpt) {
opt.errorLayout = layout
}
}
// ErrorContent sets the content for the route
func ErrorContent(content string) RouteOption {
return func(opt *routeOpt) {
opt.errorContent = content
}
}
// ErrorLayoutContentName sets the name of the template which contains the content.
/*
{{define "layout"}}
{{ define "content" }}
{{ end }}
{{end}}
Here "content" is the default layout content name
*/
func ErrorLayoutContentName(name string) RouteOption {
return func(opt *routeOpt) {
opt.errorLayoutContentName = name
}
}
// Partials sets the template partials for the route's template engine
func Partials(partials ...string) RouteOption {
return func(opt *routeOpt) {
opt.partials = partials
}
}
// Extensions sets the template file extensions read for the route's template engine
func Extensions(extensions ...string) RouteOption {
return func(opt *routeOpt) {
opt.extensions = extensions
}
}
// FuncMap appends to the default template function map for the route's template engine
func FuncMap(funcMap template.FuncMap) RouteOption {
return func(opt *routeOpt) {
opt.mergeFuncMap(funcMap)
}
}
// EventSender sets the event sender for the route. It can be used to send events for the route
// without a corresponding user event. This is useful for sending events to the route event handler for use cases like:
// sending notifications, sending emails, etc.
func EventSender(eventSender chan Event) RouteOption {
return func(opt *routeOpt) {
opt.eventSender = eventSender
}
}
// OnLoad sets the route's onload event handler
func OnLoad(f OnEventFunc) RouteOption {
return func(opt *routeOpt) {
opt.onLoad = f
}
}
// OnEvent registers an event handler for the route per unique event name. It can be called multiple times
// to register multiple event handlers for the route.
func OnEvent(name string, onEventFunc OnEventFunc) RouteOption {
return func(opt *routeOpt) {
if opt.onEvents == nil {
opt.onEvents = make(map[string]OnEventFunc)
}
opt.onEvents[strings.ToLower(name)] = onEventFunc
}
}
type routeRenderer func(data routeData) error
type eventPublisher func(event pubsub.Event) error
type routeOpt struct {
id string
layout string
errorLayout string
errorContent string
content string
layoutContentName string
errorLayoutContentName string
partials []string
extensions []string
funcMap template.FuncMap
funcMapMutex *sync.RWMutex
eventSender chan Event
onLoad OnEventFunc
onEvents map[string]OnEventFunc
opt
}
// add func to funcMap
func (opt *routeOpt) addFunc(key string, f any) {
opt.funcMapMutex.Lock()
defer opt.funcMapMutex.Unlock()
opt.funcMap[key] = f
}
// mergeFuncMap merges a value to the funcMap in a concurrency safe way.
func (opt *routeOpt) mergeFuncMap(funcMap template.FuncMap) {
opt.funcMapMutex.Lock()
defer opt.funcMapMutex.Unlock()
for k, v := range funcMap {
opt.funcMap[k] = v
}
}
// getFuncMap lists the funcMap in a concurrency safe way.
func (opt *routeOpt) getFuncMap() template.FuncMap {
opt.funcMapMutex.Lock()
defer opt.funcMapMutex.Unlock()
return opt.funcMap
}
type route struct {
template *template.Template
errorTemplate *template.Template
eventTemplates eventTemplates
cntrl *controller
routeOpt
sync.RWMutex
}
func newRoute(cntrl *controller, routeOpt *routeOpt) *route {
routeOpt.opt = cntrl.opt
rt := &route{
routeOpt: *routeOpt,
cntrl: cntrl,
eventTemplates: make(eventTemplates),
}
rt.parseTemplates()
return rt
}
func publishEvents(ctx context.Context, eventCtx RouteContext, channel string) eventPublisher {
return func(pubsubEvent pubsub.Event) error {
err := eventCtx.route.pubsub.Publish(ctx, channel, pubsubEvent)
if err != nil {
logger.Errorf("error publishing patch: %v", err)
return err
}
return nil
}
}
func writeAndPublishEvents(ctx RouteContext) eventPublisher {
return func(pubsubEvent pubsub.Event) error {
channel := ctx.route.channelFunc(ctx.request, ctx.route.id)
if channel == nil {
logger.Errorf("error: channel is empty")
http.Error(ctx.response, "channel is empty", http.StatusUnauthorized)
return nil
}
err := ctx.route.pubsub.Publish(ctx.request.Context(), *channel, pubsubEvent)
if err != nil {
logger.Debugf("error publishing patch: %v", err)
}
return writeEventHTTP(ctx, pubsubEvent)
}
}
func writeEventHTTP(ctx RouteContext, event pubsub.Event) error {
events := renderDOMEvents(ctx, event)
eventsData, err := json.Marshal(events)
if err != nil {
logger.Errorf("error marshaling patch: %v", err)
return err
}
ctx.response.Write(eventsData)
return nil
}
// set route template concurrency safe
func (rt *route) setTemplate(t *template.Template) {
rt.template = t
}
// get route template concurrency safe
func (rt *route) getTemplate() *template.Template {
return rt.template
}
// set route error template concurrency safe
func (rt *route) setErrorTemplate(t *template.Template) {
rt.errorTemplate = t
}
// get route error template concurrency safe
func (rt *route) getErrorTemplate() *template.Template {
return rt.errorTemplate
}
// set event templates concurrency safe
func (rt *route) setEventTemplates(templates eventTemplates) {
rt.eventTemplates = templates
}
// get event templates concurrency safe
func (rt *route) getEventTemplates() eventTemplates {
return rt.eventTemplates
}
func (rt *route) ServeHTTP(w http.ResponseWriter, r *http.Request) {
timing := servertiming.FromContext(r.Context())
defer timing.NewMetric("route").Start().Stop()
if r.URL.Path == "/favicon.ico" {
http.NotFound(w, r)
return
}
if r.Method == http.MethodHead {
w.Header().Add("X-FIR-WEBSOCKET-ENABLED", strconv.FormatBool(!rt.disableWebsocket))
w.WriteHeader(http.StatusNoContent)
return
}
if websocket.IsWebSocketUpgrade(r) {
// onWebsocket: upgrade to websocket
if rt.disableWebsocket {
http.Error(w, "websocket is disabled", http.StatusForbidden)
return
}
} else {
if rt.pathParamsFunc != nil {
r = r.WithContext(context.WithValue(r.Context(), PathParamsKey, rt.pathParamsFunc(r)))
}
}
if websocket.IsWebSocketUpgrade(r) {
onWebsocket(w, r, rt.cntrl)
} else if r.Header.Get("X-FIR-MODE") == "event" && r.Method == http.MethodPost {
// onEvents
var event Event
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()
err := decoder.Decode(&event)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if decoder.More() {
http.Error(w, "unknown fields in request body", http.StatusBadRequest)
return
}
if event.ID == "" {
http.Error(w, "event id is missing", http.StatusBadRequest)
return
}
eventCtx := RouteContext{
event: event,
request: r,
response: w,
route: rt,
}
onEventFunc, ok := rt.onEvents[strings.ToLower(event.ID)]
if !ok {
http.Error(w, "event id is not registered", http.StatusBadRequest)
return
}
// error event is not published
errorEvent := handleOnEventResult(onEventFunc(eventCtx), eventCtx, writeAndPublishEvents(eventCtx))
if errorEvent != nil {
writeEventHTTP(eventCtx, *errorEvent)
}
} else {
// postForm
if r.Method == http.MethodPost {
formAction := ""
values := r.URL.Query()
if len(values) == 1 {
event := values.Get("event")
if event != "" {
formAction = event
}
}
if formAction == "" && len(rt.onEvents) > 1 {
http.Error(w, "form action[?event=myaction] is missing and default onEvent can't be selected since there is more than 1", http.StatusBadRequest)
return
} else if formAction == "" && len(rt.onEvents) == 1 {
for k := range rt.onEvents {
formAction = k
}
}
err := r.ParseForm()
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
urlValues := r.PostForm
params, err := json.Marshal(urlValues)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
event := Event{
ID: formAction,
Params: params,
IsForm: true,
}
eventCtx := RouteContext{
event: event,
request: r,
response: w,
route: rt,
urlValues: urlValues,
}
onEventFunc, ok := rt.onEvents[event.ID]
if !ok {
http.Error(w, fmt.Sprintf("onEvent handler for %s not found", event.ID), http.StatusBadRequest)
return
}
handlePostFormResult(onEventFunc(eventCtx), eventCtx)
} else if r.Method == http.MethodGet {
// onLoad
event := Event{ID: rt.routeOpt.id}
eventCtx := RouteContext{
event: event,
request: r,
response: w,
route: rt,
isOnLoad: true,
}
handleOnLoadResult(rt.onLoad(eventCtx), nil, eventCtx)
} else {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
}
}
}
func handleOnEventResult(err error, ctx RouteContext, publish eventPublisher) *pubsub.Event {
target := ""
if ctx.event.Target != nil {
target = *ctx.event.Target
}
if err == nil {
publish(pubsub.Event{
ID: &ctx.event.ID,
State: eventstate.OK,
Target: &target,
ElementKey: ctx.event.ElementKey,
SessionID: ctx.event.SessionID,
})
return nil
}
switch errVal := err.(type) {
case *firErrors.Status:
errs := map[string]any{
ctx.event.ID: firErrors.User(errVal.Err).Error(),
"onevent": firErrors.User(errVal.Err).Error(),
}
return &pubsub.Event{
ID: &ctx.event.ID,
State: eventstate.Error,
Target: &target,
ElementKey: ctx.event.ElementKey,
Detail: &dom.Detail{Data: errs},
SessionID: ctx.event.SessionID,
}
case *firErrors.Fields:
fieldErrorsData := *errVal
fieldErrors := make(map[string]any)
for field, err := range fieldErrorsData {
fieldErrors[field] = err.Error()
}
errs := map[string]any{ctx.event.ID: fieldErrors}
return &pubsub.Event{
ID: &ctx.event.ID,
State: eventstate.Error,
Target: &target,
ElementKey: ctx.event.ElementKey,
Detail: &dom.Detail{Data: errs},
SessionID: ctx.event.SessionID,
}
case *routeData:
publish(pubsub.Event{
ID: &ctx.event.ID,
State: eventstate.OK,
Target: &target,
ElementKey: ctx.event.ElementKey,
Detail: &dom.Detail{Data: *errVal},
SessionID: ctx.event.SessionID,
})
return nil
case *routeDataWithState:
publish(pubsub.Event{
ID: &ctx.event.ID,
State: eventstate.OK,
Target: &target,
ElementKey: ctx.event.ElementKey,
Detail: &dom.Detail{Data: *errVal.routeData, State: *errVal.stateData},
SessionID: ctx.event.SessionID,
})
return nil
case *stateData:
publish(pubsub.Event{
ID: &ctx.event.ID,
State: eventstate.OK,
Target: &target,
ElementKey: ctx.event.ElementKey,
Detail: &dom.Detail{State: *errVal},
SessionID: ctx.event.SessionID,
})
return nil
default:
errs := map[string]any{
ctx.event.ID: firErrors.User(err).Error(),
"onevent": firErrors.User(err).Error(),
}
return &pubsub.Event{
ID: &ctx.event.ID,
State: eventstate.Error,
Target: &target,
ElementKey: ctx.event.ElementKey,
Detail: &dom.Detail{Data: errs},
SessionID: ctx.event.SessionID,
}
}
}
func handlePostFormResult(err error, ctx RouteContext) {
if err == nil {
http.Redirect(ctx.response, ctx.request, ctx.request.URL.Path, http.StatusFound)
return
}
switch err.(type) {
case *routeData, *stateData, *routeDataWithState:
http.Redirect(ctx.response, ctx.request, ctx.request.URL.Path, http.StatusFound)
default:
handleOnLoadResult(ctx.route.onLoad(ctx), err, ctx)
}
}
func handleOnLoadResult(err, onFormErr error, ctx RouteContext) {
if err == nil {
errs := make(map[string]any)
if onFormErr != nil {
fieldErrorsVal, ok := onFormErr.(*firErrors.Fields)
if !ok {
errs = map[string]any{
ctx.event.ID: onFormErr.Error(),
}
} else {
errs = map[string]any{
ctx.event.ID: fieldErrorsVal.Map(),
}
}
}
renderRoute(ctx, false)(routeData{"errors": errs})
return
}
switch errVal := err.(type) {
case *routeData:
onLoadData := *errVal
errs := make(map[string]any)
if onFormErr != nil {
fieldErrorsVal, ok := onFormErr.(*firErrors.Fields)
if !ok {
errs = map[string]any{
ctx.event.ID: onFormErr.Error(),
}
} else {
errs = map[string]any{
ctx.event.ID: fieldErrorsVal.Map(),
}
}
}
onLoadData["errors"] = errs
renderRoute(ctx, false)(onLoadData)
case *routeDataWithState:
onLoadData := *errVal.routeData
errs := make(map[string]any)
if onFormErr != nil {
fieldErrorsVal, ok := onFormErr.(*firErrors.Fields)
if !ok {
errs = map[string]any{
ctx.event.ID: onFormErr.Error(),
}
} else {
errs = map[string]any{
ctx.event.ID: fieldErrorsVal.Map(),
}
}
}
onLoadData["errors"] = errs
renderRoute(ctx, false)(onLoadData)
case firErrors.Status:
errs := make(map[string]any)
if onFormErr != nil {
fieldErrorsVal, ok := onFormErr.(*firErrors.Fields)
if !ok {
errs = map[string]any{
ctx.event.ID: onFormErr.Error(),
"onload": fmt.Sprintf("%v", errVal.Error())}
} else {
errs = map[string]any{
ctx.event.ID: fieldErrorsVal.Map(),
"onload": fmt.Sprintf("%v", errVal.Error()),
}
}
}
renderRoute(ctx, true)(routeData{"errors": errs})
case firErrors.Fields:
errs := make(map[string]any)
if onFormErr != nil {
fieldErrorsVal, ok := onFormErr.(*firErrors.Fields)
if !ok {
errs = map[string]any{
ctx.event.ID: onFormErr.Error(),
"onload": fmt.Sprintf("%v", errVal)}
} else {
errs = map[string]any{
ctx.event.ID: fieldErrorsVal.Map(),
"onload": fmt.Sprintf("%v", errVal),
}
}
}
renderRoute(ctx, false)(routeData{"errors": errs})
default:
var errs map[string]any
if onFormErr != nil {
fieldErrorsVal, ok := onFormErr.(*firErrors.Fields)
if !ok {
// err is not nil and not routeData and onFormErr is not nil and not fieldErrors
// merge err and onFormErr
errs = map[string]any{
ctx.event.ID: onFormErr,
"onload": errVal,
}
} else {
errs = map[string]any{
ctx.event.ID: fieldErrorsVal.Map(),
"onload": fmt.Sprintf("%v", errVal),
}
}
} else {
errs = map[string]any{
"onload": err.Error()}
}
renderRoute(ctx, false)(routeData{"errors": errs})
}
}
func (rt *route) parseTemplates() {
rt.Lock()
defer rt.Unlock()
var err error
if rt.getTemplate() == nil || (rt.getTemplate() != nil && rt.disableTemplateCache) {
var successEventTemplates eventTemplates
var rtTemplate *template.Template
rtTemplate, successEventTemplates, err = parseTemplate(rt.routeOpt)
if err != nil {
panic(err)
}
rtTemplate.Option("missingkey=zero")
rt.setTemplate(rtTemplate)
var errorEventTemplates eventTemplates
var rtErrorTemplate *template.Template
rtErrorTemplate, errorEventTemplates, err = parseErrorTemplate(rt.routeOpt)
if err != nil {
panic(err)
}
rtTemplate.Option("missingkey=zero")
rt.setErrorTemplate(rtErrorTemplate)
rtEventTemplates := deepMergeEventTemplates(errorEventTemplates, successEventTemplates)
for eventID, templates := range rt.getEventTemplates() {
var templatesStr string
for k := range templates {
if k == "-" {
continue
}
templatesStr += k + " "
}
fmt.Println("eventID: ", eventID, " templates: ", templatesStr)
}
rt.setEventTemplates(rtEventTemplates)
}
}