KrakenD插件读取配置设置

问题描述

我用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
}

解决方法

我自己弄清楚了。在为问题构建示例代码时,我注意到它可以完全按照问题中的编码方式工作。