CHAPTER 3Writing HTTP Clients

In this chapter, you are going to learn about the building blocks of writing testable HTTP clients. You will become familiar with key concepts—sending and receiving data, serialization and deserialization, and working with binary data. Once you grasp these concepts, you will be able to write stand-alone client applications and a Go client for your service's HTTP API and make HTTP API calls as part of a service-to-service communication architecture. As you progress through the chapter, you will be enhancing the mync http sub-command by implementing these features and techniques. Let's get started!

Downloading Data

You are likely familiar with command-line programs such as wget and curl, which are suitable for downloading data over HTTP. Let's see how you can write one using the functions and types defined in the net/http package. First, let's write a function that will accept an HTTP URL as a parameter and return a byte slice containing the contents at the URL and an error value:

func fetchRemoteResource(url string) ([]byte, error) {
        r, err := http.Get(url)
        if err != nil {
                return nil, err
        }
        defer r.Body.Close()
        return io.ReadAll(r.Body)
        
}

The Get() function defined in the net/http package makes a HTTP GET request to the specified url and returns an object of type Response and an error value. The Response object, r, has several fields, one of which is the Body field (of type io.ReadCloser ), which contains the response body. We use a

Get Practical Go now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.