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.
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.
| Namespace | Purpose |
|---|---|
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.
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
}
Provisionreceives acaddy.Context, which carries the logger and any dependencies the module asked for. Do the setup work here, not in the constructor.Validateruns 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.Cleanupis called when the configuration is replaced or the server shuts down. Release anything you acquired.
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.
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
}
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
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.
- Use a semantic version tag. Caddy modules depend on the Caddy API, so a
v2major 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.
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:
- Create the Go module with a
go.modthat requires Caddy v2, and choose a module ID inside an existing namespace. The IDhttp.handlers.custom_headerplaces the module where Caddy expects request handlers, and it must be unique across all compiled modules. - Implement
caddy.Moduleby returning acaddy.ModuleInfowith the ID and a constructor, and callcaddy.RegisterModulefrominit()so registration happens before configuration is parsed. - Implement
Provisionto validate the input and to capture the logger from the context. Setup belongs inProvision, not in the constructor. - Implement
caddyhttp.MiddlewareHandler. Set the header, then callnext.ServeHTTPso that the rest of the chain still runs. Returning an error instead routes the request into Caddy’s error handling. - Implement
caddyfile.Unmarshalerand register the directive withhttpcaddyfile.RegisterHandlerDirective, which gives the directive an optional matcher token for free. - Register the position with
httpcaddyfile.RegisterDirectiveOrder, so the directive runs in a predictable place without the user wrapping it in arouteblock. - Build with
xcaddy build --with ., confirm the module is present withcaddy list-modules, and check the generated JSON withcaddy adapt --prettybefore 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.
