This tutorial aims to guide you through making HTTP requests using Go's net/http package. By the end of this tutorial, you will learn how to send and receive HTTP requests and responses using Go.
Prerequisites:
- Basic knowledge of Go programming language
- Go installed on your system
The net/http package in Go provides functions to send and receive HTTP requests. Here, we will focus on making requests using the 'http.Get', 'http.Post', and 'http.NewRequest' functions.
The http.Get function makes a GET request to a URL and returns a Response and an error. The Response contains the server's response to the request.
The http.Post function sends a POST request to a URL. It includes a payload (data) to send to the server. It also returns a Response and an error.
The http.NewRequest function is used when you need more flexibility with your HTTP request – for example, adding headers or changing the method (GET, POST, PUT, DELETE, etc.) It returns a Request and an error.
package main
import (
"io/ioutil"
"log"
"net/http"
)
func main() {
res, err := http.Get("http://example.com")
if err != nil {
log.Fatal(err)
}
body, err := ioutil.ReadAll(res.Body)
res.Body.Close()
if err != nil {
log.Fatal(err)
}
log.Printf("%s", body)
}
In this example, we make a GET request to http://example.com using http.Get. The response from the server is read and logged to the console.
package main
import (
"log"
"net/http"
"strings"
)
func main() {
res, err := http.Post(
"http://example.com/form",
"application/x-www-form-urlencoded",
strings.NewReader("name=test"),
)
if err != nil {
log.Fatal(err)
}
defer res.Body.Close()
log.Printf("Response status: %s", res.Status)
}
In this example, we send a POST request to http://example.com/form with a data payload of "name=test". The server's response status is logged to the console.
This tutorial covered how to make HTTP requests using the net/http package in Go. You learned how to send GET and POST requests, and read the server's response.
Next steps:
- Explore other methods available in the net/http package
- Learn how to handle errors and status codes in HTTP responses
Additional resources:
- Go net/http package documentation
Solutions and tips will vary depending on the server used and the data sent in the requests. Remember to handle errors and close response bodies to prevent memory leaks.