Last active
April 9, 2023 11:03
-
-
Save sonus21/a7e9a632aa254f25fc57e8c7f5bb8643 to your computer and use it in GitHub Desktop.
Main package
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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("/v1/orders", controller.HandleCreateOrder) | |
r.Get("/v1/orders/{orderId:[a-z0-9-]+}", controller.OrderDetails) | |
err = http.ListenAndServe(":3000", r) | |
if err == nil { | |
log.Fatal(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment