Go 通过给定键从map[string]接口{}调用函数
我希望能够将函数名传递给gin.Engine路由处理程序。我有以下代码Go 通过给定键从map[string]接口{}调用函数,go,Go,我希望能够将函数名传递给gin.Engine路由处理程序。我有以下代码 // status service type StatusService struct { App *gin.Engine } func (s *StatusService) Ping(ctx *gin.Context) { ctx.JSON(200, gin.H{ "message": "pong", }) } app := gin.Default() // define ser
// status service
type StatusService struct {
App *gin.Engine
}
func (s *StatusService) Ping(ctx *gin.Context) {
ctx.JSON(200, gin.H{
"message": "pong",
})
}
app := gin.Default()
// define services
statusService := &services.StatusService{
App: app,
}
ss := make(map[string]interface{})
ss["auth"] = statusService
app.GET("/ping", ss["auth"].Ping)
编译器给出以下错误
./app.go:60: ss["auth"].Ping undefined (type interface {} has no field or method Ping)
关于如何解决这个问题有什么想法吗?
接口{}
适用于几乎任何类型,问题是您无法断言该对象是哪种类型。在这种情况下,你需要像ss[“auth”]。(*StatusService).Ping(myCtxInstance)
。这个答案有一个更彻底的例子,我将避免重复
其他一些事情;如果您的实际用例像您的示例一样简单,只需停止您正在做的事情,并添加func(ctx*gin.Context)
作为第二个参数。此外,根据要使用的函数的性质(例如,如果它们都具有相同的参数和返回类型),您可能希望为委托使用第二个参数,map[string]func(argumentType)
更合适
您当前的设计将所有错误推送到运行时,这显然不如我上面提到的任何一个选项所提供的编译时安全性好。好吧,我不必定义映射结构。我可以初始化变量并将其函数传递给
app.GET()
。使用它更方便吗?顺便说一句,ss[“auth”](func(ctx*gin.Context))。Ping不方便work@aacanakin是的,有一件事我没有注意到,那就是对于Ping
,你有一个接收类型s*StatusService
,所以你实际上需要做类型断言。我将更新该示例。谢谢。它起作用了<代码>应用程序获取(“/ping”,(*statusService.ping)