Reputation: 1400
I am fairly new to Go and am curious if there is an established design pattern for extensible applications.
For example, in my source I have an extensions directory where I place different application specific extensions for my program. I currently load each in my main function individually by name. I would like to have the program auto-include my extensions when it gets compiled.
Just to be clear, I am not trying to dynamically load extensions at runtime. I would just like to make adding an extension to the program as simple as:
If this is just not possible with Go then I'll make due, but I'm just thinking there has to be a better way to do this.
To show more clearly what I want to make simpler, here is an example of what I do now:
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()
}
extensions/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, "")
})
}
Upvotes: 9
Views: 1711
Reputation: 54117
Use an init
method in each extension go file to register the extension.
So in plugin1.go
you'd write
func init() {
App.Router.Group("/example", extensions.Example)
}
You'd need to make app
public.
You could use a registration function in the main code instead.
I use this technique in rclone: Here is the registration function and here is an example of it being called. The modules are each compiled in by including them in the main pacakge
Upvotes: 4