package main
import (
"encoding/json"
"gorilla/mux"
"log"
"net/http"
"database/sql"
_ "go-sql-driver/mysql"
)
func GetPeople(w http.ResponseWriter, r *http.Request, db *sql.DB) {
json.NewEncoder(w).Encode(db.QueryRow("SELECT * from test.animal"))
}
func main() {
db, err := sql.Open("mysql", "root:mariadb@tcp(127.0.0.1:3306)/test")
if err != nil {
panic(err.Error())
}
defer db.Close()
router := mux.NewRouter()
router.HandleFunc("/people", GetPeople).Methods("GET")
log.Fatal(http.ListenAndServe(":8000", router))
}
我需要在GetPeople函数中识别我的db,但是给函数第三个参数(db * sql.DB)是不可能的。
我该如何解决?谢谢
答案 0 :(得分:3)
另一种方法是使用闭包,这可以防止全局使用变量:
func GetPeopleHandler(db *sql.DB) func (w http.ResponseWriter, r *http.Request) {
return func (w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(db.QueryRow("SELECT * from test.animal"))
}
}
func main() {
var err error
db, err = sql.Open("mysql", "root:mariadb@tcp(127.0.0.1:3306)/test")
if err != nil {
panic(err.Error())
}
defer db.Close()
router := mux.NewRouter()
router.HandleFunc("/people", GetPeopleHandler(db)).Methods("GET")
log.Fatal(http.ListenAndServe(":8000", router))
}
答案 1 :(得分:1)
只需将db
变量设为全局变量,而不是main()
中的本地变量:
var db *sql.DB
func GetPeople(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(db.QueryRow("SELECT * from test.animal"))
}
func main() {
var err error
db, err = sql.Open("mysql", "root:mariadb@tcp(127.0.0.1:3306)/test")
if err != nil {
panic(err.Error())
}
defer db.Close()
router := mux.NewRouter()
router.HandleFunc("/people", GetPeople).Methods("GET")
log.Fatal(http.ListenAndServe(":8000", router))
}
参见相关问题:
How to use global var across files in a package?
Performance difference between global database connection and opening connection everytime on Golang