-
Notifications
You must be signed in to change notification settings - Fork 4
/
server.go
63 lines (54 loc) · 1.4 KB
/
server.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// Copyright (c) 2016 struktur AG.
// Use of this source code is governed by the MIT License that can be
// that can be found in the LICENSE file.
package main
import (
"github.com/miekg/dns"
"log"
"os"
"os/signal"
"strconv"
"syscall"
)
// A Server represents a DNS server.
type Server struct {
ip string
port int
}
// NewServer returns a Server created with IP and port.
func NewServer(ip string, port int) (*Server, error) {
return &Server{ip, port}, nil
}
// Addr returns the listen address (IP:port) as string.
func (s *Server) Addr() string {
return s.ip + ":" + strconv.Itoa(s.port)
}
// Serve starts the TCP and UDP listeners and blocks until
// syscall.SIGINT or syscall.SIGTERM is received.
func (s *Server) Serve(name string) (err error) {
log.Printf("creating DNS service for %s", name)
handler := NewHandler(name, s.ip)
dns.HandleFunc(".", handler.handleQuery)
tcpServer := &dns.Server{
Addr: s.Addr(),
Net: "tcp",
}
udpServer := &dns.Server{
Addr: s.Addr(),
Net: "udp",
UDPSize: 65535,
}
go s.start(udpServer)
go s.start(tcpServer)
ch := make(chan os.Signal)
signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
log.Println(<-ch)
return
}
func (s *Server) start(ds *dns.Server) {
log.Printf("start %s listener on %s\n", ds.Net, s.Addr())
err := ds.ListenAndServe()
if err != nil {
log.Printf("start %s listener on %s failed:%s\n", ds.Net, s.Addr(), err.Error())
}
}