In this article, we'll explore how to make HTTP requests using the net/http package in Go, one of the most widely used packages for handling HTTP operations. Understanding how to make such requests is vital for interacting with APIs, fetching web content, and more.
Introduction to the net/http Package
The net/http package in Go is comprehensive and provides many functions and methods for HTTP clients and servers. In this discussion, we will focus on its client capabilities.
Performing a Simple GET Request
A GET request is one of the most common HTTP requests. Let's see how it can be done:
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
resp, err := http.Get("https://jsonplaceholder.typicode.com/posts/1")
if err != nil {
fmt.Println(err)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(body))
}
This code snippet demonstrates how to perform a simple GET request and print the response body to the console.
Sending a POST Request
To send data to a server, you use a POST request. The example below shows how to perform a POST request with JSON data.
package main
import (
"bytes"
"fmt"
"net/http"
)
func main() {
jsonStr := []byte(`{"title":"foo","body":"bar","userId":1}`)
resp, err := http.Post("https://jsonplaceholder.typicode.com/posts", "application/json", bytes.NewBuffer(jsonStr))
if err != nil {
fmt.Println(err)
return
}
defer resp.Body.Close()
fmt.Println("Response status:", resp.Status)
}
This code snippet shows how to send JSON data in the body of a POST request.
Customizing Requests Using http.Client
For more control over your HTTP requests, use http.Client. It allows specifying request headers, timeouts, etc.
package main
import (
"fmt"
"io/ioutil"
"net/http"
"time"
)
func main() {
client := &http.Client{
Timeout: 10 * time.Second,
}
req, err := http.NewRequest("GET", "https://jsonplaceholder.typicode.com/posts/1", nil)
if err != nil {
fmt.Println(err)
return
}
req.Header.Set("User-Agent", "MyCustomUserAgent/1.0")
resp, err := client.Do(req)
if err != nil {
fmt.Println(err)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(body))
}
In the above code, method http.NewRequest gives more flexibility in crafting an HTTP request. We can add a custom header as shown.
Conclusion
The net/http package is a powerful tool for making HTTP requests in Go. With its ability to handle different request types and customize them using the http.Client, you can interact with APIs and web services efficiently.