Golang如何连接远程服务器
Golang如何连接远程服务器 我已将我的Go语言文件上传到服务器(例如125.168.147.11),同时也在服务器上部署了Postgres数据库。但现在我不知道如何从我的Go程序连接到Postgres数据库,我尝试了如下操作:
const (
host = "http://125.168.147.11"
port = 5432
user = "postgres"
password = "postgres"
dbname = "postgres"
)
func main() {
psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+
"password=%s dbname=%s sslmode=disable",
host, port, user, password, dbname)
db, err := sql.Open("postgres", psqlInfo)
if err != nil {
panic(err)
}
defer db.Close()
err = db.Ping()
if err != nil {
panic(err)
}
fmt.Println("Successfully connected!")
}
但我遇到了错误:
panic: dial tcp 78.140.223.85:5432: connect: connection refused
更多关于Golang如何连接远程服务器的实战教程也可以访问 https://www.itying.com/category-94-b0.html
2 回复
“localhost"是一个主机名,会解析到"127.0.0.1”,这是分配给"环回"接口的IP地址,始终指向本地主机。
如果PostgreSQL服务器与Go程序在同一台机器上,你应该连接到"localhost"而不使用"http://"。PostgreSQL不使用HTTP协议。
你还应该查看这个链接来了解IP地址和域名系统(DNS)的工作原理,因为你的问题实际上与Go无关。
更多关于Golang如何连接远程服务器的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
您遇到的连接错误表明Go程序无法与远程PostgreSQL服务器建立TCP连接。问题主要出在连接字符串的格式和网络配置上。
以下是修正后的代码:
package main
import (
"database/sql"
"fmt"
"log"
_ "github.com/lib/pq"
)
const (
host = "125.168.147.11" // 移除http://前缀
port = 5432
user = "postgres"
password = "postgres"
dbname = "postgres"
)
func main() {
psqlInfo := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
host, port, user, password, dbname)
db, err := sql.Open("postgres", psqlInfo)
if err != nil {
log.Fatal(err)
}
defer db.Close()
// 设置连接池参数
db.SetMaxOpenConns(25)
db.SetMaxIdleConns(25)
db.SetConnMaxLifetime(5 * time.Minute)
err = db.Ping()
if err != nil {
log.Fatal("连接失败:", err)
}
fmt.Println("成功连接到数据库!")
}
主要修正点:
- 移除HTTP协议前缀:PostgreSQL使用纯TCP连接,不需要
http:// - 确保导入正确的驱动:
_ "github.com/lib/pq" - 改进错误处理:使用
log.Fatal替代panic
还需要检查服务器端的配置:
# 检查PostgreSQL监听配置
sudo grep -E "listen_addresses|port" /etc/postgresql/*/main/postgresql.conf
# 检查pg_hba.conf配置
sudo cat /etc/postgresql/*/main/pg_hba.conf
服务器端需要确保:
- postgresql.conf中设置:
listen_addresses = '*'或listen_addresses = '125.168.147.11' - pg_hba.conf中添加:
host all all 0.0.0.0/0 md5 - 防火墙开放5432端口:
sudo ufw allow 5432/tcp
重启PostgreSQL服务后重试连接:
sudo systemctl restart postgresql

