setup.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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/caddyserver/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() { metrics.MustRegister(c, requestCount) })
  31. return nil
  32. })
  33. // Add the Plugin to CoreDNS, so Servers can use it in their plugin chain.
  34. dnsserver.GetConfig(c).AddPlugin(func(next plugin.Handler) plugin.Handler {
  35. return Example{Next: next}
  36. })
  37. // All OK, return a nil error.
  38. return nil
  39. }