example.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. This method gets called when example is used
  16. // in a Server.
  17. func (e Example) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
  18. // This function could be simpler. I.e. just fmt.Println("example") here, but we want to show
  19. // a slightly more complex example as to make this more interesting.
  20. // Here we wrap the dns.ResponseWriter in a new ResponseWriter and call the next plugin, when the
  21. // answer comes back, it will print "example".
  22. // Wrap.
  23. pw := NewResponsePrinter(w)
  24. // Call next plugin (if any).
  25. return plugin.NextOrFailure(e.Name(), e.Next, ctx, pw, r)
  26. }
  27. // Name implements the Handler interface.
  28. func (e Example) Name() string { return "example" }
  29. // ResponsePrinter wrap a dns.ResponseWriter and will write example to standard output when
  30. // WriteMsg is called.
  31. type ResponsePrinter struct {
  32. dns.ResponseWriter
  33. }
  34. // NewResponsePrinter returns ResponseWriter.
  35. func NewResponsePrinter(w dns.ResponseWriter) *ResponsePrinter {
  36. return &ResponsePrinter{ResponseWriter: w}
  37. }
  38. // WriteMsg calls the underlying ResponseWriter's WriteMsg method and prints "example" to standard
  39. // output.
  40. func (r *ResponsePrinter) WriteMsg(res *dns.Msg) error {
  41. fmt.Fprintln(out, ex)
  42. return r.ResponseWriter.WriteMsg(res)
  43. }
  44. // Make out a reference to os.Stdout so we can easily overwrite it for testing.
  45. var out io.Writer = os.Stdout
  46. // What we will print.
  47. const ex = "example"