KrakenD plugin read config setting

748 views Asked by At

I have written a simple server plugin for KrakenD Gateway in GO language. It injects the code before routing starts.
I am trying to read a config setting from my krakend.json to pass the setting to my plugin at startup. Below I used the setting mysetting as an example (please see the code between the comments HERE THE READ OF MY SETTING STARTS/ENDS).

How can I use the value of mysetting from the config inside the plugin?

Here is my krakend.json config file that is used as the -c argument on startup:

{
  "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,
}

Here is the code for the registerHandlers function:

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
}
1

There are 1 answers

0
Florian H On BEST ANSWER

I figured it out myself. When building the sample code for the question I noticed it works exacly the way it is coded in the question.