Build a Simple Go HTTP Client
This challenge will guide you through creating a basic HTTP client in Go. You'll learn how to make HTTP requests, handle responses, and process data from a web server. This is a fundamental skill for interacting with web APIs and services.
Problem Description
Your task is to implement a Go program that can fetch data from a given URL. The program should be able to send a GET request to a specified URL, retrieve the response body, and then print the content of the response. You should also handle potential errors that might occur during the HTTP request.
Key Requirements:
- Make a GET request to a provided URL.
- Read the entire response body.
- Print the response body to standard output.
- Handle potential network errors (e.g., invalid URL, connection refused).
- Handle potential HTTP errors (e.g., 404 Not Found, 500 Internal Server Error).
Expected Behavior:
- If the request is successful (HTTP status code 2xx), print the response body.
- If an error occurs during the request or an HTTP error status is returned, print an informative error message to standard error.
Edge Cases:
- What happens if the URL is malformed?
- What happens if the server is unreachable?
- What happens if the server returns a non-200 status code?
- What happens if the response body is empty?
Examples
Example 1:
Input: https://jsonplaceholder.typicode.com/todos/1
Output:
{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
}
Explanation: The program successfully makes a GET request to the provided URL, retrieves the JSON data, and prints it to standard output.
Example 2:
Input: https://example.com/nonexistent-page
Output:
Error: HTTP request failed: status code 404 Not Found
Explanation: The program encounters a 404 Not Found error and prints an appropriate error message to standard error.
Example 3:
Input: invalid-url
Output:
Error: HTTP request failed: invalid URL: parse "invalid-url": for URL must have a scheme matching "http" or "https"
Explanation: The program detects an invalid URL format and prints a parsing error message to standard error.
Constraints
- The URL will be provided as a string argument to your program.
- You are expected to use Go's standard
net/httppackage for making requests. - The response body is not expected to exceed 1MB in size for typical successful requests in this challenge.
- The program should execute within a reasonable time frame (e.g., a few seconds for network operations).
Notes
- You will likely need to import the
net/httpandiopackages. - Consider using
http.Get()for simplicity in making GET requests. - Remember to read the response body completely before the response connection is closed. The
io.ReadAll()function is very useful here. - Pay attention to the
resp.StatusCodeto check for HTTP errors. - For printing errors,
fmt.Errorfandlog.Fatalorfmt.Fprintln(os.Stderr, ...)are good options.