example.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // Package example is a CoreDNS plugin that prints "example" to stdout on every packet received.
  2. //
  3. // It serves as an example CoreDNS plugin with numerous code comments.
  4. package example
  5. import (
  6. "fmt"
  7. "io"
  8. "os"
  9. "github.com/coredns/coredns/plugin"
  10. "github.com/coredns/coredns/plugin/metrics"
  11. "github.com/coredns/coredns/plugin/pkg/log"
  12. "github.com/miekg/dns"
  13. "golang.org/x/net/context"
  14. )
  15. // Example is an example plugin to show how to write a plugin.
  16. type Example struct {
  17. Next plugin.Handler
  18. }
  19. // ServeDNS implements the plugin.Handler interface. This method gets called when example is used
  20. // in a Server.
  21. func (e Example) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
  22. // This function could be simpler. I.e. just fmt.Println("example") here, but we want to show
  23. // a slightly more complex example as to make this more interesting.
  24. // Here we wrap the dns.ResponseWriter in a new ResponseWriter and call the next plugin, when the
  25. // answer comes back, it will print "example".
  26. // Debug log that we've have seen the query. This will only be shown when the debug plugin is loaded.
  27. log.Debug("Received response")
  28. // Wrap.
  29. pw := NewResponsePrinter(w)
  30. // Export metric with the server label set to the current server handling the request.
  31. requestCount.WithLabelValues(metrics.WithServer(ctx)).Add(1)
  32. // Call next plugin (if any).
  33. return plugin.NextOrFailure(e.Name(), e.Next, ctx, pw, r)
  34. }
  35. // Name implements the Handler interface.
  36. func (e Example) Name() string { return "example" }
  37. // ResponsePrinter wrap a dns.ResponseWriter and will write example to standard output when
  38. // WriteMsg is called.
  39. type ResponsePrinter struct {
  40. dns.ResponseWriter
  41. }
  42. // NewResponsePrinter returns ResponseWriter.
  43. func NewResponsePrinter(w dns.ResponseWriter) *ResponsePrinter {
  44. return &ResponsePrinter{ResponseWriter: w}
  45. }
  46. // WriteMsg calls the underlying ResponseWriter's WriteMsg method and prints "example" to standard
  47. // output.
  48. func (r *ResponsePrinter) WriteMsg(res *dns.Msg) error {
  49. fmt.Fprintln(out, ex)
  50. return r.ResponseWriter.WriteMsg(res)
  51. }
  52. // Make out a reference to os.Stdout so we can easily overwrite it for testing.
  53. var out io.Writer = os.Stdout
  54. // What we will print.
  55. const ex = "example"