forked from ThreeDotsLabs/watermill
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
84 lines (70 loc) · 1.55 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
package main
import (
"context"
"database/sql"
"fmt"
"math/rand"
"time"
"github.com/kelseyhightower/envconfig"
_ "github.com/lib/pq"
)
type config struct {
Port int `envconfig:"PORT" required:"true"`
DatabaseURL string `envconfig:"DATABASE_URL" required:"true"`
PubSubProjectID string `envconfig:"PUBSUB_PROJECT_ID" required:"true"`
}
func main() {
var cfg config
err := envconfig.Process("", &cfg)
if err != nil {
panic(err)
}
db, err := sql.Open("postgres", cfg.DatabaseURL)
if err != nil {
panic(err)
}
err = MigrateDB(db)
if err != nil {
panic(err)
}
repo := NewRepository(db)
routers, err := NewRouters(cfg, repo)
if err != nil {
panic(err)
}
go func() {
err := routers.EventsRouter.Run(context.Background())
if err != nil {
panic(err)
}
}()
go func() {
err := routers.SSERouter.Run(context.Background())
if err != nil {
panic(err)
}
}()
go func() {
// This goroutine simulates some events being published in the background
ctx := context.Background()
for {
postID := 1 + rand.Intn(2)
if rand.Intn(2) == 0 {
_ = routers.EventBus.Publish(ctx, PostViewed{
PostID: postID,
})
} else {
_ = routers.EventBus.Publish(ctx, PostReactionAdded{
PostID: postID,
ReactionID: allReactions[rand.Intn(len(allReactions))].ID,
})
}
time.Sleep(time.Millisecond * time.Duration(3000+rand.Intn(5000)))
}
}()
handler := NewHandler(repo, routers.EventBus, routers.SSERouter)
err = handler.Start(fmt.Sprintf(":%d", cfg.Port))
if err != nil {
panic(err)
}
}