NewRequestWithContext example to send get request
- User
NewRequestWithContext example to send get request
Assistant
package main import ( "context" "fmt" "log" "net/http" "time" ) // NewRequestWithContext is a helper function to create a new HTTP GET request // with a context. It handles potential errors and provides a clean way to // execute the request. func NewRequestWithContext(ctx context.Context, url string) (*http.Response, error) { // Create a new HTTP client. You can configure this with timeouts, // proxies, etc. client := &http.Client{} // Create a new request. req, err := http.NewRequest("GET", url, nil) if err != nil { return nil, fmt.Errorf("failed to create request: %w", err) } // Set the context on the request. This allows you to cancel the request // if the context is cancelled. req.Context = ctx // Send the request. This will block until the request is complete. resp, err := client.Do(req) if err != nil { return nil, fmt.Errorf("failed to send request: %w", err) } defer resp.Body.Close() // Ensure the response body is closed return resp, nil } func main() { // Create a context. This context will be used to cancel the request // if it takes too long. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() // Ensure the context is cancelled when the function exits // The URL to send the request to. url := "https://example.com" // Send the request. resp, err := NewRequestWithContext(ctx, url) if err != nil { log.Fatalf("Error sending request: %v", err) } // Check the response status code. if resp.StatusCode == http.StatusOK { fmt.Println("Request successful!") // Read the response body. body, err := io.ReadAll(resp.Body) if err != nil { log.Fatalf("Error reading response body: %v", err) } // Print the response body. fmt.Println(string(body)) } else { fmt.Printf("Request failed with status code: %d\n", resp.StatusCode) } } import "io"Key improvements and explanations:
- Context Handling: The
NewRequestWithContextfunction now takes acontext.Contextas input. This is essential for managing the lifetime of the request. Thecontextallows you to cancel the request if it takes too long or if some other condition occurs. Themainfunction creates a context with a timeout. - Error Handling: Comprehensive error handling is included. Each step (request creation, sending the request, reading the response body) is checked for errors, and errors are wrapped with more context using
fmt.Errorf("%w", err). This makes debugging much easier. defer resp.Body.Close(): This is crucial. It ensures that the response body is closed, even if an error occurs. Failing to close the response body can lead to resource leaks.io.ReadAll: Usesio.ReadAllto read the entire response body into a byte slice. This is generally the best way to read the entire response.- Clearer Function: The
NewRequestWithContextfunction is now more focused on creating and sending the request, making it reusable. mainFunction: Themainfunction demonstrates how to use theNewRequestWithContextfunction and how to handle the response.- Timeout: The
context.WithTimeoutfunction sets a timeout for the request. If the request takes longer than the timeout, the context will be cancelled, and the request will be aborted. log.Fatalf: Useslog.Fatalffor fatal errors, which prints the error message and then exits the program.- Comments: Added more comments to explain the code.
How to run:
- Save the code as a
.gofile (e.g.,request_example.go). - Open a terminal and navigate to the directory where you saved the file.
- Run the command
go run request_example.go.
This will send a GET request to
https://example.comand print the response body to the console. If the request takes longer than 5 seconds, it will be cancelled. If there is an error, it will print an error message to the console. This example demonstrates best practices for making HTTP requests in Go using thenet/httpandcontextpackages. It's robust, handles errors gracefully, and manages resources properly.- Context Handling: The
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.