What is an HTTP client in Go?
To create an HTTP client in Go, you typically start by creating an instance of the "http.Client" struct provided by the "net/http" package. This struct allows you to configure various options for the client, such as the timeout for requests, the maximum number of redirects to follow, and whether to enable HTTP/2 support.
Once you have your HTTP client, you can use the "http.NewRequest" function to create an HTTP request object. This function takes several arguments, including the HTTP method (such as "GET" or "POST"), the URL to request, and an optional request body.
You can then use the "http.Client.Do" method to send the HTTP request and receive the HTTP response. This method takes the HTTP request object as an argument and returns an HTTP response object, as well as an error value that indicates whether the request was successful.
Here's an example of a simple HTTP client in Go that sends a GET request to a server and prints the response body:
Example
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
resp, err := http.Get("http://example.com/")
if err != nil {
// handle error
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// handle error
}
fmt.Println(string(body))
}