我正在使用Gin,https://gin-gonic.github.io/gin/,用Golang构建一个简单的RESTful JSON API.

路由设置如下:

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

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

我的问题是如何将参数传递给testRouteHandler函数?例如,公共数据库连接可能是您希望在路由之间重用的东西.

将其放入全局变量中的最佳方法是什么?或者Go中是否有某种方法将额外的变量传递给testRouteHandler函数?Go中的函数是否有可选参数?

另外,我刚刚开始学习围棋,所以可能是我错过了一些明显的东西:)

推荐答案

使用我在 comments 上发布的链接,我创建了一个简单的示例.

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")
}

这只是一个简单的POC.但我相信这是一个开始.

Go相关问答推荐

CGO如何转换为文件*类型

GitHub发布Golang子模块

验证访问令牌(密钥罩)

一次打印用户输入的字符串n次

是否需要手动调用rand.Seed?

仅使用公共 api 对 alexedwards/scs 进行简单测试

在 Cloud Run 中找不到默认凭据

如何使用 go 包设置标头键和值:shurcooL/graphql 或 hasura/go-graphql-client?

上传图片失败,出现错误dial tcp: lookup api.cloudinary.com: no such host

使用 ssh 从私有 gilab 仓库导入一个 go 项目:未知修订

在 Go 中公开公共 JWK

使用自定义处理程序 nats golang 保留订阅方法

CORS grpc 网关 GoLang

Go cmp - 如何为以 struct 为键的映射定义自定义相等性?

Golang Gin 绑定请求正文 XML 到 Slice

在 Golang 中,如何将接口作为泛型类型与 nil 进行比较?

如何在 Windows 上使用 cgo 为 386 arch 构建 lib?

Go GCP 同时模拟两个服务帐户

如何获得Ent中数字列的总和

如何使用 httputil.ReverseProxy 设置 X-Forwarded-For