我正在尝试创建与数据库的基本连接。当我尝试使用db.Ping()
测试连接时,会出现问题;一切顺利,直到我到达这条线。 Ping
将程序发送到一个无限循环(函数调用永远不会返回),我不知道如何解决这个问题。
package main
import (
"database/sql"
"fmt"
"html/template"
"net/http"
_ "github.com/lib/pq"
}
type Page struct {
Name string
DBStatus bool
}
const (
host = "localhost"
port = 8080
user = "username"
password = "password"
dbname = "GoTest"
)
func main() {
templates := template.Must(template.ParseFiles("templates/index.html"))
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()
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
p := Page{Name: "Gopher"}
if name := r.FormValue("name"); name != "" {
p.Name = name
}
p.DBStatus = db.Ping() == nil //this point is reached but never returned
if err := templates.ExecuteTemplate(w, "index.html", p); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
})
fmt.Println(http.ListenAndServe(":8080", nil))
}
似乎我可以正常连接到数据库,因为sql.Open
调用不会返回错误,如果我在http服务器句柄函数之外调用Ping
,它也会返回细
非常感谢任何帮助!
答案 0 :(得分:1)
您的数据库配置错误。它指向Golang服务器端口8080
。它应该指向pgsql端口(默认为5432)