From c1b5b0c2c53dd6f26859087ff88c51a7394fabdd Mon Sep 17 00:00:00 2001 From: Starainrt Date: Wed, 10 Apr 2024 15:52:57 +0800 Subject: [PATCH] update host file --- hosts/hosts.go | 17 +++++++++-------- hosts/hosts_test.go | 17 +++++++++++++++++ hosts/test_hosts.txt | 1 + 3 files changed, 27 insertions(+), 8 deletions(-) diff --git a/hosts/hosts.go b/hosts/hosts.go index 0eaf37e..411d56e 100644 --- a/hosts/hosts.go +++ b/hosts/hosts.go @@ -580,19 +580,20 @@ func (h *Host) SetIPHosts(ip string, hosts ...string) error { } func (h *Host) SetHostIPs(host string, ips ...string) error { - info := h.ListByHost(host) - if len(info) == 0 { - return h.AddHosts(host, ips...) - } else if len(info) == 1 { - info[0].ip = ips[0] - info[0].comment = "" - return nil + if len(ips) == 0 { + return fmt.Errorf("no ip address") } err := h.RemoveHosts(host) if err != nil { return err } - return h.AddHosts(ips[0], host) + for _, ip := range ips { + err := h.AddHosts(ip, host) + if err != nil { + return err + } + } + return nil } func (h *Host) addHosts(comment string, ip string, hosts ...string) error { diff --git a/hosts/hosts_test.go b/hosts/hosts_test.go index 8ae2394..d356886 100644 --- a/hosts/hosts_test.go +++ b/hosts/hosts_test.go @@ -116,6 +116,23 @@ func Test_Hosts(t *testing.T) { } } + err = h.SetHostIPs("ssh.b612.me", "9.9.9.9") + if err != nil { + t.Error(err) + } + + data = h.ListIPsByHost("ssh.b612.me") + if len(data) == 0 { + t.Error("Expected 1 got ", data) + } else { + t.Log(data) + } + + err = h.SetIPHosts("10.10.10.10", "ssh.b612.me", "ssr.b612.me") + if len(data) == 0 { + t.Error("Expected 1 got ", data) + } + err = h.SaveAs("./test_hosts_02.txt") if err != nil { t.Error(err) diff --git a/hosts/test_hosts.txt b/hosts/test_hosts.txt index 718a539..0d22a47 100644 --- a/hosts/test_hosts.txt +++ b/hosts/test_hosts.txt @@ -8,6 +8,7 @@ #special IPv6 addre 127.0.0.1 localhost 127.0.0.1 b612 +8.8.8.8 ssh.b612.me #special IPv6 addresses ::1 localhost ipv6-localhost ipv6-loopback fe00::0 ipv6-localnet