我正在尝试连接到数据库,但是当我使用该方法向端点发出 curl 请求时出现错误GET。我仔细检查了用户凭据并授予了完全权限和超级用户权限。以下是卷曲端点时出现的错误:
santosh@pkg*$:curl -i localhost:8080/books/show
HTTP/1.1 303 See Other
Content-Type: text/html; charset=utf-8
Location: /books
Date: Sat, 19 Nov 2022 12:09:52 GMT
Content-Length: 33
<a href="/books">See Other</a>.
与数据库建立连接,当向数据库发出请求时会触发这些错误:
santosh@pkg*$:go run main.go
Database connection successful.
2022/11/19 17:39:47 http: panic serving 127.0.0.1:44324: runtime error: invalid memory address or nil pointer dereference
goroutine 35 [running]:
net/http.(*conn).serve.func1()
/usr/local/go/src/net/http/server.go:1850 +0xbf
panic({0x6960e0, 0x8e5630})
/usr/local/go/src/runtime/panic.go:890 +0x262
database/sql.(*DB).conn(0x0, {0x7593d0, 0xc00011a000}, 0x1)
/usr/local/go/src/database/sql/sql.go:1288 +0x53
database/sql.(*DB).query(0x6?, {0x7593d0, 0xc00011a000}, {0x6da967, 0x13}, {0x0, 0x0, 0x0}, 0x68?)
主要程序:
var db *sql.DB
type Books struct {
Isbn string
Title string
Author string
Price float32
}
func init() {
var err error
args := fmt.Sprintf("host=%s port=%d dbname=%s user='%s' password=%s sslmode=%s", "localhost", 5432, "bookstore", "santosh", "dts123", "disable")
db, err := sql.Open("postgres", args)
if err != nil {
fmt.Printf("Creating Database %s", err)
}
if err = db.Ping(); err != nil {
panic(err)
}
fmt.Println("Database connection succussful.")
}
func main() {
http.HandleFunc("/", index)
http.HandleFunc("/books", booksIndex)
http.ListenAndServe(":8080", nil)
}
func index(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/books", http.StatusSeeOther)
}
我尝试仔细检查用户权限和数据库格式以及顺序。一切都符合代码。连接已建立,但在查询数据库时因紧急情况而失败。
绝地无双
相关分类