gpt4 book ai didi

postgresql - 数据库连接在Golang中出错了吗?

转载 作者:行者123 更新时间:2023-12-01 22:34:49 25 4
gpt4 key购买 nike

因此,我正在使用herokuapp为我托管golang应用程序,我试图制作一个注册表单以使人们可以注册并成为用户,但是我的代码遇到错误:
我有2个主要文件,main.go和store.go,它们处理服务器内容,然后有一个/ assets文件夹,其中包含我的静态html(包括注册页面)。

main.go中的方法:

type User struct {
username string `json:"username"`
gender bool `json:"gender"`
age int `json:"age"`
password string `json:"password"`
email string `json:"email"`
}

func newRouter() *mux.Router {
r := mux.NewRouter()
r.HandleFunc("/user", getUserHandler).Methods("GET")
r.HandleFunc("/user", createUserHandler).Methods("POST")
r.HandleFunc("/forms/login", loginUserHandler).Methods("POST")
r.HandleFunc("/forms/signup", createUserHandler).Methods("POST")
//ALL PAGE FUNCTIONS HERE
r.HandleFunc("/", handler).Methods("GET")

//Declare static file directory
staticFileDirectory := http.Dir("./assets/")

staticFileHandler := http.StripPrefix("/assets/", http.FileServer(staticFileDirectory))

r.PathPrefix("/assets/").Handler(staticFileHandler).Methods("GET")
return r
}
func main() {
router := newRouter()
portEnv := os.Getenv("PORT")
port := ":" + portEnv
http.ListenAndServe(port, router)

url := os.Getenv("DATABASE_URL")
db, err := sql.Open("postgres", url)

if err != nil {
log.Fatalf("Connection error: %s", err.Error())
panic(err)
}
defer db.Close()

err = db.Ping()

if err != nil {
log.Fatalf("Ping error: %s", err.Error())
panic(err)
}

InitStore(&dbStore{db: db})
}
func createUserHandler(w http.ResponseWriter, r *http.Request) {
user := User{}

//Send all data as HTML form Data so parse form
err := r.ParseForm()
if err != nil {
fmt.Println(fmt.Errorf("Error: %v", err))
w.WriteHeader(http.StatusInternalServerError)
return
}

//Get the information about the user from user info
user.username = r.Form.Get("username")
// user.gender, _ = strconv.ParseBool(r.Form.Get("gender"))
user.age = 16
user.password = r.Form.Get("password")
cpassword := r.Form.Get("cpassword")
user.email = r.Form.Get("email")

if(user.password != cpassword) {
http.Redirect(w, r, "/assets/signup.html", http.StatusSeeOther)
return
}
user.password = hashAndSalt([]byte(user.password))
//Append existing list of users with a new entry
err = store.CreateUser(&user)
if err != nil {
log.Println(err)
fmt.Println(err)
}
//Set Cookie with username
addCookie(w, "username", user.username)

http.Redirect(w, r, "/assets/", http.StatusFound)
}

这些是用于Web服务器这一部分的主要功能,并且应该是给我此错误响应的唯一功能

store.go:
type Store interface {
CreateUser(user *User) error
GetUsers()([]*User, error)
}
func (store *dbStore) CreateUser(user *User) error {
_, err := store.db.Query("INSERT INTO users(username,age,password,email) VALUES ($1,$2,$3,$4);",user.username,user.age,user.password,user.email)
return err
}
var store dbStore

func InitStore(s dbStore) {
store = s
}

