-
Notifications
You must be signed in to change notification settings - Fork 28
/
implementation_switcher.go
68 lines (56 loc) · 1.82 KB
/
implementation_switcher.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
package webapp
import (
"context"
"fmt"
"net/http"
"github.com/authgear/authgear-server/pkg/lib/config"
)
type ImplementationSwitcherMiddleware struct {
UIConfig *config.UIConfig
}
type implementationSwitcherContextKeyType struct{}
var implementationSwitcherContextKey = implementationSwitcherContextKeyType{}
type implementationSwitcherContext struct {
UIImplementation config.UIImplementation
}
func WithUIImplementation(ctx context.Context, impl config.UIImplementation) context.Context {
v, ok := ctx.Value(implementationSwitcherContextKey).(*implementationSwitcherContext)
if ok {
v.UIImplementation = impl
return ctx
}
return context.WithValue(ctx, implementationSwitcherContextKey, &implementationSwitcherContext{
UIImplementation: impl,
})
}
func GetUIImplementation(ctx context.Context) config.UIImplementation {
v, ok := ctx.Value(implementationSwitcherContextKey).(*implementationSwitcherContext)
if !ok {
return config.UIImplementationDefault
}
return v.UIImplementation
}
func (m *ImplementationSwitcherMiddleware) Handle(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r = r.WithContext(WithUIImplementation(r.Context(), m.UIConfig.Implementation))
next.ServeHTTP(w, r)
})
}
type ImplementationSwitcherHandler struct {
Interaction http.Handler
Authflow http.Handler
AuthflowV2 http.Handler
}
func (h *ImplementationSwitcherHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
impl := GetUIImplementation(r.Context()).WithDefault()
switch impl {
case config.UIImplementationAuthflow:
h.Authflow.ServeHTTP(w, r)
case config.UIImplementationAuthflowV2:
h.AuthflowV2.ServeHTTP(w, r)
case config.UIImplementationInteraction:
h.Interaction.ServeHTTP(w, r)
default:
panic(fmt.Errorf("unknown ui implementation %s", impl))
}
}