...
1 package dns
2
3 import (
4 "sync"
5 )
6
7
8
9
10
11
12
13
14
15
16
17
18 type ServeMux struct {
19 z map[string]Handler
20 m sync.RWMutex
21 }
22
23
24 func NewServeMux() *ServeMux {
25 return new(ServeMux)
26 }
27
28
29 var DefaultServeMux = NewServeMux()
30
31 func (mux *ServeMux) match(q string, t uint16) Handler {
32 mux.m.RLock()
33 defer mux.m.RUnlock()
34 if mux.z == nil {
35 return nil
36 }
37
38 q = CanonicalName(q)
39
40 var handler Handler
41 for off, end := 0, false; !end; off, end = NextLabel(q, off) {
42 if h, ok := mux.z[q[off:]]; ok {
43 if t != TypeDS {
44 return h
45 }
46
47 handler = h
48 }
49 }
50
51
52 if h, ok := mux.z["."]; ok {
53 return h
54 }
55
56 return handler
57 }
58
59
60 func (mux *ServeMux) Handle(pattern string, handler Handler) {
61 if pattern == "" {
62 panic("dns: invalid pattern " + pattern)
63 }
64 mux.m.Lock()
65 if mux.z == nil {
66 mux.z = make(map[string]Handler)
67 }
68 mux.z[CanonicalName(pattern)] = handler
69 mux.m.Unlock()
70 }
71
72
73 func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Msg)) {
74 mux.Handle(pattern, HandlerFunc(handler))
75 }
76
77
78 func (mux *ServeMux) HandleRemove(pattern string) {
79 if pattern == "" {
80 panic("dns: invalid pattern " + pattern)
81 }
82 mux.m.Lock()
83 delete(mux.z, CanonicalName(pattern))
84 mux.m.Unlock()
85 }
86
87
88
89
90
91
92
93
94
95
96 func (mux *ServeMux) ServeDNS(w ResponseWriter, req *Msg) {
97 var h Handler
98 if len(req.Question) >= 1 {
99 h = mux.match(req.Question[0].Name, req.Question[0].Qtype)
100 }
101
102 if h != nil {
103 h.ServeDNS(w, req)
104 } else {
105 handleRefused(w, req)
106 }
107 }
108
109
110
111
112 func Handle(pattern string, handler Handler) { DefaultServeMux.Handle(pattern, handler) }
113
114
115
116 func HandleRemove(pattern string) { DefaultServeMux.HandleRemove(pattern) }
117
118
119
120 func HandleFunc(pattern string, handler func(ResponseWriter, *Msg)) {
121 DefaultServeMux.HandleFunc(pattern, handler)
122 }
123
View as plain text