micro/resolver/dns/dns.go

79 lines
1.5 KiB
Go
Raw Normal View History

2019-10-08 09:04:13 +01:00
// Package dns resolves names to dns records
2019-07-28 12:14:40 +01:00
package dns
import (
"context"
2019-07-28 12:14:40 +01:00
"net"
"github.com/miekg/dns"
"github.com/unistack-org/micro/v3/resolver"
2019-07-28 12:14:40 +01:00
)
// Resolver is a DNS network resolve
type Resolver struct {
// The resolver address to use
Address string
}
2019-07-28 12:14:40 +01:00
// Resolve assumes ID is a domain name e.g micro.mu
2019-07-28 20:00:09 +01:00
func (r *Resolver) Resolve(name string) ([]*resolver.Record, error) {
2019-10-08 09:04:13 +01:00
host, port, err := net.SplitHostPort(name)
if err != nil {
host = name
port = "8085"
}
2019-10-13 18:36:22 +01:00
if len(host) == 0 {
host = "localhost"
}
if len(r.Address) == 0 {
r.Address = "1.0.0.1:53"
}
2019-12-07 23:28:39 +00:00
//nolint:prealloc
var records []*resolver.Record
// parsed an actual ip
if v := net.ParseIP(host); v != nil {
records = append(records, &resolver.Record{
Address: net.JoinHostPort(host, port),
})
return records, nil
}
m := new(dns.Msg)
m.SetQuestion(dns.Fqdn(host), dns.TypeA)
rec, err := dns.ExchangeContext(context.Background(), m, r.Address)
2019-07-28 12:14:40 +01:00
if err != nil {
return nil, err
}
2019-10-08 09:04:13 +01:00
for _, answer := range rec.Answer {
h := answer.Header()
// check record type matches
if h.Rrtype != dns.TypeA {
continue
}
arec, _ := answer.(*dns.A)
addr := arec.A.String()
2019-10-08 09:04:13 +01:00
// join resolved record with port
address := net.JoinHostPort(addr, port)
// append to record set
2019-07-28 12:14:40 +01:00
records = append(records, &resolver.Record{
Address: address,
})
}
2019-10-08 09:04:13 +01:00
2019-12-07 23:28:39 +00:00
// no records returned so just best effort it
if len(records) == 0 {
records = append(records, &resolver.Record{
Address: net.JoinHostPort(host, port),
})
}
2019-07-28 12:14:40 +01:00
return records, nil
}