Developing Caddy Plugins

Caddy is not extensible through configuration alone. Everything the server can do is a module, and the standard distribution happens to bundle a large set of them. When you need behaviour that no directive provides, you write a module in Go, register it, and build a custom binary that includes it. By the end of this page you will be able to implement an HTTP handler module, give it a lifecycle that fits Caddy’s provisioning model, expose it as a Caddyfile directive, build the result with xcaddy, and debug it using the same tools you use for the server itself.

1. How the module system works

Caddy is built around a registry of modules, each identified by a namespaced string such as http.handlers.reverse_proxy or tls.issuance.acme. The namespace tells Caddy what kind of thing the module is and where it may be used.

NamespacePurpose
http.handlers.*Request handlers in the HTTP chain
http.matchers.*Request matchers
http.reverse_proxy.*Reverse proxy transports and policies
tls.*, tls.issuance.*TLS behaviour and certificate issuance
caddy.logging.*Log writers and encoders
storage.*Certificate and configuration storage backends
dns.providers.*DNS challenge providers
events.*Event handlers

A module is any Go type that implements the caddy.Module interface, which is a single method returning a caddy.ModuleInfo. That struct carries the module ID and a constructor function.

func init() {
	caddy.RegisterModule(CustomHeader)
}

type CustomHeader struct {
	Value string `json:"value,omitempty"`
}

func (CustomHeader) CaddyModule() caddy.ModuleInfo {
	return caddy.ModuleInfo{
		ID:  "http.handlers.custom_header",
		New: func() caddy.Module { return new(CustomHeader) },
	}
}

RegisterModule is called from init(), so the registration happens as soon as the package is loaded, before any configuration is parsed.

2. The module lifecycle

Caddy creates, provisions, validates, and eventually disposes of your module. Implementing the optional interfaces is how you hook into those stages.

func (h *CustomHeader) Provision(ctx caddy.Context) error {
	if h.Value == "" {
		return caddy.Error("custom_header requires a value", nil)
	}
	h.logger = ctx.Logger()
	return nil
}

func (h *CustomHeader) Validate() error {
	return nil
}

func (h *CustomHeader) Cleanup() error {
	return nil
}
  • Provision receives a caddy.Context, which carries the logger and any dependencies the module asked for. Do the setup work here, not in the constructor.
  • Validate runs after provisioning and is where you reject a configuration that does not make sense. Returning an error here aborts the load with a clear message.
  • Cleanup is called when the configuration is replaced or the server shuts down. Release anything you acquired.

3. Writing an HTTP handler

A handler that participates in the middleware chain implements caddyhttp.MiddlewareHandler, whose ServeHTTP receives the next handler in the chain.

func (h *CustomHeader) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error {
	w.Header().Set("X-Custom-Header", h.Value)
	return next.ServeHTTP(w, r)
}

Returning nil means the response was handled. Returning an error hands the request to Caddy’s error handling, which is how you produce a 500 page or redirect to a custom error route. To answer the request yourself instead, write the response and return nil without calling next.

4. Caddyfile support

Without a Caddyfile parser, the module is only usable from JSON. To let users write it in a Caddyfile, implement caddyfile.Unmarshaler and register a directive.

func init() {
	httpcaddyfile.RegisterHandlerDirective("custom_header", parseCaddyfileHTTP)
	httpcaddyfile.RegisterDirectiveOrder("custom_header", httpcaddyfile.Before, "header")
}

func parseCaddyfileHTTP(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) {
	var hd CustomHeader
	err := hd.UnmarshalCaddyfile(h.Dispenser)
	return &hd, err
}

func (h *CustomHeader) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
	d.Next()
	if !d.NextArg() {
		return d.ArgErr()
	}
	h.Value = d.Val()
	return nil
}

The Dispenser walks the tokens of the directive. d.Next() advances to the directive name, d.NextArg() moves to the next argument on the same line, d.Val() returns the current token, and d.ArgErr() produces a good error message when the arguments are wrong.

RegisterDirectiveOrder places the new directive relative to one of the standard directives, so that it runs in a sensible position in the chain without the user having to wrap it in a route block.

Now the module can be used from a Caddyfile:

example.com {
	custom_header "served-by-caddy"
	respond "ok" 200
}

