What is a Config Adapter?
A config adapter implements a simple interface:configadapters.go:24-28
- Receives raw configuration bytes (e.g., Caddyfile text)
- Parses and validates the input
- Transforms it into Caddy JSON
- Returns the JSON, any warnings, and potential errors
Built-in Adapters
Caddy ships with the Caddyfile adapter, which is the most popular format:httptype.go:38-40
The Caddyfile adapter is actually a family of adapters with different “server types”. The HTTP server type is the most common.
How Adapters Work
1
Input Parsing
The adapter parses the input format into an internal representation.For Caddyfile, this involves:
- Lexical analysis (tokenization)
- Syntax parsing (server blocks, directives)
- Placeholder replacement
- Import resolution
2
Validation
The adapter validates the parsed configuration:Warnings are collected but don’t stop the adaptation process.
configadapters.go:30-36
3
Transformation
The adapter transforms the configuration into Caddy’s JSON structure.Helper functions simplify JSON generation:
configadapters.go:46-60
4
Module Object Creation
For module values, adapters use special helpers:This allows the adapter to specify module names inline with configuration.
configadapters.go:62-106
Registering Adapters
Adapters must be registered before they can be used:configadapters.go:108-117
Adapters are also registered as Caddy modules in the
caddy.adapters namespace. This ensures they appear in module listings.Adapter Module Wrapper
configadapters.go:125-140
Using Adapters
CLI Usage
You can specify an adapter when loading a config:API Usage
Adapters can be retrieved programmatically:configadapters.go:119-123
Caddyfile Adapter Deep Dive
The Caddyfile adapter is the most sophisticated adapter. Let’s explore how it works:Server Blocks
Caddyfile configurations are organized into server blocks:Phase 1: Parsing
Phase 1: Parsing
Server blocks are parsed into an internal structure:
httptype.go:66-80
Phase 2: Directive Processing
Phase 2: Directive Processing
Each directive is processed by its registered handler:
httptype.go:120-159
Phase 3: Server Construction
Phase 3: Server Construction
Server blocks are consolidated and HTTP servers are created:
httptype.go:174-188
Directive Registration
Directives must be registered to be recognized:Creating Custom Adapters
Here’s how to create a simple YAML adapter:1
Define the Adapter
2
Implement the Adapt Method
3
Add Transformation Logic
Warning System
Adapters should generate warnings for non-fatal issues:configadapters.go:38-44
Best Practices
1
Preserve Line Information
Track file and line numbers to provide helpful error messages:
2
Use Warning System
Generate warnings for deprecated features or potential issues:
3
Validate Early
Catch errors during parsing rather than waiting for Caddy to load the config:
4
Use Helper Functions
Leverage the
JSON() and JSONModuleObject() helpers:5
Document Your Format
Provide clear documentation and examples for your adapter’s input format.