Kay*_*lly 9 design-patterns go
我是Go的新手,如果有可扩展应用程序的既定设计模式,我很好奇.
例如,在我的源代码中,我有一个扩展目录,我为我的程序放置了不同的特定于应用程序的扩展.我目前按名称单独加载每个主函数.我希望程序在编译时自动包含我的扩展.
为了清楚起见,我不是试图在运行时动态加载扩展.我只想添加一个扩展程序,如下所示:
如果这对Go来说是不可能的,那么我会做出应有的决定,但我只是想有一个更好的方法来做到这一点.
为了更清楚地展示我想要简化的内容,这里是我现在所做的一个例子:
main.go
package main
import (
"github.com/go-martini/martini"
"gopath/project/extensions"
)
func main() {
app := martini.Classic()
// Enable Each Extension
app.Router.Group("/example", extensions.Example)
// app.Router.Group("/example2", extensions.Example2)
// ...
app.Run()
}
Run Code Online (Sandbox Code Playgroud)
扩展/ example.go
package extensions
import (
"github.com/codegangsta/martini-contrib/render"
"github.com/go-martini/martini"
)
func Example(router martini.Router) {
router.Get("", func(r render.Render) {
// respond to query
r.JSON(200, "")
})
}
Run Code Online (Sandbox Code Playgroud)
使用init每个扩展 go 文件中的方法来注册扩展。
所以plugin1.go你会写
func init() {
App.Router.Group("/example", extensions.Example)
}
Run Code Online (Sandbox Code Playgroud)
你需要公开app。
您可以在主代码中使用注册函数。
我在rclone中使用了这种技术:这是注册函数,这是调用它的示例。每个模块都是通过将它们包含在主包中来编译的