So I’m working on building a very basic boilerplate Caddy plugin. But I’m having issues just compiling caddy with a plugin and I was hoping I could get some guidance. After this I will be working on porting an ingress toolkit and a onion routed DHT server as plugins. Caddy has the exact structure I realized I needed and instead of reinventing the wheel it seems building plugins on Caddy makes more sense.
The guide seems to assume some knowledge and doesn’t fully explain the process of building caddy with plugins.
It is my understanding to compile caddy with a plugin you need to modify:
caddy/caddy/caddymain/run.go
And add in the import line
_ "github.com/lostinblue/boilerplate-caddy-plugin"
Then this will cause the init() function in the plugin to run:
https://raw.githubusercontent.com/lostinblue/boilerplate-caddy-plugin/master/boilerplate.go
I’m trying to implement the simplest possible boilerplate plugin:
package boilerplate
import (
"net/http"
"regexp"
"time"
"github.com/mholt/caddy"
"github.com/mholt/caddy/caddyhttp/httpserver"
)
type matchDef struct {
Re *regexp.Regexp
Duration time.Duration
}
func init() {
caddy.RegisterPlugin("boilerplate", caddy.Plugin{
ServerType: "http",
Action: setup,
})
}
func setup(c *caddy.Controller) error {
cfg := httpserver.GetConfig(c)
mid := func(next httpserver.Handler) httpserver.Handler {
return boilerplateHandler{Next: next}
}
cfg.AddMiddleware(mid)
return nil
}
type boilerplateHandler struct {
Next httpserver.Handler
Rules []*matchDef
}
func (h boilerplateHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
for _, rule := range h.Rules {
if rule.Re.MatchString(r.URL.Path) {
w.Header().Set("Boilerplate", "TEST")
break
}
}
return h.Next.ServeHTTP(w, r)
}