Debian Codegraph @

cmd/atomdns/handlers/handler.go

raw
1 package handlers
2
3 import (
4 "context"
5 "slices"
6
7 "codeberg.org/miekg/dns"
8 "codeberg.org/miekg/dns/cmd/atomdns/internal/dnsserver"
9 )
10
11 //go:generate go run string_generate.go
12 //go:generate go run err_generate.go
13
14 // A Handler is a dns.HandlerFunc that has a handler func (the next when to call in the middleware stack) as
15 // input and returns a handle func which is the handler itself.
16 //
17 // There are several types of handlers that you can implement, handlers that:
18 //
19 // - observe, things like logging and metrics.
20 // - modify the [dns.Msg] and then call the next handler, they can enrich the context or modify the message.
21 // - call the next handler, wait for it to return and modify the [dns.Msg], think of setting TSIG or a DNS
22 // cookie.
23 //
24 // If a Handler implements HandleFunc that returns a nil, instead of a proper dns.HandlerFunc, it is
25 // considered a noop handler and not added to the handlers chain. For the Handler to be useful it should
26 // implement [Setupper], because without it would be a comletely useless handler.
27 type Handler interface {
28 // HandlerFunc run the handler's code.
29 HandlerFunc(next dns.HandlerFunc) dns.HandlerFunc
30
31 // Err returns a error with some extra data that identifies the handler in erroring. This method can be
32 // created with go generate, once some scaffolding is in place.
33 Err(error) error
34 }
35
36 // Setupper holds a single method that is called when this Handler has configuration that needs to be parsed
37 // from the config file. The co's Global holds the server's global config.
38 type Setupper interface {
39 Setup(co *dnsserver.Controller) error
40 }
41
42 // Teardowner holds a method that is called when the handler block is processed and the handler needs to reset
43 // some state.
44 type Teardowner interface {
45 Teardown(co *dnsserver.Controller) error
46 }
47
48 // Compile takes the Handlers hs and creates a wrapped handle func.
49 func Compile(hs []Handler) dns.HandlerFunc {
50 if len(hs) < 1 {
51 panic("atomdns: need something compile")
52 }
53
54 wrapped := func(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) {}
55 for _, h := range slices.Backward(hs) { // loop in reverse to preserve middleware order
56 wrapped = h.HandlerFunc(wrapped)
57 }
58 return wrapped
59 }