【问题标题】:How to connect to Cloud-SQL from Cloud Function in Go?如何从 Go 中的 Cloud Function 连接到 Cloud-SQL?
【发布时间】:2019-03-25 08:21:07
【问题描述】:

对于一个项目,我正在尝试将云功能连接到云 sql 数据库设置,如 this quickstart guide 中所述。

功能配置在同一个区域,服务账号的角色Cloud SQL-Client。我通过我的电脑调用了这个函数:

gcloud functions call <function-name> --region=<region> --data '{"recipient":"hello","requester":"hello","message":"test"}'

与函数的连接正常,似乎只是对数据库的身份验证不起作用,但我不知道失败的地方。

我多次检查了密码、用户名和连接名,重新设置了密码,还是不行。 我发现问题here与将云函数连接到云sql有关。

我尝试用单引号将dsn-string 中的密码括起来,以确保密码中的字符转义不成问题。

我还检查了传入的环境变量,它们是我在配置中输入的。

该函数只是为了测试目的 ping 数据库:

package receiver

import (
    "database/sql"
    "fmt"
    "net/http"
    "os"

    // Import Postgres SQL driver
    _ "github.com/lib/pq"
)

// Receives a message and stores it
func Receive(w http.ResponseWriter, r *http.Request) {
    connectionName := os.Getenv("POSTGRES_INSTANCE_CONNECTION_NAME")
    dbUser         := os.Getenv("POSTGRES_USER")
    dbPassword     := os.Getenv("POSTGRES_PASSWORD")
    dsn            := fmt.Sprintf("user=%s password='%s' host=/cloudsql/%s dbname=messages", dbUser, dbPassword, connectionName)

    var err error
    db, err := sql.Open("postgres", dsn)
    if err != nil {
        fmt.Fprintf(w, "Could not open db: %v \n", err)
    }

    // Only allow 1 connection to the database to avoid overloading
    db.SetMaxIdleConns(1)
    db.SetMaxOpenConns(1)
    defer db.Close()

    if pingerror := db.Ping(); pingerror != nil {
        fmt.Fprintf(w, "Failed to ping database: %s \n", pingerror)
        return
    }
}

变量POSTGRES_INSTANCE_CONNECTION_NAME 被格式化为here 描述为ProjectID:Region:InstanceID

预期是成功消息或没有错误,我实际上收到此消息:

pq: password authentication failed for user "postgres" 

注意:我还使用我的 sql 数据库设置创建了一个包含来自here 的演示代码的函数,并且错误是相同的。似乎我在设置用户或 sql 实例时错过了一些步骤。但我不知道是哪个。

【问题讨论】:

    标签: postgresql go google-cloud-functions google-cloud-sql


    【解决方案1】:

    回答我自己的问题感觉很奇怪,但它是:由于某种原因,与postgres 用户的连接不起作用。最后我为函数创建了一个新的数据库用户和一个只包含字母数字字符的密码。

    【讨论】:

    • 嘿,很好地找到了您问题的解决方案。请尽快将其标记为解决方案,以提高问题的可见性。
    【解决方案2】:

    /cloudsql/{connectionName} 的 unix 套接字仅在 GCF 运行时中提供。在本地运行时,您要么需要更改连接字符串,要么使用 Cloud SQL proxy 在同一路径模拟 unix 套接字。

    【讨论】:

    • 我已经用模拟器和代理进行了测试,但没有成功,我已经在 gcloud 控制台中创建了函数,但仍然收到相同的错误。
    猜你喜欢
    • 2020-01-23
    • 2019-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-18
    • 2019-09-05
    • 1970-01-01
    • 2022-01-24
    相关资源
    最近更新 更多