Home > Blockchain >  How to access database connection in http handler in Golang?
How to access database connection in http handler in Golang?

Time:12-21

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?

CodePudding user response:

Probably your db variable is created in your main func when you try to connect to the database. The problem is, that db 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.

package main

var db *DB

func main() {
  var err error
  db, err = sql.Connect(...)
  if err != nil {
      log.Fatal(err)
  }
  defer db.Close()

  //Start HTTP server
}

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.

CodePudding user response:

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

package boot

import (
    "fmt"
    "log"
    "os"

    "gorm.io/driver/postgres"
    "gorm.io/gorm"
)

var DB *gorm.DB

func ConnectDB() {
    var err error
    dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%s sslmode=disable",
        os.Getenv("PG_HOST"),
        os.Getenv("PG_USER"),
        os.Getenv("PG_PASSWORD"),
        os.Getenv("PG_DBNAME"),
        os.Getenv("PG_PORT"),
    )
    DB, err = gorm.Open(postgres.Open(dsn), &gorm.Config{})
    if err != nil {
        log.Println(err)
        panic("Failled to connect to Database. ")
    }

}
  • Related