Search⌘ K

Using http.NewRequest() to Improve the Client

Explore how to improve HTTP client requests in Go by using http.NewRequest instead of http.Get. Understand parsing URLs, sending requests with http.Client, inspecting response status, headers, and content length, and techniques for debugging HTTP interactions.

We'll cover the following...

In this lesson, we will learn how to read a URL without using the http.Get() function with more options. However, the extra flexibility comes at a cost because we must write more code.

Coding example

The code of wwwClient.go, without the import block, is as follows:

Go (1.19.0)
package main
import (
"fmt"
"net/http"
"net/http/httputil"
"net/url"
"os"
"path/filepath"
"strings"
"time"
)
func main() {
if len(os.Args) != 2 {
fmt.Printf("Usage: %s URL\n", filepath.Base(os.Args[0]))
return
}

Although using filepath.Base() is not necessary, it makes our output more professional.

Go (1.19.0)
URL, err := url.Parse(os.Args[1])
if err != nil {
fmt.Println("Error in parsing:", err)
return
}

The url.Parse() function parses a string into a URL structure. This means that if the given argument is not a valid URL, ...