package main import ( "fmt" "net/http" "time" ) func main() { client := &http.Client{ Timeout: time.Second * 5, } // Make a GET request to the Google homepage with a timeout of 5 seconds resp, err := client.Get("http://www.google.com") if err != nil { fmt.Println("Error:", err) return } defer resp.Body.Close() // Print the status code and response body fmt.Println("Status Code:", resp.StatusCode) }
package main import ( "fmt" "io/ioutil" "net/http" "time" ) func main() { client := &http.Client{ Timeout: time.Second * 10, } // Make a POST request to an API with JSON data and a 10-second timeout req, _ := http.NewRequest("POST", "https://api.example.com/user", nil) req.Header.Set("Content-Type", "application/json") resp, err := client.Do(req) if err != nil { fmt.Printf("Error: %s\n", err.Error()) return } defer resp.Body.Close() // Read the response body body, _ := ioutil.ReadAll(resp.Body) // Print the response status code and body fmt.Printf("Status Code: %d\n", resp.StatusCode) fmt.Printf("Response Body: %s\n", body) }In this example, we created an HTTP client with a timeout of 10 seconds and made a POST request to an API with JSON data. If the request takes longer than 10 seconds to complete, the client will return an error. The package library used in this example is also `net/http`.