-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathapp_response.go
116 lines (94 loc) · 2.02 KB
/
app_response.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
package main
import (
"github.com/gorilla/sessions"
)
type AppResponse struct {
Session *sessions.Session
User *User
Status int
Error error
Redirect string
State map[string]interface{}
Meta map[string]string
}
func NewAppResponse() *AppResponse {
return &AppResponse{
State: make(map[string]interface{}),
Meta: make(map[string]string),
}
}
func (a *AppResponse) WithSession(session *sessions.Session) *AppResponse {
c := *a
c.Session = session
return &c
}
func (a *AppResponse) WithUser(user *User) *AppResponse {
c := *a
c.User = user
return &c
}
func (a *AppResponse) WithStatus(status int) *AppResponse {
c := *a
c.Status = status
return &c
}
func (a *AppResponse) WithError(err error) *AppResponse {
c := *a
c.Error = err
return &c
}
func (a *AppResponse) WithRedirect(redirect string) *AppResponse {
c := *a
c.Redirect = redirect
return &c
}
func (a *AppResponse) WithState(state map[string]interface{}) *AppResponse {
c := *a
c.State = state
return &c
}
func (a *AppResponse) WithMeta(meta map[string]string) *AppResponse {
c := *a
c.Meta = meta
return &c
}
func (a *AppResponse) GetMeta(name, defaultValue string) string {
if v, ok := a.Meta[name]; ok {
return v
}
return defaultValue
}
func (a *AppResponse) ShallowMergeState(state map[string]interface{}) *AppResponse {
s := make(map[string]interface{})
for k, v := range a.State {
s[k] = v
}
for k, v := range state {
s[k] = v
}
return a.WithState(s)
}
func (a *AppResponse) MergeMeta(meta map[string]string) *AppResponse {
m := make(map[string]string)
for k, v := range a.Meta {
m[k] = v
}
for k, v := range meta {
m[k] = v
}
return a.WithMeta(m)
}
func (a *AppResponse) MergeUserContext(user *User) *AppResponse {
if user == nil {
delete(a.Session.Values, "user_id")
} else {
a.Session.Values["user_id"] = user.ID
}
return a.WithUser(user).ShallowMergeState(map[string]interface{}{
"authentication": map[string]interface{}{
"loading": false,
"error": nil,
"user": user,
},
})
}