tl;dr
What is the right way to set Store
to be shared between multiple services in this example: https://github.com/th0th/goblog/blob/2b2d7ac51978de41f392396309424043817a49d7/store/store.go#L29
Details
Greetings, I am trying to comprehend how go works by creating a simple MVC-ish blog REST API. I have planned the application to consist of 3 packages/layers:
models
Holds the structs of data. Defines the interfaces for database access layers of these structs.
store
Presents the actual database connections. Implements the interfaces from models. All database access is done through this implementation.
api
REST API related stuff. Routes and such.
I have a Store
struct in store
package, which holds the services:
// Store wraps all services
type Store struct {
DB *sqlx.DB
CategoryService CategoryService
PostService PostService
}
And here is the CategoryService
(PostService
is also like this. They both have methods for CRUD actions.):
// CategoryService represents a service for managing categories.
type CategoryService struct {
store *Store
}
When I create an instance of this Store
, I need to set store of every single service.
// New creates and returns new Store
func New() Store {
var s Store
db, err := sqlx.Connect("mysql", "<user>:<pass>@(localhost:3306)/goblog")
if err != nil {
log.Fatal(err)
}
s.DB = db
s.CategoryService.store = &s
s.PostService.store = &s
return s
}
I want store to be shared between services, what is the correct approach? Am I doing something wrong?