Cutom module: Adding parameter to caddyfile

I have implmented a custom module called my handler.
The module received one paramater, so the directive is caddyfile should look like this:

myhandler 50

I parse the parameters in the method:

func (f *Filter) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {

which is called from:

func parseCaddyfileHandler(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) {
	f := &Filter{}
	err := f.UnmarshalCaddyfile(h.Dispenser)
	return f, err
}

loaded in the init function:

func init() {
	rand.Seed(uint64(time.Now().UnixNano()))
	f := Filter{}
	caddy.RegisterModule(f)
	httpcaddyfile.RegisterHandlerDirective("myhandler", parseCaddyfileHandler)

}

The problem is that the pointer in the UnmarshalCaddyfile method is different from the Provision method, so the caddyfile parameters does not propogate to provision (i.e. I set the parameter in the UnmarshalCaddyfile method, but it does not appear in the Provision).
What do I miss?

Sorry for the delay, was taking some time off from the forums.

That’s correct, you should not assume it’s the same struct instance. Caddy has the intermediate step of converting Caddyfile to JSON config (encoding the config to a JSON string) then loading it as a config from JSON at runtime, which is when the actual struct that will be used to run is initialized and provisioned.

You should make sure your struct’s fields correctly have json tags so that adapting Caddyfile to JSON works correctly. Use the caddy adapt -p command to see that it looks correct after parsing the Caddyfile. Make sure to use omitempty for most fields (to allow zero/empty values to be omitted from the JSON output).

1 Like

This topic was automatically closed after 60 days. New replies are no longer allowed.