Im new to the Golang language and im coming from Nodejs, where it was quite simple to access database and manipulate db within a http request handler.Now i want to do the same in Golang and i cant access the db variable from the handlers.
Lets say i want to get users on a get request from a postgres db.
func getHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "get req made")
rows, error := db.Query("SELECT id, name, age FROM new_table LIMIT $1", 4)
if error != nil {
panic(error)
}
defer rows.Close()
for rows.Next() {
var id int
var name string
var age int
error = rows.Scan(&id, &name, &age)
if error != nil {
panic(error)
}
fmt.Println(id, name, age)
}
error = rows.Err()
if error != nil {
panic(error)
}
}```
And i get error: undeclared name: db, if i use this code inside the main function where the db connection is located, its working fine.
How can i use the db variable outside the scope where its declared?
2
Answers
Probably your
db
variable is created in your main func when you try to connect to the database. The problem is, thatdb
variable will have a scope within your main func only. So to work, you need to declare it globally at package level.So in your main.go declare a variable outside of your main func, then use it everywhere.
But if you use global variables, you must check whenever it supports multi threaded access. Your db connection will work fine, but you have to read some tutorial about variable scopes and mutexes in go.
If db is from another package make sure it has public access. You will need to start with a capital letter e.g. Db
This would be a basic database function in a separate file using gorm.io