Skip to content

Instantly share code, notes, and snippets.

@miekg
Created September 7, 2025 06:00
Show Gist options
  • Save miekg/b9006dbb35873dd0be5acfb832c86da1 to your computer and use it in GitHub Desktop.
Save miekg/b9006dbb35873dd0be5acfb832c86da1 to your computer and use it in GitHub Desktop.
testserv vs coredns "plugin"
difference between my newer impl and coredns for a plugin that adds a NSID OPT rr to the Msg.
First coredns, after that "testserv"
```go
// Nsid plugin
type Nsid struct {
Next plugin.Handler
Data string
}
// ResponseWriter is a response writer that adds NSID response
type ResponseWriter struct {
dns.ResponseWriter
Data string
request *dns.Msg
}
// ServeDNS implements the plugin.Handler interface.
func (n Nsid) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
if option := r.IsEdns0(); option != nil {
for _, o := range option.Option {
if _, ok := o.(*dns.EDNS0_NSID); ok {
nw := &ResponseWriter{ResponseWriter: w, Data: n.Data, request: r}
return plugin.NextOrFailure(n.Name(), n.Next, ctx, nw, r)
}
}
}
return plugin.NextOrFailure(n.Name(), n.Next, ctx, w, r)
}
// WriteMsg implements the dns.ResponseWriter interface.
func (w *ResponseWriter) WriteMsg(res *dns.Msg) error {
if w.request.IsEdns0() != nil && res.IsEdns0() == nil {
res.SetEdns0(w.request.IsEdns0().UDPSize(), true)
}
if option := res.IsEdns0(); option != nil {
var exists bool
for _, o := range option.Option {
if e, ok := o.(*dns.EDNS0_NSID); ok {
e.Code = dns.EDNS0NSID
e.Nsid = hex.EncodeToString([]byte(w.Data))
exists = true
}
}
// Append the NSID if it doesn't exist in EDNS0 options
if !exists {
option.Option = append(option.Option, &dns.EDNS0_NSID{
Code: dns.EDNS0NSID,
Nsid: hex.EncodeToString([]byte(w.Data)),
})
}
}
return w.ResponseWriter.WriteMsg(res)
}
```
newer impl
```go
type Nsid struct {
Data string
}
func (n *Nsid) HandlerFunc(next dns.HandlerFunc) dns.HandlerFunc {
return dns.HandlerFunc(func(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) {
for _, o := range r.Pseudo {
if _, ok := o.(*dns.NSID); ok {
ctx = dnsmsg.WithValue(ctx, n.Key(),
func(m *dns.Msg) *dns.Msg {
nsid := &dns.NSID{Nsid: n.Data}
m.Pseudo = append(m.Pseudo, nsid)
return m
})
break
}
}
next.ServeDNS(ctx, w, r)
})
}
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment