feat(dns): default serve ports from configured values when unset

Co-Authored-By: Virgil <virgil@lethean.io>
This commit is contained in:
Virgil 2026-04-03 23:32:52 +00:00
parent 987ebec1cd
commit 9b077efe4e
2 changed files with 33 additions and 2 deletions

View file

@ -171,6 +171,9 @@ func (service *Service) Serve(bind string, port int) (*DNSServer, error) {
if bind == "" {
bind = "127.0.0.1"
}
if port <= 0 {
port = service.ResolveDNSPort()
}
addr := net.JoinHostPort(bind, strconv.Itoa(port))
udpListener, err := net.ListenPacket("udp", addr)
@ -213,8 +216,8 @@ func (service *Service) Serve(bind string, port int) (*DNSServer, error) {
// defer func() { _ = runtime.Close() }()
// fmt.Println("dns:", runtime.DNSAddress(), "health:", runtime.HealthAddress())
func (service *Service) ServeAll(bind string, dnsPort int, httpPort int) (*ServiceRuntime, error) {
if dnsPort == 0 {
dnsPort = service.dnsPort
if dnsPort <= 0 {
dnsPort = service.resolveServePort()
}
if httpPort <= 0 {
httpPort = service.resolveHTTPPort()

View file

@ -638,6 +638,34 @@ func TestServiceServeConfiguredUsesPortsFromServiceOptions(t *testing.T) {
}
}
func TestServiceServeDefaultsPortWhenZero(t *testing.T) {
const configuredDNSPort = 5353
service := NewService(ServiceOptions{
DNSPort: configuredDNSPort,
Records: map[string]NameRecords{
"gateway.charon.lthn": {
A: []string{"10.10.10.10"},
},
},
})
server, err := service.Serve("127.0.0.1", 0)
if err != nil {
t.Fatalf("expected Serve to default DNS port: %v", err)
}
defer func() {
_ = server.Close()
}()
_, port, err := net.SplitHostPort(server.DNSAddress())
if err != nil {
t.Fatalf("expected DNS address to parse: %v", err)
}
if port != strconv.Itoa(configuredDNSPort) {
t.Fatalf("expected zero port to default to configured service DNS port %d, got %s", configuredDNSPort, port)
}
}
func TestServiceDiscoverReplacesRecordsFromDiscoverer(t *testing.T) {
records := []map[string]NameRecords{
{