[Question] Since main.go is generated, where should initialization logic be performed? i.e. setting up a database #146
-
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hey @donovanrost! The automatic dependency injection should help you with initializing your dependencies (like a database) on boot. The nice thing about this is that you will (soon) be able to do this with other entrypoints like tests so there's much less initialization boilerplate. I wrote an example in this comment that I think is relevant here. Create an package env
import "github.com/caarlos0/env"
// Load the environment
func Load() (*Env, error) {
var e Env
if err := env.Parse(&env); err != nil {
return err
}
return &e, nil
}
type Env struct {
DatabaseURL string `env:DATABASE_URL`
} Then in a package db
import "app.com/env"
import "github.com/jackc/pgx"
func Dial(env *env.Env) (*Client, error) {
return pgx.Dial(env.DatabaseURL)
}
type Client = pgx.Client Finally in your package controller
import "app.com/db"
type Controller struct {
DB *db.Client
}
type User struct {
Name string
}
func (c *Controller) Index() ([]*User, error) {
rows, err := c.DB.Query("select * from users")
if err != nil {
return nil, err
}
// TODO: turn rows into users
return users, nil
} With that you can now switch out your development database with your production database using: DATABASE_URL="..." bud run Let me know how that works for you! We still may need to be able to hook into |
Beta Was this translation helpful? Give feedback.
Hey @donovanrost! The automatic dependency injection should help you with initializing your dependencies (like a database) on boot. The nice thing about this is that you will (soon) be able to do this with other entrypoints like tests so there's much less initialization boilerplate.
I wrote an example in this comment that I think is relevant here.
Create an
env/env.go
file:Then in a
db/db.go
file: