-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
77 lines (69 loc) · 2.09 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
package main
import (
"database/sql"
"github.com/sonus21/db-read-write/controller"
"github.com/sonus21/db-read-write/pkg/database"
"log"
"net/http"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
)
func getPrimaryDbConfig() database.MySqlConfig {
// use any other mechanism like viper/toml/env file to create the cpnfig
return database.MySqlConfig{
Host: "localhost",
Port: 3306,
Database: "my_app_db",
Username: "my_app",
Password: "my_app_pass",
MaxConnectionRetries: 3,
MaxOpenConnection: 30,
MaxIdleConnection: 5,
ConnectionLifetime: 5,
}
}
func getSecondaryDbConfig() database.MySqlConfig {
// use any other mechanism like viper/toml/env file to create the config
return database.MySqlConfig{
Host: "localhost",
Port: 3306,
Database: "my_app_db",
Username: "my_app_reader",
Password: "my_app_reader_pass",
MaxConnectionRetries: 3,
MaxOpenConnection: 30,
MaxIdleConnection: 5,
ConnectionLifetime: 5,
}
}
func main() {
// get primary database configurations and create primary database
primary, err := database.MySqlDataBase(getPrimaryDbConfig())
defer primary.Close()
if err != nil {
panic("Primary database could not be created" + err.Error())
}
// get secondary database configurations and create secondary database
secondary, err := database.MySqlDataBase(getSecondaryDbConfig())
defer secondary.Close()
if err != nil {
panic("Secondary database could not be created" + err.Error())
}
// initialize database map
databases := map[string]*sql.DB{
database.Primary: primary,
database.Secondary: secondary,
}
// initialize database
database.Init(databases, database.Primary)
r := chi.NewRouter()
r.Use(middleware.Logger)
// add database middleware
r.Use(database.Middleware())
r.Post("/api/v1/orders", controller.HandleCreateOrder)
r.Get("/api/v1/orders/{orderId:[0-9-]+}", controller.OrderDetails)
err = http.ListenAndServe(":3000", r)
if err == nil {
log.Fatal(err)
}
}