Add server support for multiple listen addresses

This commit is contained in:
gdm85 committed 2018-04-15 19:57:17 +02:00
1 parent ce656ac3f7
commit 1abba72898
3 files changed
+27 -7

No files matched your search

+4 -3
View File
@@ -30,7 +30,7 @@ import (
) )
type config struct { type config struct {
Listen string `toml:"listen"` Listen []string `toml:"listen"`
Cert string `toml:"cert"` Cert string `toml:"cert"`
Key string `toml:"key"` Key string `toml:"key"`
Path string `toml:"path"` Path string `toml:"path"`
@@ -51,9 +51,10 @@ func loadConfig(path string) (*config, error) {
return nil, &configError{fmt.Sprintf("unknown option %q", key.String())} return nil, &configError{fmt.Sprintf("unknown option %q", key.String())}
} }
if conf.Listen == "" { if len(conf.Listen) == 0 {
conf.Listen = "127.0.0.1:8053" conf.Listen = []string{"127.0.0.1:8053"}
} }
if conf.Path == "" { if conf.Path == "" {
conf.Path = "/dns-query" conf.Path = "/dns-query"
} }
+3 -1
View File
@@ -1,5 +1,7 @@
# HTTP listen port # HTTP listen port
listen = "127.0.0.1:8053" listen = [
"127.0.0.1:8053"
]
# TLS certification file # TLS certification file
cert = "" cert = ""
+20 -3
View File
@@ -75,10 +75,27 @@ func (s *Server) Start() error {
if s.conf.Verbose { if s.conf.Verbose {
servemux = handlers.CombinedLoggingHandler(os.Stdout, servemux) servemux = handlers.CombinedLoggingHandler(os.Stdout, servemux)
} }
if s.conf.Cert != "" || s.conf.Key != "" { listeners := make(chan error, len(s.conf.Listen))
return http.ListenAndServeTLS(s.conf.Listen, s.conf.Cert, s.conf.Key, servemux) for _, addr := range s.conf.Listen {
if s.conf.Cert != "" || s.conf.Key != "" {
go func() {
listeners <- http.ListenAndServeTLS(addr, s.conf.Cert, s.conf.Key, servemux)
}()
continue
}
go func() {
listeners <- http.ListenAndServe(addr, servemux)
}()
} }
return http.ListenAndServe(s.conf.Listen, servemux) // wait for all handlers
for i := 0; i < cap(listeners); i++ {
err := <-listeners
if err != nil {
return err
}
}
close(listeners)
return nil
} }
func (s *Server) handlerFunc(w http.ResponseWriter, r *http.Request) { func (s *Server) handlerFunc(w http.ResponseWriter, r *http.Request) {