Skip to content

Commit

Permalink
Merge pull request #19 from edwinvautier/feat_env-db
Browse files Browse the repository at this point in the history
Read db config from .env file
  • Loading branch information
Edwin Vautier authored Mar 29, 2021
2 parents 2ccd44f + 73980bb commit a95fa2f
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 7 deletions.
8 changes: 7 additions & 1 deletion templates/.env.dist.template
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,10 @@ TOKEN_VALID_DURATION=60
RSA_PUBLIC_PATH=../public.pem
RSA_PRIVATE_PATH=../private.pem
RSA_PASSWORD=password
DOMAIN=localhost{{end}}
DOMAIN=localhost{{end}}

DB_USER=root
DB_PASSWORD=root
DB_NAME=db
DB_HOST={{.DBMS}}
DB_PORT={{if eq .DBMS "postgres"}}5432{{else}}3306{{end}}
12 changes: 7 additions & 5 deletions templates/main.go.template
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,12 @@ import (
"os"
"os/signal"
"syscall"
"strconv"

"time"

"github.com/caarlos0/env"
"{{.GoPackageFullPath}}/shared/database"
"{{.GoPackageFullPath}}/shared/env"
"{{.GoPackageFullPath}}/shared/helpers"
"{{.GoPackageFullPath}}/api/routes"
"github.com/gin-gonic/gin"
Expand All @@ -21,10 +22,11 @@ func main() {

// Connect to database and execute migrations
cfg := database.Config{}
if err := env.Parse(&cfg); err != nil {
log.Fatal(err)
}

cfg.User = env.GoDotEnvVariable("DB_USER")
cfg.Password = env.GoDotEnvVariable("DB_PASSWORD")
cfg.Port, _ = strconv.ParseInt(env.GoDotEnvVariable("DB_PORT"), 10, 0)
cfg.Name = env.GoDotEnvVariable("DB_NAME")
cfg.Host = env.GoDotEnvVariable("DB_HOST")
err := database.Init(cfg)
helpers.DieOnError("database connection failed", err)
database.Migrate()
Expand Down
2 changes: 1 addition & 1 deletion templates/shared/database/connector.go.template
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ var Db *gorm.DB
type Config struct {
User string `env:"DB_USER"`
Password string `env:"DB_PASSWORD"`
Port int `env:"DB_PORT" envDefault:"5432"`
Port int64 `env:"DB_PORT" envDefault:"5432"`
Host string `env:"DB_HOST"`
Name string `env:"DB_NAME"`
}
Expand Down

0 comments on commit a95fa2f

Please sign in to comment.