diff options
| -rw-r--r-- | hosts/hosts.go | 18 |
1 files changed, 18 insertions, 0 deletions
diff --git a/hosts/hosts.go b/hosts/hosts.go index 0412e4a..e56451c 100644 --- a/hosts/hosts.go +++ b/hosts/hosts.go @@ -41,6 +41,20 @@ func Add(host Host) error { return Store(hosts) } +// Lookup searches for a host in the known hosts file. +// If it is not found, a non-nil error is returned. +func Lookup(hostname netip.Addr) (Host, error) { + hosts, err := Load() + if err != nil { + return Host{}, err + } + i, ok := slices.BinarySearchFunc(hosts, hostname, cmpHostAddr) + if ok { + return hosts[i], nil + } + return Host{}, fmt.Errorf("no such host: %s", hostname) +} + // Load loads the set of known hosts from disc. // The returned list is sorted. func Load() ([]Host, error) { @@ -121,6 +135,10 @@ func cmpHost(a, b Host) int { return a.SigPublicKey.Compare(b.SigPublicKey) } +func cmpHostAddr(host Host, addr netip.Addr) int { + return host.Addr.Compare(addr) +} + func (h Host) String() string { return fmt.Sprintf("%s %x %x", h.Addr, h.BoxPublicKey, h.SigPublicKey) } |