I've set up a GitHub workflow to start a Postgres instance inside a docker container. I then execute my web API to simply prove it connects. This satisfies the workflow.
My workflow
name: Build
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
build:
runs-on: ubuntu-latest
services:
postgres:
image: postgres:10.8
env:
POSTGRES_USER: test
POSTGRES_PASSWORD: test
POSTGRES_DB: test
POSTGRES_PORT: 5432
ports:
- 5432/tcp
options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5
steps:
- uses: actions/checkout@v2
- name: Set up Go
uses: actions/setup-go@v2
with:
go-version: 1.15
- name: Run
env:
# These are the expected envs in my code
DB_HOST: localhost
DB_USER: test
DB_PASSWORD: test
DB_NAME: test
DB_PORT: 5432
DB_DIALECT: postgres
PORT: 8080
run: make run
For brevity I've trimmed irrelavent bits of code out, this is my database package:
// Config Model
type Config struct {
Host string
Name string
User string
Password string
Port string
Dialect string
}
// Open a new connection to a database
func Open(c Config) (*gorm.DB, error) {
dsn := fmt.Sprintf("host=%s port=%s dbname=%s password=%s user=%s sslmode=disable",
c.Host,
c.Port,
c.Name,
c.Password,
c.User,
)
db, err := gorm.Open(postgres.New(postgres.Config{
DriverName: c.Dialect,
DSN: dsn,
}), &gorm.Config{})
if err != nil {
return nil, fmt.Errorf("sql.Open: %v", err)
}
return db, nil
}
And this is called from my main package
func main() {
// Create Database Configuration
dbConfig := database.Config{
Host: os.Getenv("DB_HOST"),
Name: os.Getenv("DB_NAME"),
User: os.Getenv("DB_USER"),
Port: os.Getenv("DB_PORT"),
Password: os.Getenv("DB_PASSWORD"),
Dialect: os.Getenv("DB_DIALECT"),
}
// Connect to database
db, err := database.Open(dbConfig)
if err != nil {
log.Fatalf("failed to connect to database: %s", err)
}
}
The code fails to connect during the workflow with the given error:
go run -ldflags "-X main.Version=afc0042" cmd/api/main.go
2021/02/10 09:55:12 Running Version: afc0042
2021/02/10 09:55:12 failed to connect to database: sql.Open: dial tcp [::1]:5432: connect: connection refused
2021/02/10 09:55:12 /home/runner/work/database/database.go:32
[error] failed to initialize database, got error dial tcp [::1]:5432: connect: connection refused