Files
coredns/core/dnsserver/example_test.go
houyuwushang 8a269232e4 core/dnsserver: support explicit registration for embedded hosts (#8525)
* core/dnsserver: test host-plugin embedding with forward

Signed-off-by: houyuwushang <liuluoqianqiu@outlook.com>

* core/dnsserver: add a directive setter for embedded hosts

Signed-off-by: houyuwushang <liuluoqianqiu@outlook.com>

* core/dnsserver: support explicit server registration for embedded hosts

Signed-off-by: houyuwushang <liuluoqianqiu@outlook.com>

---------

Signed-off-by: houyuwushang <liuluoqianqiu@outlook.com>
2026-09-10 20:54:41 -07:00

83 lines
2.0 KiB
Go

package dnsserver_test
import (
"errors"
"fmt"
"github.com/coredns/caddy"
"github.com/coredns/coredns/core/dnsserver"
_ "github.com/coredns/coredns/plugin/bind"
_ "github.com/coredns/coredns/plugin/whoami"
"github.com/miekg/dns"
)
func ExampleSetDirectives() {
oldDirectives := dnsserver.Directives
defer func() { dnsserver.Directives = oldDirectives }()
if err := dnsserver.SetDirectives([]string{"bind", "whoami"}); err != nil {
panic(err)
}
fmt.Println(dnsserver.Directives)
// Output: [bind whoami]
}
func ExampleRegister() {
// Required before caddy.Start in builds with coredns_manual_registration;
// harmless when the default import-time registration has already run.
if err := dnsserver.Register(); err != nil {
panic(err)
}
fmt.Println("registered")
// Output: registered
}
func Example_embedding() {
oldDirectives := dnsserver.Directives
oldCaddyQuiet := caddy.Quiet
oldDNSQuiet := dnsserver.Quiet
defer func() {
dnsserver.Directives = oldDirectives
caddy.Quiet = oldCaddyQuiet
dnsserver.Quiet = oldDNSQuiet
}()
// Import only the plugins the host needs and set their execution order
// before starting the first server.
dnsserver.Directives = []string{"bind", "whoami"}
if err := dnsserver.Register(); err != nil {
panic(err)
}
caddy.Quiet = true
dnsserver.Quiet = true
instance, err := caddy.Start(caddy.CaddyfileInput{
Filepath: "Corefile",
Contents: []byte(".:0 {\nbind 127.0.0.1\nwhoami\n}\n"),
ServerTypeName: "dns",
})
if err != nil {
panic(err)
}
defer func() {
shutdownErr := errors.Join(instance.ShutdownCallbacks()...)
stopErr := instance.Stop()
instance.Wait()
if err := errors.Join(shutdownErr, stopErr); err != nil {
panic(err)
}
}()
server := instance.Servers()[0].LocalAddr().String()
query := new(dns.Msg)
query.SetQuestion("example.org.", dns.TypeA)
response, err := dns.Exchange(query, server)
if err != nil {
panic(err)
}
fmt.Println(response.Authoritative, response.Rcode == dns.RcodeSuccess)
// Output: true true
}