livebud / bud

The Full-Stack Web Framework for Go
MIT License
5.53k stars 181 forks source link

How can I connect a database using Bud? #325

Closed Fuerback closed 1 year ago

Fuerback commented 1 year ago

I'm wondering how and where integrates a database (Postegres) using Bud.

I believe is similar to that https://github.com/livebud/bud/issues/210, but not sure.

any thoughts?

Fuerback commented 1 year ago

In my case, I'm using Postgres as a database and I could find the solution for that:

First I created a connection file in:

├── bud
├── controller
├── pkg
│   └── models
│       └── conn.go
package models

type Conn = pgx.Conn

func Open() (*Conn, error) {
    db, err := pgx.Connect(context.Background(), "POSTGRES_CONN")
    if err != nil {
        return nil, fmt.Errorf("open db: %w", err)
    }
    return db, nil
}

Then I used it on the controller:

package controller

type Controller struct {
    DB *models.Conn
}

Done! Thanks to @matthewmueller !