KrakenD 插件读取配置设置

KrakenD plugin read config setting

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

我自己想出来了。在为问题构建示例代码时,我注意到它的工作方式与问题中的编码方式完全相同。