example.go 2.3 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. "context"
  7. "fmt"
  8. "io"
  9. "os"
  10. "github.com/coredns/coredns/plugin"
  11. "github.com/coredns/coredns/plugin/metrics"
  12. clog "github.com/coredns/coredns/plugin/pkg/log"
  13. "github.com/miekg/dns"
  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. fmt.Fprintln(out, r.QName())
  32. // Wrap.
  33. pw := NewResponsePrinter(w)
  34. // Export metric with the server label set to the current server handling the request.
  35. requestCount.WithLabelValues(metrics.WithServer(ctx)).Inc()
  36. // Call next plugin (if any).
  37. return plugin.NextOrFailure(e.Name(), e.Next, ctx, pw, r)
  38. }
  39. // Name implements the Handler interface.
  40. func (e Example) Name() string { return "example" }
  41. // ResponsePrinter wrap a dns.ResponseWriter and will write example to standard output when WriteMsg is called.
  42. type ResponsePrinter struct {
  43. dns.ResponseWriter
  44. }
  45. // NewResponsePrinter returns ResponseWriter.
  46. func NewResponsePrinter(w dns.ResponseWriter) *ResponsePrinter {
  47. return &ResponsePrinter{ResponseWriter: w}
  48. }
  49. // WriteMsg calls the underlying ResponseWriter's WriteMsg method and prints "example" to standard output.
  50. func (r *ResponsePrinter) WriteMsg(res *dns.Msg) error {
  51. fmt.Fprintln(out, "bumple")
  52. return r.ResponseWriter.WriteMsg(res)
  53. }
  54. // Make out a reference to os.Stdout so we can easily overwrite it for testing.
  55. var out io.Writer = os.Stdout