coredns-ldap/example.go

61 lines
1.7 KiB
Go
Raw Normal View History

// The example plugin prints example to stdout on every packet received.
package example
import (
"fmt"
"io"
"os"
2017-09-15 20:29:47 +00:00
"github.com/coredns/coredns/plugin"
2018-02-27 11:39:01 +00:00
"github.com/miekg/dns"
"golang.org/x/net/context"
)
// Example is an example plugin to show how to write a plugin.
type Example struct {
2017-09-15 20:29:47 +00:00
Next plugin.Handler
}
2018-02-25 08:52:52 +00:00
// ServeDNS implements the plugin.Handler interface. This method gets called when example is used
// in a Server.
func (e Example) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
2018-02-25 08:52:52 +00:00
// This function could be simpler. I.e. just fmt.Println("example") here, but we want to show
// a slightly more complex example as to make this more interesting.
// Here we wrap the dns.ResponseWriter in a new ResponseWriter and call the next plugin, when the
// answer comes back, it will print "example".
// Wrap.
pw := NewResponsePrinter(w)
2018-02-25 08:52:52 +00:00
// Call next plugin (if any).
2017-09-15 20:29:47 +00:00
return plugin.NextOrFailure(e.Name(), e.Next, ctx, pw, r)
}
// Name implements the Handler interface.
func (e Example) Name() string { return "example" }
2018-02-25 08:52:52 +00:00
// ResponsePrinter wrap a dns.ResponseWriter and will write example to standard output when
// WriteMsg is called.
type ResponsePrinter struct {
dns.ResponseWriter
}
2018-02-25 08:52:52 +00:00
// NewResponsePrinter returns ResponseWriter.
func NewResponsePrinter(w dns.ResponseWriter) *ResponsePrinter {
return &ResponsePrinter{ResponseWriter: w}
}
2018-02-25 08:52:52 +00:00
// WriteMsg calls the underlying ResponseWriter's WriteMsg method and prints "example" to standard
// output.
func (r *ResponsePrinter) WriteMsg(res *dns.Msg) error {
2018-02-25 08:52:52 +00:00
fmt.Fprintln(out, ex)
return r.ResponseWriter.WriteMsg(res)
}
2018-02-25 08:52:52 +00:00
// Make out a reference to os.Stdout so we can easily overwrite it for testing.
var out io.Writer = os.Stdout
2018-02-25 08:52:52 +00:00
// What we will print.
const ex = "example"