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 (

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 {



The LookupCNAME function is described as follows:

func 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.

Related Posts

  • Embedding file with Go 1.16
  • Truncating a Unix timestamp to the hour using Go
  • Parsing a key pair from a PEM file in Go
  • Gotcha with defer in Go
  • Pretty-print JSON with Go