gpt4 book ai didi

postgresql - 在GitHub Actions中运行Postgres以测试我的Go API

转载 作者:行者123 更新时间:2023-12-03 10:09:07 25 4
gpt4 key购买 nike

我已经建立了一个GitHub工作流程来在Docker容器中启动一个Postgres实例。然后,我执行我的Web API以简单地证明它可以连接。这满足了工作流程。
我的工作流程

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
为简洁起见,我将一些不相关的代码裁剪掉了,这是我的数据库包:
// 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
}
这是从我的主包中调用的
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)
}
}
代码在工作流期间无法连接,并显示给定错误:
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

最佳答案

仅当您尝试在本地连接服务器时,您才可以使用localhost,因为docker不在您的计算机中本地,因此您不能使用localhost,除非您位于docker容器内。
尝试使用port forward

ports:
- 5432:5432 //update this one

关于postgresql - 在GitHub Actions中运行Postgres以测试我的Go API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66134691/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com