setup.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package example
  2. import (
  3. "github.com/coredns/coredns/core/dnsserver"
  4. "github.com/coredns/coredns/plugin"
  5. "github.com/coredns/coredns/plugin/metrics"
  6. "github.com/mholt/caddy"
  7. )
  8. // init registers this plugin within the Caddy plugin framework. It uses "example" as the
  9. // name, and couples it to the Action "setup".
  10. func init() {
  11. caddy.RegisterPlugin("example", caddy.Plugin{
  12. ServerType: "dns",
  13. Action: setup,
  14. })
  15. }
  16. // setup is the function that gets called when the config parser see the token "example". Setup is responsible
  17. // for parsing any extra options the example plugin may have. The first token this function sees is "example".
  18. func setup(c *caddy.Controller) error {
  19. c.Next() // Ignore "example" and give us the next token.
  20. if c.NextArg() {
  21. // If there was another token, return an error, because we don't have any configuration.
  22. // Any errors returned from this setup function should be wrapped with plugin.Error, so we
  23. // can present a slightly nicer error message to the user.
  24. return plugin.Error("example", c.ArgErr())
  25. }
  26. // Add a startup function that will -- after all plugins have been loaded -- check if the
  27. // prometheus plugin has been used - if so we will export metrics. We can only register
  28. // this metric once, hence the "once.Do".
  29. c.OnStartup(func() error {
  30. once.Do(func() {
  31. m := dnsserver.GetConfig(c).Handler("prometheus")
  32. if m == nil {
  33. return
  34. }
  35. if x, ok := m.(*metrics.Metrics); ok {
  36. x.MustRegister(requestCount)
  37. }
  38. })
  39. return nil
  40. })
  41. // Add the Plugin to CoreDNS, so Servers can use it in their plugin chain.
  42. dnsserver.GetConfig(c).AddPlugin(func(next plugin.Handler) plugin.Handler {
  43. return Example{Next: next}
  44. })
  45. // All OK, return a nil error.
  46. return nil
  47. }