Setting the Timeout Period on the Client Side
Let’s learn how to set the timeout period on the client side.
We'll cover the following...
We'll cover the following...
This lesson presents a technique for timing out network connections that take too long to finish on the client side. So, if the client does not receive a response from the server in the desired time, it closes the connection.
Coding example
The timeoutClient.go
source file, without the import
block, illustrates the technique.
Press + to interact
package mainvar myUrl stringvar delay int = 5var wg sync.WaitGrouptype myData struct {r *http.Responseerr error}
In the code above, we define global variables and a structure that are going to be used in the rest of the program.
Press + to interact
func connect(c context.Context) error {defer wg.Done()data := make(chan myData, 1)tr := &http.Transport{}httpClient := &http.Client{Transport: tr}req, _ := http.NewRequest("GET", myUrl, nil)go func() {response, err := httpClient.Do(req)if err != nil {fmt.Println(err)data <- myData{nil, err}return} else {pack := myData{response, err}data <- pack}}()select {case <-c.Done():tr.CancelRequest(req)<-datafmt.Println("The request was canceled!")return c.Err()case ok := <-data:err := ok.errresp := ok.rif err != nil {fmt.Println("Error select:", err)return err}defer resp.Body.Close()realHTTPData, err := io.ReadAll(resp.Body)if err != nil {fmt.Println("Error select:", err)return err}// Although fmt.Printf() is used here, server processes// use the log.Printf() function instead.fmt.Printf("Server Response: %s\n", realHTTPData)}return nil}
...