I am trying to use Golang as a REST API. I have managed to get handlers to work and queries as well. But not got a query inside a handler to work.
When the query resides within the main() it works:
func handleRequests() {
http.HandleFunc("/getuser", Getuser)
}
---> this handler gets respons on localhost:8080/getuser
func Getuser(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Getuser")
}
func main() {
handleRequests()
//Connect to db
rows, err := db.Queryx(`SELECT "USER_ID","USER_NAME" FROM user`)
for rows.Next() {
results := make(map[string]interface{})
err = rows.MapScan(results)
fmt.Printf("%#v
", results)
}
log.Fatal(http.ListenAndServe(":8080", nil))
}
But when I move the query to the handler it gives an error that the db is not defined.
func handleRequests() {
http.HandleFunc("/getuser", Getuser)
}
---> this gives the error that the db is not defined
func Getuser(w http.ResponseWriter, r *http.Request) {
rows, err := db.Queryx(`SELECT "USER_ID","USER_NAME" FROM user`)
for rows.Next() {
results := make(map[string]interface{})
err = rows.MapScan(results)
fmt.Printf("%#v
", results)
}
}
func main() {
handleRequests()
//Connect to db
log.Fatal(http.ListenAndServe(":8080", nil))
}
EDIT
Full code inside the handler (added db var as suggested), but gives various errors on "err".
var db *sqlx.DB <---solved the db problem
func Getsign(w http.ResponseWriter, r *http.Request) {
rows, err := db.Queryx(`SELECT "USER_ID","USER_NAME" FROM user`)
for rows.Next() {
results := make(map[string]interface{})
err = rows.MapScan(results)
fmt.Printf("%#v
", results)
}
defer rows.Close()
if err := rows.Err(); err != nil {
log.Fatal(err)
}
}
Any tip what I am doing wrong?