forked from ThreeDotsLabs/watermill
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
83 lines (68 loc) · 1.56 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
package main
import (
stdSQL "database/sql"
"encoding/json"
"log"
"net/http"
"github.com/ThreeDotsLabs/watermill"
"github.com/ThreeDotsLabs/watermill-sql/v3/pkg/sql"
"github.com/ThreeDotsLabs/watermill/message"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
driver "github.com/go-sql-driver/mysql"
)
const topic = "counter"
func main() {
db := createDB()
logger := watermill.NewStdLogger(false, false)
r := chi.NewRouter()
r.Use(middleware.Recoverer)
r.Use(middleware.Logger)
publisher, err := sql.NewPublisher(
db,
sql.PublisherConfig{
SchemaAdapter: sql.DefaultMySQLSchema{},
},
logger,
)
if err != nil {
panic(err)
}
r.Post("/count/{counterUUID}", func(w http.ResponseWriter, r *http.Request) {
payload, err := json.Marshal(messagePayload{
CounterUUID: chi.URLParam(r, "counterUUID"),
})
if err != nil {
log.Print(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
msg := message.NewMessage(watermill.NewUUID(), payload)
if err := publisher.Publish(topic, msg); err != nil {
log.Print(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusNoContent)
})
http.ListenAndServe(":8080", r)
}
type messagePayload struct {
CounterUUID string `json:"counter_uuid"`
}
func createDB() *stdSQL.DB {
conf := driver.NewConfig()
conf.Net = "tcp"
conf.User = "root"
conf.Addr = "mysql"
conf.DBName = "example"
db, err := stdSQL.Open("mysql", conf.FormatDSN())
if err != nil {
panic(err)
}
err = db.Ping()
if err != nil {
panic(err)
}
return db
}