I am trying to prototype this little golang app and hoping to get some advice on how to go about managing my database and redis connection objects.
I want to create a a 'service layer' that will have all the product related logic, so maybe a ProductService.
I want ProductService to have a reference to both redis and my database client.
What would this ProductService look like roughly, and if I need to create a single instance of this and use it throughout the app do I define it in a var?
func main() {
db, err := gorm.Open("postgres", "host=localhost user=blankman dbname=blank_development sslmode=disable password=")
if err != nil {
log.Fatalf("Got error when connect database, the error is '%v'", err)
}
defer db.Close()
redis := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "",
DB: 0,
})
pong, err := redis.Ping().Result()
fmt.Println(pong, err)
router := mux.NewRouter()
router.HandleFunc("/products", GetProducts).Methods("GET")
log.Fatal(http.ListenAndServe(":3001", router))
}
My GetProducts handler has your regular signature:
func GetProducts(w http.ResponseWriter, r *http.Request)
How am I suppose to pass in the ProductsService into this handler? It looks like the request/response are somehow automatically passed to this handler by MUX, so unsure how it can get a reference to the ProductService?