example.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. // The example plugin prints example to stdout on every packet received.
  2. package example
  3. import (
  4. "fmt"
  5. "io"
  6. "os"
  7. "github.com/coredns/coredns/plugin"
  8. "github.com/miekg/dns"
  9. "golang.org/x/net/context"
  10. )
  11. // Example is an example plugin to show how to write a plugin.
  12. type Example struct {
  13. Next plugin.Handler
  14. }
  15. // ServeDNS implements the plugin.Handler interface.
  16. func (e Example) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
  17. // Somewhat convoluted, as we could have printed "example" here and just call
  18. // the next plugin - but as an example, show how to wrap a ResponseWriter might be
  19. // educational.
  20. pw := NewResponsePrinter(w)
  21. return plugin.NextOrFailure(e.Name(), e.Next, ctx, pw, r)
  22. }
  23. // Name implements the Handler interface.
  24. func (e Example) Name() string { return "example" }
  25. type ResponsePrinter struct {
  26. dns.ResponseWriter
  27. }
  28. // NewResponsePrinter returns a dns.Msg modifier that print example when a query is received.
  29. func NewResponsePrinter(w dns.ResponseWriter) *ResponsePrinter {
  30. return &ResponsePrinter{ResponseWriter: w}
  31. }
  32. // WriteMsg records the status code and calls the underlying ResponseWriter's WriteMsg method.
  33. func (r *ResponsePrinter) WriteMsg(res *dns.Msg) error {
  34. fmt.Fprintf(out, "example")
  35. return r.ResponseWriter.WriteMsg(res)
  36. }
  37. var out io.Writer = os.Stdout