Add example middleware

Serves both as documentation and to test external middleware
compilation.
This commit is contained in:
Miek Gieben 2017-07-29 09:17:24 +01:00
commit 1fb7424a47
3 changed files with 94 additions and 0 deletions

26
README.md Normal file
View File

@ -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.

40
alias.go Normal file
View File

@ -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)
}

28
setup.go Normal file
View File

@ -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
}