使用SQLX连接PostgreSQL时,设置sslmode=disable仍遇pq: SSL未启用报错
解决PostgreSQL连接时
pq: SSL is not enabled on the server错误 问题场景
已设置环境变量:
SET DSN="postgres://postgres:password@127.0.0.1/food_db_development?sslmode=disable" SET GIN_PORT=":7070"
运行使用sqlx和envconfig的Go项目时,日志显示配置已正确加载,但数据库连接失败,报错pq: SSL is not enabled on the server。项目代码如下:
import ( "fmt" "log" "github.com/jmoiron/sqlx" "github.com/kelseyhightower/envconfig" _ "github.com/lib/pq" ) type Config struct { Dsn string `required:"true"` GinPort string `required:"true" split_words:"true"` } func LoadConfig() (*Config, error) { var c Config err := envconfig.Process("", &c) if err != nil { return nil, fmt.Errorf("failed to load config: %w", err) } return &c, nil } func NewPostgresDB(conf *Config) (*sqlx.DB, error) { db, err := sqlx.Connect("postgres", conf.Dsn) if err != nil { return nil, err } return db, nil } func main() { conf, err := LoadConfig() if err != nil { log.Fatalln(err) } log.Println("configurations: ", conf) db, err := NewPostgresDB(conf) if err != nil { log.Fatalln(err) } log.Println("connected to db with: ", db) }
解决方案
移除环境变量值的引号
你设置环境变量时用双引号包裹了DSN,导致程序接收到的DSN包含多余的引号(从日志&{"postgres://..."可以看出),这会让pq驱动无法正确解析sslmode=disable参数。正确的设置方式:SET DSN=postgres://postgres:password@127.0.0.1/food_db_development?sslmode=disable SET GIN_PORT=:7070直接验证DSN有效性
可以临时在代码中硬编码DSN测试连接,确认参数本身没问题:db, err := sqlx.Connect("postgres", "postgres://postgres:password@127.0.0.1/food_db_development?sslmode=disable")如果这样能成功连接,说明问题完全出在环境变量的引号上。
确认PostgreSQL服务器SSL配置
检查PostgreSQL配置文件postgresql.conf,确保ssl参数设置为off(若不需要SSL)。如果服务器确实未开启SSL,只要客户端的sslmode=disable参数正确传递,就能正常连接。
内容的提问来源于stack exchange,提问作者Leo Santos
相关产品推荐
相关产品推荐

