droos02800 2015-06-30 22:40
浏览 15
已采纳

通过提供键从map [string] interface {}调用函数

I want to be able to pass function name to gin.Engine route handler. I have the following code;

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

The compiler gives the following error;

./app.go:60: ss["auth"].Ping undefined (type interface {} has no field or method Ping)

Any ideas about how to fix that?

  • 写回答

1条回答 默认 最新

  • dorisdong0514 2015-06-30 22:45
    关注

    interface{} works for just about any type, the problem is that you've failed to assert which type the thing is. In this case you would need something like... ss["auth"].(*StatusService).Ping(myCtxInstance). This answer has a more thorough example which I'll refrain from duplicating; Go map of functions

    Couple other things; if your real use case is as simple as your example just stop what you're doing and add func(ctx *gin.Context) as a second argument. Also, depending on the nature of the functions you want to use (like if they all have the same args and return types) then you might want to use a second arg for the delegates, map[string]func(argumentType) would be more appropriate.

    The design you currently have pushes all errors to runtime which obviously is less desirable than the compile time safety you'd get from either of the options I touched on above.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作