I'm studying "Clean Architecture" by Uncle Bob (https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html).
I'm also studying Golang.
I'm trying to understand if the following is a best practice or one to avoid.
Example
db.go
:
package db
import (
"errors"
"log"
"os"
"github.com/go-pg/pg/v9"
)
var (
pgDatabaseUrl = os.Getenv("DATABASE_URL")
pgDatabase *pg.DB
)
func New() *pg.DB {
options, _ := pg.ParseURL(pgDatabaseUrl)
pgDatabase = pg.Connect(options)
if pgDatabase == nil {
err := errors.New("error connecting to database")
log.Fatal(err)
}
return pgDatabase
}
func Close() {
err := pgDatabase.Close()
if err != nil {
panic(err)
}
}
func Get() *pg.DB {
if pgDatabase == nil {
panic(errors.New("postgres database not initialized"))
}
return pgDatabase
}
Is it ok to have a (private) var pgDatabase *pg.DB
exposed through Get()
and used by Close()
?
In some projects I use db.Get()
to get a *pg.DB
instance already initialized elsewhere:
func LoadUser(ctx context.Context, key string) (auth.User, error) {
user := new(models.User)
err := db.Get().Model(user).Where("email = ?", key).Select() // <--- I'm using it here
if err != nil {
return nil, err
}
return user, nil
}
What do you think about?
Aucun commentaire:
Enregistrer un commentaire