Go provides excellent support for working with HTTP requests through its net/http
package. In this article, we'll see how to make GET and POST requests using only the packages included in Go's standard library.
Making a GET Request
To send a GET request, we can use the http.Get
function. Here's an example:
package main
import (
"fmt"
"io"
"net/http"
)
func main() {
resp, err := http.Get("https://example.com")
if (err != nil) {
panic(err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if (err != nil) {
panic(err)
}
fmt.Println(string(body))
}
In the code above:
- We call
http.Get
with the desired URL. - We check for errors and remember to close the response body using
defer
. - We use
io.ReadAll
to read the entire response body.
Making a POST Request
To send data with a POST request, we can use http.Post
or manually create a request with http.NewRequest
. Here's a simple example using http.Post
:
package main
import (
"bytes"
"fmt"
"io"
"net/http"
)
func main() {
data := []byte(`{"name":"John","age":30}`)
resp, err := http.Post("https://example.com/api", "application/json", bytes.NewBuffer(data))
if (err != nil) {
panic(err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if (err != nil) {
panic(err)
}
fmt.Println(string(body))
}
Here:
- We prepare the data to send as JSON.
- We call
http.Post
specifying the URL, content type, and body. - We read and print the response as in the GET case.
Handling Custom Requests
For more control, we can manually create a request using http.NewRequest
and send it with http.Client
:
package main
import (
"bytes"
"fmt"
"io"
"net/http"
)
func main() {
client := &http.Client{}
req, err := http.NewRequest("PUT", "https://example.com/resource", bytes.NewBuffer([]byte(`{"update":"true"}`)))
if (err != nil) {
panic(err)
}
req.Header.Set("Content-Type", "application/json")
resp, err := client.Do(req)
if (err != nil) {
panic(err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if (err != nil) {
panic(err)
}
fmt.Println(string(body))
}
This approach allows you to:
- Specify the HTTP method (such as PUT, PATCH, DELETE).
- Add custom headers.
- Use a custom
http.Client
.
Conclusion
With the net/http
package and io
functions, Go makes it simple to send HTTP requests in a robust and performant way, without needing external libraries.