ip-ddns/adapter/dnsresolver/resolver.go

46 lines
813 B
Go

package dnsresolver
import (
"errors"
"net"
"github.com/miekg/dns"
)
type dnsResolver struct {
resolver dns.Client
}
// New creates new DomainNameResolver.
func New() DomainNameResolver {
return &dnsResolver{
resolver: dns.Client{},
}
}
// ResolveA implements DomainNameResolver.
func (r *dnsResolver) ResolveA(domain, nameserver string) ([]net.IP, error) {
msg := &dns.Msg{}
msg.SetQuestion(domain+".", dns.TypeA)
answer, _, err := r.resolver.Exchange(msg, nameserver+":53")
if err != nil {
return nil, err
}
if len(answer.Answer) == 0 {
return nil, errors.New("empty answer")
}
result := make([]net.IP, len(answer.Answer))
for idx, rr := range answer.Answer {
record := rr.(*dns.A)
result[idx] = record.A
}
return result, nil
}
var (
_ DomainNameResolver = &dnsResolver{}
)