We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
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
.
package main
import (
"errors"
"log"
"net"
"strings"
)
func lookupCNAME(host string) (string, error) {
if host == "" {
return "", errors.New("Empty host name")
}
cname, err := net.LookupCNAME(host)
if err != nil {
return "", errors.New("Domain name doesn't exist")
}
cname = strings.TrimSuffix(cname, ".")
host = strings.TrimSuffix(host, ".")
if cname == "" || cname == host {
return "", errors.New("Domain name is not a CNAME")
}
return cname, nil
}
func main() {
result, err := lookupCNAME("api.yellowduck.be")
if err != nil {
log.Fatal(err)
}
log.Println(result)
}
The LookupCNAME
function is described as follows:
func LookupCNAME(host string) (cname string, err error)
LookupCNAME
returns the canonical name for the givenhost
. Callers that do not care about the canonical name can callLookupHost
orLookupIP
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.
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.