Avatar ·

How to make an HTTP request in Go?

Hello everyone! Please tell me how to properly make an HTTP GET request in Go and get a response from the server. I'm new to the language and ran into a problem when trying to get data from an external API.

Currently I'm using the standard library net/http, but my code seems to hang and doesn't return a result. Here's what I tried:

package main\n\nimport (\n    "fmt"\n    "io/ioutil"\n    "net/http"\n)\n\nfunc main() {\n    resp, err := http.Get("https://api.example.com/data")\n    if err != nil {\n        fmt.Println("Error:", err)\n        return\n    }\n    defer resp.Body.Close()\n\n    body, err := ioutil.ReadAll(resp.Body)\n    if err != nil {\n        fmt.Println("Error reading:", err)\n        return\n    }\n\n    fmt.Println(string(body))\n}