我的错误代码:
2020-02-07T04:58:18.077322+00:00 app[web.1]: 2020/02/07 04:58:18 http: panic serving (MYIP):18930: runtime error: invalid memory address or nil pointer dereference
2020-02-07T04:58:18.077334+00:00 app[web.1]: goroutine 13 [running]:
2020-02-07T04:58:18.077337+00:00 app[web.1]: net/http.(*conn).serve.func1(0xc00008f400)
2020-02-07T04:58:18.077339+00:00 app[web.1]: /app/tmp/cache/go1.12.12/go/src/net/http/server.go:1769 +0x139
2020-02-07T04:58:18.077341+00:00 app[web.1]: panic(0x725720, 0xa29b80)
2020-02-07T04:58:18.077343+00:00 app[web.1]: /app/tmp/cache/go1.12.12/go/src/runtime/panic.go:522 +0x1b5
2020-02-07T04:58:18.077346+00:00 app[web.1]: database/sql.(*DB).conn(0x0, 0x7fdf40, 0xc000016048, 0xa2a301, 0x0, 0x0, 0xc000055920)
2020-02-07T04:58:18.077348+00:00 app[web.1]: /app/tmp/cache/go1.12.12/go/src/database/sql/sql.go:1080 +0x3a
2020-02-07T04:58:18.077350+00:00 app[web.1]: database/sql.(*DB).query(0x0, 0x7fdf40, 0xc000016048, 0x798f41, 0x44, 0xc000055a30, 0x4, 0x4, 0x1, 0xc00010acc0, ...)
2020-02-07T04:58:18.077352+00:00 app[web.1]: /app/tmp/cache/go1.12.12/go/src/database/sql/sql.go:1513 +0x66
2020-02-07T04:58:18.077355+00:00 app[web.1]: database/sql.(*DB).QueryContext(0x0, 0x7fdf40, 0xc000016048, 0x798f41, 0x44, 0xc000055a30, 0x4, 0x4, 0x6d5085, 0x0, ...)
2020-02-07T04:58:18.077357+00:00 app[web.1]: /app/tmp/cache/go1.12.12/go/src/database/sql/sql.go:1495 +0xd1
2020-02-07T04:58:18.077359+00:00 app[web.1]: database/sql.(*DB).Query(...)
2020-02-07T04:58:18.077362+00:00 app[web.1]: /app/tmp/cache/go1.12.12/go/src/database/sql/sql.go:1509
2020-02-07T04:58:18.077364+00:00 app[web.1]: main.(*dbStore).CreateUser(0xa34758, 0xc000055b50, 0x20, 0xc00010acc0)
2020-02-07T04:58:18.077366+00:00 app[web.1]: /tmp/tmp.N9S5bJfo59/.go/src/github.com/InsanityMatrix/SocialFoot/store.go:19 +0x1a3
2020-02-07T04:58:18.077369+00:00 app[web.1]: main.createUserHandler(0x7fd680, 0xc0000f4460, 0xc00012ce00)
2020-02-07T04:58:18.077371+00:00 app[web.1]: /tmp/tmp.N9S5bJfo59/.go/src/github.com/InsanityMatrix/SocialFoot/main.go:114 +0x367
2020-02-07T04:58:18.077373+00:00 app[web.1]: net/http.HandlerFunc.ServeHTTP(0x79e1a0, 0x7fd680, 0xc0000f4460, 0xc00012ce00)
2020-02-07T04:58:18.077375+00:00 app[web.1]: /app/tmp/cache/go1.12.12/go/src/net/http/server.go:1995 +0x44
2020-02-07T04:58:18.077378+00:00 app[web.1]: github.com/InsanityMatrix/SocialFoot/vendor/github.com/gorilla/mux.(*Router).ServeHTTP(0xc0000f0000, 0x7fd680, 0xc0000f4460, 0xc00012cc00)
2020-02-07T04:58:18.077380+00:00 app[web.1]: /tmp/tmp.N9S5bJfo59/.go/src/github.com/InsanityMatrix/SocialFoot/vendor/github.com/gorilla/mux/mux.go:210 +0xe3
2020-02-07T04:58:18.077382+00:00 app[web.1]: net/http.serverHandler.ServeHTTP(0xc000084a90, 0x7fd680, 0xc0000f4460, 0xc00012cc00)
2020-02-07T04:58:18.077384+00:00 app[web.1]: /app/tmp/cache/go1.12.12/go/src/net/http/server.go:2774 +0xa8
2020-02-07T04:58:18.077386+00:00 app[web.1]: net/http.(*conn).serve(0xc00008f400, 0x7fdf00, 0xc000020a40)
2020-02-07T04:58:18.077388+00:00 app[web.1]: /app/tmp/cache/go1.12.12/go/src/net/http/server.go:1878 +0x851
2020-02-07T04:58:18.077391+00:00 app[web.1]: created by net/http.(*Server).Serve
2020-02-07T04:58:18.077393+00:00 app[web.1]: /app/tmp/cache/go1.12.12/go/src/net/http/server.go:2884 +0x2f4

最佳答案

除非有错误,否则函数http.ListenAndServe()不会返回。它侦听HTTP连接并为其提供服务。因此,main中的数据库初始化代码永远不会运行,并且HTTP连接正在使用nil数据库连接。

http.ListenAndServe移动到main()的底部进行修复。

关于postgresql - 数据库连接在Golang中出错了吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60107358/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com