简体   繁体   English

如何在 Golang 的 http 处理程序中访问数据库连接?

[英]How to access database connection in http handler in Golang?

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.我是 Golang 语言的新手,我来自 Nodejs,在 Nodejs 中访问数据库和在 http 请求处理程序中操作 db 非常简单。现在我想在 Golang 中做同样的事情,我无法从处理程序访问 db 变量。 Lets say i want to get users on a get request from a postgres db.可以说我想让用户收到来自 postgres 数据库的获取请求。

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?

Probably your db variable is created in your main func when you try to connect to the database.当您尝试连接到数据库时,您的db变量可能是在您的主要功能中创建的。 The problem is, that db variable will have a scope within your main func only.问题是,那个db变量只会在你的 main func 中有一个范围。 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.所以在你的 main.go 中声明一个变量在你的 main func 之外,然后在任何地方使用它。

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.您的数据库连接可以正常工作,但您必须阅读一些有关 go 中的变量范围和互斥量的教程。

If db is from another package make sure it has public access.如果 db 来自另一个包,请确保它具有公共访问权限。 You will need to start with a capital letter eg Db您需要以大写字母开头,例如 Db

This would be a basic database function in a separate file using gorm.io这将是一个使用 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. ")
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM