-2

Why the db variable is nil in the getBooks function?

package main

import (
    ...
)

var db *sql.DB

func init() {
    gotenv.Load()
}

func main() {

    db, err := sql.Open("postgres", os.Getenv("ELEPHANTSQL_URL"))
    err = db.Ping()
    fmt.Println(db, err)

    router := mux.NewRouter()
    router.HandleFunc("/books", getBooks).Methods("GET")
    log.Fatal(http.ListenAndServe("localhost:8000", router))
}

func getBooks(w http.ResponseWriter, r *http.Request) {
    if db == nil {
        log.Print("!!!!!!!!!!")
        os.Exit(2)
    }
}
user8049659
  • 129
  • 1
  • 1
  • 8

1 Answers1

2

With := you're declaring a new db variable inside the main() scope instead of assigning to the db variable at the package scope.

You must either use just = or use another name than db.

Try this:

var err error
db, err = sql.Open("postgres", os.Getenv("ELEPHANTSQL_URL"))
Zippo
  • 15,850
  • 10
  • 60
  • 58