大家好,我在连接我的Golang应用程序到Cloud SQL Postgres实例时遇到了困难。我刚刚按照谷歌云平台的教程和示例代码进行操作,但似乎并没有起作用。我只有两个文件app.yaml和main.go来测试连接。
我尝试使用"go run ." 和 "goapp serve",还尝试添加了appengine导入包,但是似乎都没有起作用,并且一直给我报错:
app.yaml
runtime: go api_version: go1 env: standard
env_variables: CLOUDSQL_CONNECTION_NAME: bxustl2019proj:asia-east1:sqlstlbxu CLOUDSQL_USER: ustldbbxu CLOUDSQL_PASSWORD: bxuuserstldb CLOUDSQL_DB: stlbxudbs
beta_settings:
cloud_sql_instances: bxustl2019proj:asia-east1:sqlstlbxu
handlers:
- url: /(.*\.(gif|png|jpg))$ static_files: static/\1 upload: static/.*\.(gif|png|jpg)
- url: /.* script: _go_app
main.go
package dptest
import (
_"bytes"
"database/sql"
"fmt"
"log"
"net/http"
"os"
_ "github.com/lib/pq"
)
var db *sql.DB
func init() {
db = DB()
http.HandleFunc("/", indexHandler)
}
// DB gets a connection to the database.
// This can panic for malformed database connection strings, invalid credentials, or non-existance database instance.
func DB() *sql.DB {
/*
var (
connectionName = mustGetenv("CLOUDSQL_CONNECTION_NAME")
user = mustGetenv("CLOUDSQL_USER")
dbname = mustGetenv("CLOUDSQL_DB")
password = os.Getenv("CLOUDSQL_PASSWORD") // NOTE: password may be empty
socket = os.Getenv("CLOUDSQL_SOCKET_PREFIX")
)
//cloudsql is used on App Engine.
if socket == "" {
socket = "/cloudsql"
}
*/
// PostgreSQL Connection, uncomment to use.
// connection string format: user=USER password=PASSWORD host=/cloudsql/PROJECT_ID:REGION_ID:INSTANCE_ID/[ dbname=DB_NAME]
//dbURI := fmt.Sprintf("user=%s password=%s host=/cloudsql/%s database=%s", user, password, connectionName, dbname)
dbURI := fmt.Sprintf("user=ustldbbxu password=bxuuserstldb host=/cloudsql/bxustl2019proj:asia-east1:sqlstlbxu/stlbxudbs")
conn, err := sql.Open("postgres", dbURI)
log.Printf("CONNECTION: %v", conn)
if err != nil {
panic(fmt.Sprintf("DB: %v", err))
}
rows, err := conn.Query("SELECT * FROM GAMES")
log.Printf("ROW: %v", rows)
if err != nil {
log.Printf("Could not query db: %v", err)
}
defer rows.Close()
return conn
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "text/plain")
log.Printf("CONNECTION: %v", db)
rows, err := db.Query("SELECT * FROM GAMES")
log.Printf("ROW: %v", rows)
if err != nil {
log.Printf("Could not query db: %v", err)
http.Error(w, "Internal Error", 500)
return
}
defer rows.Close()
}
func mustGetenv(k string) string {
v := os.Getenv(k)
if v == "" {
log.Panicf("%s environment variable not set.", k)
}
return v
}
我尝试使用"go run ." 和 "goapp serve",还尝试添加了appengine导入包,但是似乎都没有起作用,并且一直给我报错:
无法查询数据库:dial unix /cloudsql/bxustl2019proj:asia-east1:sqlstlbxu/stlbxudbs/.s.PGSQL.5432:连接:没有这个文件或目录
Cloud SQL管理已启用。我只是注释掉了环境变量以便更轻松地运行,但不管是硬编码查询路径还是从yaml中导入,错误看起来都是相同的。
希望有人能够帮助我。谢谢。