~/Making HTTP Requests in Go
Dec 14, 2024
To perform HTTP requests in Go, use the built-in net/http package. Use http.Get, http.Post, or build custom requests with http.NewRequest for more control.
Example GET request:
1
2
3
4
5
6
7
8
9
10
|
resp, err := http.Get("https://example.com")
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(body))
|
Example POST request:
1
2
3
4
5
6
|
data := strings.NewReader("key=value")
resp, err := http.Post("https://example.com", "application/x-www-form-urlencoded", data)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
|
Custom request with headers:
1
2
3
4
|
client := &http.Client{}
req, err := http.NewRequest("GET", "https://example.com", nil)
req.Header.Set("X-Custom-Header", "value")
resp, err := client.Do(req)
|
Read more in the official Go documentation. For error handling and request customization, refer to the http.Client docs.