mirror of
https://github.com/coredns/coredns.git
synced 2025-11-01 18:53:43 -04:00
plugin/template: support metadata (#2958)
* Enable use of metadata in templates * Update README * Don't stash away ctx, instead use a new func
This commit is contained in:
@@ -8,6 +8,7 @@ import (
|
||||
gotmpl "text/template"
|
||||
|
||||
"github.com/coredns/coredns/plugin"
|
||||
"github.com/coredns/coredns/plugin/metadata"
|
||||
"github.com/coredns/coredns/plugin/metrics"
|
||||
"github.com/coredns/coredns/plugin/pkg/fall"
|
||||
"github.com/coredns/coredns/plugin/pkg/upstream"
|
||||
@@ -47,6 +48,19 @@ type templateData struct {
|
||||
Type string
|
||||
Message *dns.Msg
|
||||
Question *dns.Question
|
||||
md map[string]metadata.Func
|
||||
}
|
||||
|
||||
func (data *templateData) Meta(metaName string) string {
|
||||
if data.md == nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
if f, ok := data.md[metaName]; ok {
|
||||
return f()
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
// ServeDNS implements the plugin.Handler interface.
|
||||
@@ -59,7 +73,7 @@ func (h Handler) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg)
|
||||
}
|
||||
|
||||
for _, template := range h.Templates {
|
||||
data, match, fthrough := template.match(state, zone)
|
||||
data, match, fthrough := template.match(ctx, state, zone)
|
||||
if !match {
|
||||
if !fthrough {
|
||||
return dns.RcodeNameError, nil
|
||||
@@ -114,7 +128,7 @@ func (h Handler) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg)
|
||||
// Name implements the plugin.Handler interface.
|
||||
func (h Handler) Name() string { return "template" }
|
||||
|
||||
func executeRRTemplate(server, section string, template *gotmpl.Template, data templateData) (dns.RR, error) {
|
||||
func executeRRTemplate(server, section string, template *gotmpl.Template, data *templateData) (dns.RR, error) {
|
||||
buffer := &bytes.Buffer{}
|
||||
err := template.Execute(buffer, data)
|
||||
if err != nil {
|
||||
@@ -129,9 +143,9 @@ func executeRRTemplate(server, section string, template *gotmpl.Template, data t
|
||||
return rr, nil
|
||||
}
|
||||
|
||||
func (t template) match(state request.Request, zone string) (templateData, bool, bool) {
|
||||
func (t template) match(ctx context.Context, state request.Request, zone string) (*templateData, bool, bool) {
|
||||
q := state.Req.Question[0]
|
||||
data := templateData{}
|
||||
data := &templateData{md: metadata.ValueFuncs(ctx)}
|
||||
|
||||
zone = plugin.Zones(t.zones).Matches(state.Name())
|
||||
if zone == "" {
|
||||
|
||||
Reference in New Issue
Block a user