mirror of
https://github.com/coredns/coredns.git
synced 2025-11-02 18:23:25 -05:00
msg.Service: add HostType() method (#627)
This method parses the Host field in the service. It returns 1 or 3 things 1) it is a host 2) an IPv4 address or an 3) IPv6 address. This simplifies some code a bit and allows for 1 way of parsing the Host field. This *only* parse the Host field, Mail and/or Text values should be checked separately. We reuse the dns.TypeXXX values for this as to not invent anything new.
This commit is contained in:
33
middleware/etcd/msg/type.go
Normal file
33
middleware/etcd/msg/type.go
Normal file
@@ -0,0 +1,33 @@
|
||||
package msg
|
||||
|
||||
import (
|
||||
"net"
|
||||
|
||||
"github.com/miekg/dns"
|
||||
)
|
||||
|
||||
// HostType returns the DNS type of what is encoded in the Service Host field. We're reusing
|
||||
// dns.TypeXXX to not reinvent a new set of identifiers.
|
||||
//
|
||||
// dns.TypeA: the service's Host field contains an A record.
|
||||
// dns.TypeAAAA: the service's Host field contains an AAAA record.
|
||||
// dns.TypeANY: the service's Host field contains a name.
|
||||
//
|
||||
// Note that a service can double/triple as a TXT record or MX record.
|
||||
func (s *Service) HostType() (what uint16, normalized net.IP) {
|
||||
|
||||
ip := net.ParseIP(s.Host)
|
||||
|
||||
switch {
|
||||
case ip == nil:
|
||||
return dns.TypeANY, nil
|
||||
|
||||
case ip.To4() != nil:
|
||||
return dns.TypeA, ip.To4()
|
||||
|
||||
case ip.To4() == nil:
|
||||
return dns.TypeAAAA, ip.To16()
|
||||
}
|
||||
// This should never be reached.
|
||||
return dns.TypeNone, nil
|
||||
}
|
||||
31
middleware/etcd/msg/type_test.go
Normal file
31
middleware/etcd/msg/type_test.go
Normal file
@@ -0,0 +1,31 @@
|
||||
package msg
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/miekg/dns"
|
||||
)
|
||||
|
||||
func TestType(t *testing.T) {
|
||||
tests := []struct {
|
||||
serv Service
|
||||
expectedType uint16
|
||||
}{
|
||||
{Service{Host: "example.org"}, dns.TypeANY},
|
||||
{Service{Host: "127.0.0.1"}, dns.TypeA},
|
||||
{Service{Host: "2000::3"}, dns.TypeAAAA},
|
||||
{Service{Host: "2000..3"}, dns.TypeANY},
|
||||
{Service{Host: "127.0.0.257"}, dns.TypeANY},
|
||||
{Service{Host: "127.0.0.252", Mail: true}, dns.TypeA},
|
||||
{Service{Host: "127.0.0.252", Mail: true, Text: "a"}, dns.TypeA},
|
||||
{Service{Host: "127.0.0.254", Mail: false, Text: "a"}, dns.TypeA},
|
||||
}
|
||||
|
||||
for i, tc := range tests {
|
||||
what, _ := tc.serv.HostType()
|
||||
if what != tc.expectedType {
|
||||
t.Errorf("Test %d: Expected what %v, but got %v", i, tc.expectedType, what)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user