Search⌘ K

Using http.NewRequest() to Improve the Client

Let’s enhance the HTTP web client by using the http.NewRequest() function.

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