example.go 2.0 KB

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