Before we look into the HTTP handler module implementation, we first need to study its placement in the configuration JSON. The simplest valid configuration JSON which blindly responds to clients with ok is:
{
"apps": {
"http": {
"servers": {
"srv0": {
"routes": [
{
"handle": [
{
"handler": "static_response",
"body": "ok"
}
]
}
]
}
}
}
}
}
N.B. the key-value of the objects in the handle array isn’t static. It varies based on the value of handler. The only key that is always present is handler, while everything else depends on the value of handler.
{
"handler": "<handler_name>",
// the remaining fields of this object are dependent on the
// type definition of `handler_name`
}
In other words, one key is used to tell Caddy the name of the module represented by that object. The rest of the keys depend on the kind of module it is. So all the handler modules in this place in the JSON structure will have a key of "handler" to say the name of the handler module, and all will have ServeHTTP() method. But all the other keys depend on each module’s individual configuration.
HTTP handlers/middlewares in Caddy have 2 criteria:
Their ModuleID is within the namespace http.handlers, e.g. the file-server handler has the module ID http.handlers.file_server
The implement the interface caddyhttp.MiddlewareHandler1, which is defined as:
type MiddlewareHandler interface {
ServeHTTP(http.ResponseWriter, *http.Request, Handler) error
}
Write a Caddy HTTP handler module which dumps the request headers into the response.
Remember: Use xcaddy list-modules and xcaddy run --config <config_file> to test your implementation
Use this Caddy config to test the implementation:
{
"apps": {
"http": {
"servers": {
"srv0": {
"listen": [
":443"
],
"routes": [
{
"handle": [
{
"handler": "dump_headers"
}
]
}
]
}
}
}
}
}