如何解决使用 Postgres 在 Google App Engine 上使用 API
我正在尝试使用 Go+Gin+PGX 连接到我的 GAE Postgres sql 数据库。我激活了 Postgres sql api,这个程序在我的本地机器上运行,但不在 GAE 上运行。我认为它不是通过 pgx 连接数据库,但我不确定。
main.go
在我的本地机器和 psql
实例上运行,但在部署到 GAE 后无法通过 GCP sql 实例中的公共 IP 连接到数据库。我已经修改了我的工作代码以修复 MWE。
package main
import (
"fmt"
"os"
"github.com/gin-gonic/gin"
"github.com/jackc/pgx/v4"
"golang.org/x/net/context"
)
func main() {
conn,err := connectDB()
if err != nil {
os.Exit(1)
}
defer conn.Close(context.Background())
router := gin.Default()
router.GET("/",func(c *gin.Context) {
c.JSON(200,gin.H{
"message": "pong",})
})
router.Run(":8080")
}
func connectDB() (c *pgx.Conn,err error) {
postgres := "postgresql://postgres:root@35.236.60.144:5432/goapi" //35.236.60.144
conn,err := pgx.Connect(context.Background(),postgres)
if err != nil {
fmt.Fprintf(os.Stderr,"Unable to connect to database:\n\t%v\n",err.Error())
return nil,err
}
err = conn.Ping(context.Background())
if err != nil {
fmt.Fprintf(os.Stderr,"Unable to ping:\n\t%v\n",err.Error())
return nil,err
}
return conn,err
}
如果我使用 Postman 执行到 GAE 网站的 GET,那么我得到
<html>
<head>
<Meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>500 Server Error</title>
</head>
<body text=#000000 bgcolor=#ffffff>
<h1>Error: Server Error</h1>
<h2>The server encountered an error and Could not complete your request.<p>Please try again in 30 seconds.</h2>
<h2></h2>
</body>
</html>
对应的 GAE 错误堆栈跟踪示例为
runtime error: invalid memory address or nil pointer dereference [signal SIGSEGV: segmentation violation code=0x1 addr=0x8 pc=0xaabec7]
at
github.com/jackc/pgx/v4.(*Conn).exec (conn.go:413)
at
github.com/jackc/pgx/v4.(*Conn).Exec (conn.go:396)
at
github.com/jackc/pgx/v4.(*Conn).Ping (conn.go:347)
at
main.connectDB (main.go:41)
at
main.main (main.go:15)
当我查看日志时,我看到...
Unable to connection to database: Failed to connect to `host=35.236.60.144 user=postgres database=goapi`: dial error (dial tcp 35.236.60.144:5432: connect: connection timed out)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。