douzhuang6321 2015-12-02 15:13
浏览 411
已采纳

如何使用Gin Web框架将参数传递给Golang中的路由器处理程序?

I'm using Gin, https://gin-gonic.github.io/gin/, to build a simple RESTful JSON API with Golang.

The routes are setup with something like this:

func testRouteHandler(c *gin.Context) {
    // do smth
}

func main() {
    router := gin.Default()
    router.GET("/test", testRouteHandler)
    router.Run(":8080")
}

My question is how can I pass down an argument to the testRouteHandler function? For example a common database connection could be something that one wants to reuse among routes.

Is the best way to have this in a global variable? Or is there some way in Go to pass along an extra variable to the testRouteHandler function? Are there optional arguments for functions in Go?

PS. I'm just getting started in learning Go, so could be something obvious that I'm missing :)

  • 写回答

4条回答 默认 最新

  • douchao9899 2015-12-02 21:11
    关注

    Using the link i posted on comments, I have created a simple example.

    package main
    
    import (
        "log"
    
        "github.com/gin-gonic/gin"
        "github.com/jinzhu/gorm"
        _ "github.com/mattn/go-sqlite3"
    )
    
    // ApiMiddleware will add the db connection to the context
    func ApiMiddleware(db gorm.DB) gin.HandlerFunc {
        return func(c *gin.Context) {
            c.Set("databaseConn", db)
            c.Next()
        }
    }
    
    func main() {
        r := gin.New()
    
        // In this example, I'll open the db connection here...
        // In your code you would probably do it somewhere else
        db, err := gorm.Open("sqlite3", "./example.db")
        if err != nil {
            log.Fatal(err)
        }
    
        r.Use(ApiMiddleware(db))
    
        r.GET("/api", func(c *gin.Context) {
            // Don't forget type assertion when getting the connection from context.
            dbConn, ok := c.MustGet("databaseConn").(gorm.DB)
            if !ok {
                // handle error here...
            }
    
            // do your thing here...
        })
    
        r.Run(":8080")
    }
    

    This is just a simple POC. But i believe it's a start. Hope it helps.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?