I’m trying to implement my first http.handlers custom plugin.
the code is:
package myhandler
import (
"net/http"
"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
)
func init() {
caddy.RegisterModule(Filter{})
}
// Filter is a custom module that processes HTTP requests and responses.
type Filter struct{}
// CaddyModule returns the Caddy module information.
func (Filter) CaddyModule() caddy.ModuleInfo {
return caddy.ModuleInfo{
ID: "http.handlers.myhandler",
New: func() caddy.Module { return new(Filter) },
}
}
// ServeHTTP is the middleware handler for this module.
func (f Filter) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error {
// Placeholder for functionality: log request path
caddy.Log().Info("Request handled: " + r.URL.String())
// Pass the request to the next handler in the chain
return next.ServeHTTP(w, r)
}
and I have built it using xcaddy: xcaddy build --with myhandler=.
I can see that the module is part of the module list:
./caddy list-modules| grep myhandler
http.handlers.myhandler
but when I’m trying to use it with this Caddyfile:
:6666 {
route {
myhandler
reverse_proxy 127.0.0.1:8080
}
}
I receive the following error:
./caddy run --config Caddyfile
2024/11/28 17:41:12.368 INFO using config from file {“file”: “Caddyfile”}
Error: adapting config using caddyfile: parsing caddyfile tokens for ‘route’: unrecognized directive: myhandler - are you sure your Caddyfile structure (nesting and braces) is correct?, at Caddyfile:5
What I’m doing wrong?