#development #golang #pattern

Let's learn today how to get the details of a DNS CNAME record using Go. Go provides us with the net package to do exactly this. The function we need is called LookupCNAME.

 1package main
 2
 3import (
 4    "errors"
 5    "log"
 6    "net"
 7    "strings"
 8)
 9
10func lookupCNAME(host string) (string, error) {
11
12    if host == "" {
13        return "", errors.New("Empty host name")
14    }
15
16    cname, err := net.LookupCNAME(host)
17    if err != nil {
18        return "", errors.New("Domain name doesn't exist")
19    }
20
21    cname = strings.TrimSuffix(cname, ".")
22    host = strings.TrimSuffix(host, ".")
23
24    if cname == "" || cname == host {
25        return "", errors.New("Domain name is not a CNAME")
26    }
27
28    return cname, nil
29
30}
31
32func main() {
33
34    result, err := lookupCNAME("api.yellowduck.be")
35    if err != nil {
36        log.Fatal(err)
37    }
38
39    log.Println(result)
40
41}

The LookupCNAME function is described as follows:

1func LookupCNAME(host string) (cname string, err error)

LookupCNAME returns the canonical name for the given host. Callers that do not care about the canonical name can call LookupHost or LookupIP directly; both take care of resolving the canonical name as part of the lookup.

A canonical name is the final name after following zero or more CNAME records. LookupCNAME does not return an error if host does not contain DNS "CNAME" records, as long as host resolves to address records.