How to do it...

These steps cover writing and running your application:

  1. From your Terminal or console application, create a new directory called ~/projects/go-programming-cookbook/chapter5/dns and navigate to this directory.
  2. Run the following command:
$ go mod init github.com/PacktPublishing/Go-Programming-Cookbook-Second-Edition/chapter5/dns

You should see a file called go.mod that contains the following:

module github.com/PacktPublishing/Go-Programming-Cookbook-Second-Edition/chapter5/dns
  1. Copy tests from ~/projects/go-programming-cookbook-original/chapter5/dns or use this as an exercise to write some of your own code!
  2. Create a dns.go file with the following content:
package dns

import (
"fmt"
"net"

"github.com/pkg/errors"
)

// Lookup holds the DNS information we care about
type Lookup struct {
cname string
hosts []string
}

// We can use this to print the lookup object
func (d *Lookup) String() string {
result := ""
for _, host := range d.hosts {
result += fmt.Sprintf("%s IN A %s ", d.cname, host)
}
return result
}

// LookupAddress returns a DNSLookup consisting of a cname and host
// for a given address
func LookupAddress(address string) (*Lookup, error) {
cname, err := net.LookupCNAME(address)
if err != nil {
return nil, errors.Wrap(err, "error looking up CNAME")
}
hosts, err := net.LookupHost(address)
if err != nil {
return nil, errors.Wrap(err, "error looking up HOST")
}

return &Lookup{cname: cname, hosts: hosts}, nil
}
  1. Create a new directory named example and navigate to it.
  2. Create a main.go file with the following content:
package main

import (
"fmt"
"log"
"os"

"github.com/PacktPublishing/Go-Programming-Cookbook-Second-Edition/chapter5/dns"
)

func main() {
if len(os.Args) < 2 {
fmt.Printf("Usage: %s <address> ", os.Args[0])
os.Exit(1)
}
address := os.Args[1]
lookup, err := dns.LookupAddress(address)
if err != nil {
log.Panicf("failed to lookup: %s", err.Error())
}
fmt.Println(lookup)
}
  1. Run the go run main.go golang.org command.
  2. You may also run the following:
$ go build
$ ./example golang.org

You should see the following output:

$ go run main.go golang.org
golang.org. IN A 172.217.5.17
golang.org. IN A 2607:f8b0:4009:809::2011
  1. The go.mod file may be updated and the go.sum file should now be present in the top-level recipe directory.
  2. If you copied or wrote your own tests, go up one directory and run go test. Ensure that all the tests pass.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.190.159.10