commit 1fb7424a4766a424aaf99940b03b726890b9d1c6 Author: Miek Gieben Date: Sat Jul 29 09:17:24 2017 +0100 Add example middleware Serves both as documentation and to test external middleware compilation. diff --git a/README.md b/README.md new file mode 100644 index 0000000..2d3343c --- /dev/null +++ b/README.md @@ -0,0 +1,26 @@ +# example + +The example middleware prints "example" on every query received. It can be used as documentation for +writing external middleware and to test if external middleware compiles with CoreDNS. + +## Syntax + +~~~ txt +example +~~~ + +## Examples + +``` +example.com { + file example.com.db { + upstream 8.8.8.8 + } + example +} +``` + +## How to Enable + +Follow [these](/2017/07/25/compile-time-enabling-or-disabling-middleware/) steps. +*example* should be put relatively early in the middleware chain. diff --git a/alias.go b/alias.go new file mode 100644 index 0000000..4bde260 --- /dev/null +++ b/alias.go @@ -0,0 +1,40 @@ +// The example middleware prints example to stdout on every packet received. +package example + +import ( + "fmt" + + "github.com/coredns/coredns/middleware" + + "github.com/miekg/dns" + "golang.org/x/net/context" +) + +// Example is an example middleware to ... +type Example struct { + Next middleware.Handler +} + +// ServeDNS implements the middleware.Handler interface. +func (e Example) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) { + pw := NewResponsePrinter(w) + return middleware.NextOrFailure(e.Name(), e.Next, ctx, pw, r) +} + +// Name implements the Handler interface. +func (e Example) Name() string { return "example" } + +type ResponsePrinter struct { + dns.ResponseWriter +} + +// NewResponsePrinter returns a dns.Msg modifier that print example when a query is received. +func NewResponsePrinter(w dns.ResponseWriter) *ResponsePrinter { + return &ResponsePrinter{ResponseWriter: w} +} + +// WriteMsg records the status code and calls the underlying ResponseWriter's WriteMsg method. +func (r *ResponsePrinter) WriteMsg(res *dns.Msg) error { + fmt.Println("example") + return r.ResponseWriter.WriteMsg(res) +} diff --git a/setup.go b/setup.go new file mode 100644 index 0000000..1056d52 --- /dev/null +++ b/setup.go @@ -0,0 +1,28 @@ +package example + +import ( + "github.com/coredns/coredns/core/dnsserver" + "github.com/coredns/coredns/middleware" + + "github.com/mholt/caddy" +) + +func init() { + caddy.RegisterPlugin("example", caddy.Plugin{ + ServerType: "dns", + Action: setup, + }) +} + +func setup(c *caddy.Controller) error { + c.Next() + if c.NextArg() { + return middleware.Error("example", c.ArgErr()) + } + + dnsserver.GetConfig(c).AddMiddleware(func(next middleware.Handler) middleware.Handler { + return Example{Next: next} + }) + + return nil +}