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条)

报告相同问题?

悬赏问题

  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误