Reputation: 26945
I want to dynamically create an HTTP router using custom plugins/middleware, currently, I am using a config.yml
for example:
plugins:
- waf
- jwt
- cors
After parsing the yml
file I create the routes like this:
route := violetear.New()
chain := middleware.New()
for _, plugin := range Plugins {
chain := chain.Append(plugin)
}
router.Handle("/test", chain.Then(myHandler))
log.Fatal(http.ListenAndServe(":8080", router))
For this to work, I would have to include all the plugins in the import section, something like:
import (
"net/http"
"github.com/nbari/violetear"
"github.com/nbari/violetear/midleware"
// How to deal with this
"github.com/example/waf"
"github.com/example/jwt"
"github.com/example/cors"
)
I would need to change the current config format to be something more useful/generic probably something like:
plugins:
- [github.com/foo, foo]
- [github.com/bar, bar]
But besides that what could be the best approach to "dynamically" create the imports or to generate the code the one later could be compiled?
Any ideas?
Upvotes: 1
Views: 386
Reputation: 418067
Go is a statically linked language. This means if a package is not referenced at compile time (from your .go
source files), that package will not be linked / compiled into the executable binary, which implies it will not be availabe at runtime.
So the easiest is to just use imports.
If you want truly dynamic configuration, plugins introduced in Go 1.8 may be an option for you, but using plugins complicates things and I would only use that as a last resort. Also note that plugins currently only work on linux.
Related questions:
Go Plugin variable initialization
go 1.8 plugin use custom interface
Upvotes: 1