Skip to content

Commit

Permalink
Added alternative to connect to a database via dsn
Browse files Browse the repository at this point in the history
  • Loading branch information
nicola-iacovelli committed Nov 26, 2023
1 parent 80576b7 commit a263f26
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 19 deletions.
24 changes: 13 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,17 +49,19 @@ docker run -p 8080:8080 ghcr.io/nico-iaco/food-track-be:latest -e {ALL_ENV_VARIA

## Environment variables

| Name | Description | Default value |
|------------------|-----------------------------------|---------------|
| PORT | Port on which the app will listen | 8080 |
| GIN_MODE | Release type of app | |
| DB_HOST | Database host | |
| DB_PORT | Database port | |
| DB_NAME | Database name | |
| DB_USER | Database user | |
| DB_PASSWORD | Database password | |
| GROCERY_BASE_URL | Base url for grocery-be app | |
| DB_TIMEOUT | Database connection timeout | |
| Name | Description | Default value |
|------------------|-----------------------------------------------------|---------------|
| PORT | Port on which the app will listen | 8080 |
| GIN_MODE | Release type of app | |
| DB_HOST | Database host | |
| DB_PORT | Database port | |
| DB_NAME | Database name | |
| DB_USER | Database user | |
| DB_USER | Database user | |
| DB_PASSWORD | Database password | |
| DSN | Database DSN (Alternative to DB_HOST/USER/PASSWORD) | |
| GROCERY_BASE_URL | Base url for grocery-be app | |
| DB_TIMEOUT | Database connection timeout | |

## Database

Expand Down
24 changes: 16 additions & 8 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,23 +34,31 @@ import (
// @host localhost:8080
// @BasePath /api/meal

// @externalDocs.description OpenAPI
// @externalDocs.url https://swagger.io/resources/open-api/
// @externalDocs.description OpenAPI
// @externalDocs.url https://swagger.io/resources/open-api/
func main() {

dsn := os.Getenv("DSN")
dbHost := os.Getenv("DB_HOST")
dbPort := os.Getenv("DB_PORT")
dbUser := os.Getenv("DB_USER")
dbPassword := os.Getenv("DB_PASSWORD")
dbName := os.Getenv("DB_NAME")
dbTimeout, _ := strconv.ParseInt(os.Getenv("DB_TIMEOUT"), 10, 64)

pgconn := pgdriver.NewConnector(
pgdriver.WithAddr(dbHost+":"+dbPort),
pgdriver.WithUser(dbUser),
pgdriver.WithPassword(dbPassword),
pgdriver.WithDatabase(dbName),
)
var pgconn *pgdriver.Connector

if dsn != "" {
pgconn = pgdriver.NewConnector(pgdriver.WithDSN(dsn))
} else {
pgconn = pgdriver.NewConnector(
pgdriver.WithAddr(dbHost+":"+dbPort),
pgdriver.WithUser(dbUser),
pgdriver.WithPassword(dbPassword),
pgdriver.WithDatabase(dbName),
)
}

sqldb := sql.OpenDB(pgconn)

db := bun.NewDB(sqldb, pgdialect.New())
Expand Down

0 comments on commit a263f26

Please sign in to comment.