example.go 2.3 KB

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