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

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效