-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathmain.go
116 lines (90 loc) · 2.15 KB
/
main.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 (
"context"
"encoding/json"
"log"
"net/http"
"os"
)
func main() {
logger := log.New(os.Stdout, "", log.LstdFlags)
handler := NewSubscribeHandler(logger, nopMetricsClient{})
httpHandler := func(w http.ResponseWriter, r *http.Request) {
var request SubscribeHTTPRequest
err := json.NewDecoder(r.Body).Decode(&request)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
cmd := Subscribe{
Email: request.Email,
NewsletterID: request.NewsletterID,
}
user, err := userFromRequest(r)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
ctx := ContextWithUser(r.Context(), user)
err = handler.Execute(ctx, cmd)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
}
eventHandler := func(ctx context.Context, event UserSignedUp) error {
if !event.ProductNewsConsent {
return nil
}
fakeUser := User{
ID: event.ID,
Active: true,
}
ctx = ContextWithUser(ctx, fakeUser)
cmd := Subscribe{
Email: event.Email,
NewsletterID: "product-news",
}
return handler.Execute(ctx, cmd)
}
rpcHandler := func(ctx context.Context, req SubscribeRPCRequest) error {
fakeUser := User{
ID: "1", // Missing ID in the context, let's assume it's the root user making changes
Active: true,
}
ctx = ContextWithUser(ctx, fakeUser)
cmd := Subscribe{
Email: req.Email,
NewsletterID: "product-news",
}
return handler.Execute(ctx, cmd)
}
_ = httpHandler
_ = eventHandler
_ = rpcHandler
}
func userFromRequest(r *http.Request) (User, error) {
token := r.Header.Get("Authorization")
// Verify the token, create the user struct out of it
_ = token
user := User{
ID: "1000",
Active: true,
}
return user, nil
}
type SubscribeHTTPRequest struct {
Email string `json:"email"`
NewsletterID string `json:"newsletter_id"`
}
type SubscribeRPCRequest struct {
Email string
NewsletterID string
}
type UserSignedUp struct {
ID string
Email string
ProductNewsConsent bool
}
type nopMetricsClient struct{}
func (c nopMetricsClient) Inc(key string, value int) {}