Add middleware.NextOrFailure (#462)

This checks if the next middleware to be called is nil, and if so returns
ServerFailure and an error. This makes the next calling more robust and
saves some lines of code.

Also prefix the error with the name of the middleware to aid in
debugging.
This commit is contained in:
Miek Gieben 2016-12-20 18:58:05 +00:00 committed by GitHub
parent 451a0bd529
commit c4ab98c6e3
23 changed files with 51 additions and 67 deletions

View file

@ -2,6 +2,7 @@
package middleware
import (
"errors"
"fmt"
"github.com/miekg/dns"
@ -65,5 +66,15 @@ func (f HandlerFunc) Name() string { return "handlerfunc" }
// Error returns err with 'middleware/name: ' prefixed to it.
func Error(name string, err error) error { return fmt.Errorf("%s/%s: %s", "middleware", name, err) }
// NextOrFailure calls next.ServeDNS when next is not nill, otherwise it will return, a ServerFailure
// and a nil error.
func NextOrFailure(name string, next Handler, ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
if next != nil {
return next.ServeDNS(ctx, w, r)
}
return dns.RcodeServerFailure, Error(name, errors.New("no next middleware found"))
}
// Namespace is the namespace used for the metrics.
const Namespace = "coredns"