cmd/cli: use resolvconffile lib for parsing

This commit is contained in:
Cuong Manh Le
2025-06-17 19:33:45 +07:00
committed by Cuong Manh Le
parent b9b9cfcade
commit 64632fa640
3 changed files with 57 additions and 26 deletions
+3 -21
View File
@@ -3,36 +3,18 @@ package cli
import (
"net"
"net/netip"
"os"
"path/filepath"
"strings"
"time"
"github.com/fsnotify/fsnotify"
"github.com/Control-D-Inc/ctrld/internal/resolvconffile"
)
// parseResolvConfNameservers reads the resolv.conf file and returns the nameservers found.
// Returns nil if no nameservers are found.
func (p *prog) parseResolvConfNameservers(path string) ([]string, error) {
content, err := os.ReadFile(path)
if err != nil {
return nil, err
}
// Parse the file for "nameserver" lines
var currentNS []string
lines := strings.Split(string(content), "\n")
for _, line := range lines {
trimmed := strings.TrimSpace(line)
if strings.HasPrefix(trimmed, "nameserver") {
parts := strings.Fields(trimmed)
if len(parts) >= 2 {
currentNS = append(currentNS, parts[1])
}
}
}
return currentNS, nil
return resolvconffile.NameserversFromFile(path)
}
// watchResolvConf watches any changes to /etc/resolv.conf file,
+46
View File
@@ -0,0 +1,46 @@
//go:build unix
package cli
import (
"os"
"slices"
"strings"
"testing"
"github.com/Control-D-Inc/ctrld/internal/dns/resolvconffile"
)
func oldParseResolvConfNameservers(path string) ([]string, error) {
content, err := os.ReadFile(path)
if err != nil {
return nil, err
}
// Parse the file for "nameserver" lines
var currentNS []string
lines := strings.Split(string(content), "\n")
for _, line := range lines {
trimmed := strings.TrimSpace(line)
if strings.HasPrefix(trimmed, "nameserver") {
parts := strings.Fields(trimmed)
if len(parts) >= 2 {
currentNS = append(currentNS, parts[1])
}
}
}
return currentNS, nil
}
func Test_prog_parseResolvConfNameservers(t *testing.T) {
oldNss, _ := oldParseResolvConfNameservers(resolvconffile.Path)
p := &prog{}
nss, _ := p.parseResolvConfNameservers(resolvconffile.Path)
slices.Sort(oldNss)
slices.Sort(nss)
if !slices.Equal(oldNss, nss) {
t.Errorf("result mismatched, old: %v, new: %v", oldNss, nss)
}
t.Logf("result: %v", nss)
}