5. Building the binary

xcaddy builds a Caddy binary that includes extra modules.

xcaddy init
cd my-caddy-plugin
xcaddy build --with .

For a plugin that lives in its own repository, point --with at the module path.

xcaddy build --with github.com/yourname/caddy-custom-header

The resulting binary is a normal Caddy binary that simply has more modules compiled in, so it is installed and operated exactly like the standard one.

./caddy list-modules | grep custom_header
./caddy build-info

6. Debugging and testing

The most useful tools are the ones Caddy already ships.

# Does the Caddyfile parse into the JSON you expected?
caddy adapt --config Caddyfile --pretty

# Is the module actually registered in this binary?
caddy list-modules | grep custom_header

# Run the server in the foreground with debug logging.
caddy run --config Caddyfile --adapter caddyfile

The debug global option raises the log level, and caddy run prints the startup log to the terminal so you can see provision errors immediately.

Unit tests for the module should exercise the handler directly by constructing it, calling Provision, and then calling ServeHTTP with an httptest recorder and a stub caddyhttp.Handler as the next link in the chain.

7. Publishing

  • Use a semantic version tag. Caddy modules depend on the Caddy API, so a v2 major version tracks compatibility with the Caddy 2 module API.
  • Document the module ID and the Caddyfile syntax. Both appear in the output of caddy adapt, so users rely on them.
  • Keep the module in the standard namespaces. A module under a namespace Caddy does not know will be rejected at load time.
caddy plugingo modulecustom directivexcaddy

Approach:

The requirement is a directive that adds a response header to every request, usable from a Caddyfile, in a custom binary. The work splits into four parts: the module type with its identity, the lifecycle hooks, the HTTP behaviour, and the Caddyfile adapter that turns human-written tokens into the module’s JSON structure.

Steps:

  1. Create the Go module with a go.mod that requires Caddy v2, and choose a module ID inside an existing namespace. The ID http.handlers.custom_header places the module where Caddy expects request handlers, and it must be unique across all compiled modules.
  2. Implement caddy.Module by returning a caddy.ModuleInfo with the ID and a constructor, and call caddy.RegisterModule from init() so registration happens before configuration is parsed.
  3. Implement Provision to validate the input and to capture the logger from the context. Setup belongs in Provision, not in the constructor.
  4. Implement caddyhttp.MiddlewareHandler. Set the header, then call next.ServeHTTP so that the rest of the chain still runs. Returning an error instead routes the request into Caddy’s error handling.
  5. Implement caddyfile.Unmarshaler and register the directive with httpcaddyfile.RegisterHandlerDirective, which gives the directive an optional matcher token for free.
  6. Register the position with httpcaddyfile.RegisterDirectiveOrder, so the directive runs in a predictable place without the user wrapping it in a route block.
  7. Build with xcaddy build --with ., confirm the module is present with caddy list-modules, and check the generated JSON with caddy adapt --pretty before restarting the server.

Answer:

The plugin is one Go module with two files. The module file defines CustomHeader, registers it with caddy.RegisterModule(CustomHeader) under the ID http.handlers.custom_header, implements Provision so that an empty value is rejected, and implements ServeHTTP so that the header is set before next.ServeHTTP runs. The adapter file registers the directive and parses it:

func init() {
	httpcaddyfile.RegisterHandlerDirective("custom_header", parseCaddyfileHTTP)
	httpcaddyfile.RegisterDirectiveOrder("custom_header", httpcaddyfile.Before, "header")
}

func parseCaddyfileHTTP(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) {
	var hd CustomHeader
	err := hd.UnmarshalCaddyfile(h.Dispenser)
	return &hd, err
}

func (h *CustomHeader) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
	d.Next()
	if !d.NextArg() {
		return d.ArgErr()
	}
	h.Value = d.Val()
	return nil
}

The build is xcaddy build --with .. After it, caddy list-modules shows http.handlers.custom_header, and caddy adapt --pretty on a Caddyfile containing custom_header "served-by-caddy" produces a route whose handler has "handler": "custom_header" and "value": "served-by-caddy". Requests to that site then carry the X-Custom-Header response header.

Found an issue with this content?

Tell us what could be improved.