example.go 2.4 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. // Define log to be a logger with the plugin name in it. This way we can just use log.Info and
  16. // friends to log.
  17. var log = clog.NewWithPlugin("example")
  18. // Example is an example plugin to show how to write a plugin.
  19. type Example struct {
  20. Next plugin.Handler
  21. }
  22. // ServeDNS implements the plugin.Handler interface. This method gets called when example is used
  23. // in a Server.
  24. func (e Example) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
  25. // This function could be simpler. I.e. just fmt.Println("example") here, but we want to show
  26. // a slightly more complex example as to make this more interesting.
  27. // Here we wrap the dns.ResponseWriter in a new ResponseWriter and call the next plugin, when the
  28. // answer comes back, it will print "example".
  29. // Debug log that we've have seen the query. This will only be shown when the debug plugin is loaded.
  30. log.Debug("Received response")
  31. // Wrap.
  32. pw := NewResponsePrinter(w)
  33. // Export metric with the server label set to the current server handling the request.
  34. requestCount.WithLabelValues(metrics.WithServer(ctx)).Inc()
  35. // Call next plugin (if any).
  36. return plugin.NextOrFailure(e.Name(), e.Next, ctx, pw, r)
  37. }
  38. // Name implements the Handler interface.
  39. func (e Example) Name() string { return "example" }
  40. // ResponsePrinter wrap a dns.ResponseWriter and will write example to standard output when WriteMsg is called.
  41. type ResponsePrinter struct {
  42. dns.ResponseWriter
  43. }
  44. // NewResponsePrinter returns ResponseWriter.
  45. func NewResponsePrinter(w dns.ResponseWriter) *ResponsePrinter {
  46. return &ResponsePrinter{ResponseWriter: w}
  47. }
  48. // WriteMsg calls the underlying ResponseWriter's WriteMsg method and prints "example" to standard 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"