godns/server.go

65 lines
1009 B
Go

package main
import (
"github.com/spf13/viper"
"meow.tf/joker/godns/log"
"strings"
"time"
"github.com/miekg/dns"
)
type Server struct {
host string
port int
rTimeout time.Duration
wTimeout time.Duration
}
func (s *Server) Run() {
handler := NewHandler()
nets := viper.GetStringSlice("networks")
var addr string
var split []string
// Defaults: tcp, udp
for _, net := range nets {
split = strings.Split(net, ":")
net = split[0]
addr = s.host
if len(split) == 1 {
addr += ":53"
} else {
addr += ":" + split[1]
}
h := dns.NewServeMux()
h.HandleFunc(".", handler.Bind(net))
server := &dns.Server{
Addr: addr,
Net: net,
Handler: h,
ReadTimeout: s.rTimeout,
WriteTimeout: s.wTimeout,
}
go s.start(server)
}
}
func (s *Server) start(ds *dns.Server) {
log.Info("Start %s listener on %s", ds.Net, ds.Addr)
err := ds.ListenAndServe()
if err != nil {
log.Error("Start %s listener on %s failed:%s", ds.Net, ds.Addr, err.Error())
}
}