所以我有两个文件。在其中一个中,我初始化了一个 gorilla 路由器,并注册了处理程序。在另一个我定义处理程序。处理程序应该查询MYSQL数据库。 Routes.go看起来像这样-

    package main

import (
    "net/http"
    "github.com/gorilla/mux"
    "database/sql"
    _ "github.com/go-sql-driver/mysql"
    "fmt"
)

type Route struct {
    Name string
    Method string
    Pattern string
    HandlerFunc http.HandlerFunc
}

type Routes[]Route

func NewRouter() *mux.Router {
    db, err := sql.Open("mysql", "psanker:123@/education_data")
    err = db.Ping()

    if err != nil {
        fmt.Println("Failed to prepare connection to database")
        log.Fatal("Error:", err.Error())
    }

    defer db.Close()

    router := mux.NewRouter().StrictSlash(true)
    for _, route := range routes {
        router.
            Methods(route.Method).
            Path(route.Pattern).
            Name(route.Name).
            Handler(route.HandlerFunc)
    }
    return router
}

var routes = Routes{
    Route {
        "Index",
        "GET",
        "/",
        Index,
    },
    Route {
        "getDistrict",
        "GET",
        "/district/{districtId}",
        getDistrict,
        DBConn &db,
    },
    Route {
        "getDistricts",
        "GET",
        "/districts",
        getDistricts,
    },
}

我的handlers.go文件如下所示:
package main

import (
    "fmt"
    "net/http"
    "github.com/gorilla/mux"
    "encoding/json"
)

func Index(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "WELCOME!")
}

func getDistrict(w http.ResponseWriter, r *http.Request) {
    vars := mux.Vars(r)
    districtId := vars["districtId"]
    fmt.Fprintln(w, "District id : ", districtId)
}

func getDistricts(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json;charset=UTF-8")
    w.WriteHeader(http.StatusOK)
    rows, err := db.Query("SELECT * from districts")
    check(err)
    var district District
    for rows.Next() {
        var id int64
        test := "hey"
        district = District{Id: id, Activities: test}
    }

    if err := json.NewEncoder(w).Encode(district); err != nil {
        check(err)
    }
}

我想对所有处理程序使用一个数据库连接,如何实现呢?

最佳答案

Go的sql.DB类型表示一个连接池,而不是单个连接。建议您在程序初始化时创建一个池,并且可以:

  • 创建一个全局池并使用它(该池对于并发访问是安全的)
    var db *sql.DB
    
    func main() {
    var err error
    db, err = sql.Open("connection string here")
    if err != nil {
        // handle it
    }
    
    // Rest of program/router/etc
    }
    
    func MyHandler(w http.ResponseWriter, r *http.Request) {
    err := db.Query("...")
    if err != nil {
         // handle it
        }
    
        // Rest of handler
    }
    
  • 创建满足http.Handler的自定义处理函数,并接受池或包含池的结构作为附加参数。我在这里写过:https://elithrar.github.io/article/custom-handlers-avoiding-globals/

  • (我将提供另一个示例,但我使用的是移动设备;不好意思的情况下,请原谅)

    还要查看sqlx,以简化查询与结构处理之间的关系。

    关于mysql - Golang将参数传递给 gorilla 路由器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30768684/

    10-16 09:27