Skip to content
TheChatArchiveThe Chat Archive
Googlegemma-3n-e4b-it· GoogleHugging Face LMArena Human Preference 140K

NewRequestWithContext example to send get request

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Mistralmagistral-medium-2506’s answer.
  1. User

    NewRequestWithContext example to send get request

  2. Google 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 NewRequestWithContext function now takes a context.Context as input. This is essential for managing the lifetime of the request. The context allows you to cancel the request if it takes too long or if some other condition occurs. The main function 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: Uses io.ReadAll to read the entire response body into a byte slice. This is generally the best way to read the entire response.
    • Clearer Function: The NewRequestWithContext function is now more focused on creating and sending the request, making it reusable.
    • main Function: The main function demonstrates how to use the NewRequestWithContext function and how to handle the response.
    • Timeout: The context.WithTimeout function 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: Uses log.Fatalf for fatal errors, which prints the error message and then exits the program.
    • Comments: Added more comments to explain the code.

    How to run:

    1. Save the code as a .go file (e.g., request_example.go).
    2. Open a terminal and navigate to the directory where you saved the file.
    3. Run the command go run request_example.go.

    This will send a GET request to https://example.com and 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 the net/http and context packages. It's robust, handles errors gracefully, and manages resources properly.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.