To perform a simple HTTP GET request in Go using the net/http package, follow these steps:
Step 1: Import the necessary packages
import (
"net/http"
"fmt"
)
Step 2: Create a new HTTP client
client := http.Client{}
Step 3: Send a GET request
response, err := client.Get("https://example.com") // specify your URL here
if err != nil {
fmt.Println("Error:", err)
return
}
defer response.Body.Close()
Step 4: Read the response body
body, err := ioutil.ReadAll(response.Body)
if err != nil {
fmt.Println("Error:", err)
return
}
Step 5: Print the response body
fmt.Println(string(body))
Putting it all together, here's a complete example:
package main
import (
"fmt"
"net/http"
"io/ioutil"
)
func main() {
client := http.Client{}
response, err := client.Get("https://example.com")
if err != nil {
fmt.Println("Error:", err)
return
}
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println(string(body))
}
Replace "https://example.com" with the URL you want to perform the GET request on.
Note that this is a very basic example and does not handle various aspects such as error handling or request headers.