Postgresql Golang中的数据库连接出错?

Postgresql Golang中的数据库连接出错?,postgresql,http,go,heroku,web-applications,Postgresql,Http,Go,Heroku,Web Applications,因此,我正在使用herokuapp为我主持一个golang应用程序,我正在尝试制作一个注册表单,以便人们可以注册并成为用户,但我的代码中遇到了一个错误: 我有两个主文件,main.go和store.go,它们处理服务器上的东西,然后是一个/assets文件夹,其中包含我的静态html,包括注册页面 main.go中的方法: type User struct { username string `json:"username"` gender bool `json:"gender"

因此,我正在使用herokuapp为我主持一个golang应用程序,我正在尝试制作一个注册表单,以便人们可以注册并成为用户,但我的代码中遇到了一个错误: 我有两个主文件,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.listendServe
移动到
main()
的底部进行修复。

谢谢,我认为因为go是一种多线程语言,所以它可以在单独的线程上完成与网络相关的工作。我现在明白了,情况并非如此,谢谢!它在单独的goroutine中也会这样做。将为
ListenAndServe
中的每个连接创建一个新的goroutine。如果需要它在单独的线程中运行listenAndServe,请将其启动为
go func(){http.listenAndServe(…)}()