Skip to content

Instantly share code, notes, and snippets.

@rlgino
Last active February 23, 2023 02:40
Show Gist options
  • Save rlgino/26538ca67e8e05882f9dafe4c1bc1f5c to your computer and use it in GitHub Desktop.
Save rlgino/26538ca67e8e05882f9dafe4c1bc1f5c to your computer and use it in GitHub Desktop.
Variables Globales en Golang, si o no?
package db
import "github.com/go-pg/pg/v10"
var db *pg.DB // Nuestra variable global, la cual probablemente inicializamos en el mail.go
type Customer struct {
ID int
Name string
LastName string
}
func SaveCustomer(cust Customer) error {
// Al ejecutar nuestro test si no satisfacemos `db` esto va a fallar por un nil pointer
_, err := db.Exec("insert into customers (id, name, lastname) values (%d, %s, %s)", cust.ID, cust.Name, cust.LastName)
if err != nil {
return err
}
return nil
}
// Un aproach es crear una estructura y poder inyectar la dependencia por constructor
type CustomerRepository struct {
db *pg.DB
}
// NewCustomerRepository crea un repositorio y le inyecta
// la DB, por lo que en nuestro test
// si siempre usamos el constructor
// lograremos satisfacer esa dependecia
func NewCustomerRepository(db *pg.DB) CustomerRepository {
return CustomerRepository{
db: db,
}
}
func (repo CustomerRepository) SaveCustomer(cust Customer) error {
// Al ejecutar nuestro test si no satisfacemos `db` esto va a fallar por un nil pointer
_, err := repo.db.Exec("insert into customers (id, name, lastname) values (%d, %s, %s)", cust.ID, cust.Name, cust.LastName)
if err != nil {
return err
}
return nil
}
package db
import "github.com/go-pg/pg/v10"
var db *pg.DB
func GetDB() *pg.DB {
if db == nil {
db = pg.Connect(&pg.Options{
Addr: "localhost:5432",
User: "postgres",
Password: "password",
Database: "testdb",
})
// outside we need defer db.Close()
}
return db
}
package main
import "postgres/db"
func main() {
connection := db.GetDB() // Si es nula, se inicializa la DB
_, err := connection.Exec("insert into customers(...) values (...)")
if err != nil {
panic(err.Error())
}
// ...
connection := db.GetDB() // Es la misma conexión que arriba.
_, err := connection.Exec("insert into products(...) values (...)")
if err != nil {
panic(err.Error())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment