In Go, you can perform HTTP GET requests using the net/http
package. Here's an example of how to perform an HTTP GET request:
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
)
func main() {
// Make an HTTP GET request
resp, err := http.Get("https://api.example.com/data")
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
// Read the response body
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
// Print the response body
fmt.Println(string(body))
}
In this example, we use the http.Get()
function to send an HTTP GET request to the specified URL ("https://api.example.com/data"). The response is stored in the resp
variable.
We then defer the closing of the response body using resp.Body.Close()
to ensure that it's closed after we've finished using it.
Next, we use ioutil.ReadAll()
to read the entire response body, storing it in the body
variable.
Finally, we print the response body using fmt.Println()
. Note that we convert the []byte
response body to a string using string(body)
.
Remember to handle any errors that may occur during the HTTP request and response handling.