我用 GO 语言为 KrakenD Gateway 编写了一个简单的服务器插件。它在路由开始之前注入代码。
我正在尝试从我的配置中读取配置设置,krakend.json
以便在启动时将设置传递给我的插件。下面我以设置mysetting
为例(请看注释之间的代码HERE THE READ OF MY SETTING STARTS/ENDS
)。
如何使用mysetting
插件内部配置的值?
这是我在启动时krakend.json
用作-c
参数的配置文件:
{
"version": 2,
"timeout": "3000ms",
"cache_ttl": "300s",
"output_encoding": "json",
"name": "Gateway",
"plugin": {
"pattern": ".so",
"folder": "./plugins/"
},
"extra_config": {
"github_com/devopsfaith/krakend/transport/http/server/handler": {
"name": "testPlugin",
"mysetting": "Hello"
}
},
"endpoints": [
...
],
"port": 9010,
}
这是 registerHandlers 函数的代码:
func (r registerer) registerHandlers(ctx context.Context, extra map[string]interface{}, _ http.Handler) (http.Handler, error) {
// check the passed configuration and initialize the plugin
name, ok := extra["name"].(string)
if !ok {
return nil, errors.New("wrong config")
}
if name != string(r) {
return nil, fmt.Errorf("unknown register %s", name)
}
//************ HERE THE READ OF MY SETTING STARTS ************
setting, ok := extra["mysetting"].(string)
if !ok {
return nil, errors.New("mysetting missing in config")
}
fmt.Printf("PLUGIN: My custom setting: %s\n", setting)
//************ HERE THE READ OF MY SETTING ENDS ************
// return the actual handler wrapping or your custom logic so it can be used as a replacement for the default http handler
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
fmt.Fprintf(w, "%s, %q", setting, html.EscapeString(req.URL.Path))
}), nil
}