In today's world, making HTTP requests is a common task that is performed by most software engineers. Golang has gained immense popularity due to its simplicity, efficiency, and ease of use, making it a popular choice for building web applications. In this blog, we will discuss how to make a GET request in Golang.
Before we start, we need to install a few packages that will help us make HTTP requests. The net/http package provides the basic tools for making HTTP requests, while the fmt package helps us print the response on the console.
To install these packages, we can use the following command:
go get net/http
go get fmt
Once we have installed the packages, we can start making GET requests. In Golang, we can use the http.Get function to make a GET request. Here is a simple example:
package main
import (
"fmt"
"net/http"
)
func main() {
response, err := http.Get("https://jsonplaceholder.typicode.com/posts")
if err != nil {
fmt.Println("Error:", err)
return
}
defer response.Body.Close()
fmt.Println("Response status code:", response.StatusCode)
}
In the above example, we are making a GET request to the JSONPlaceholder API. The http.Get function returns two values: the HTTP response and an error object. We are using the defer keyword to ensure that the response body is closed after the function returns.
If there is an error in making the request, we print the error message on the console. Otherwise, we print the response status code. This code will print the HTTP status code of the response, which should be 200 OK.
We can also read the response body by using the ioutil.ReadAll function. Here's an example:
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
response, err := http.Get("https://jsonplaceholder.typicode.com/posts")
if err != nil {
fmt.Println("Error:", err)
return
}
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("Response body:", string(body))
}
In the above example, we are using the ioutil.ReadAll function to read the response body. We convert the byte slice to a string and print it on the console. This code will print the JSON response returned by the JSONPlaceholder API.
In conclusion, making GET requests in Golang is a straightforward task. We need to use the net/http package to make HTTP requests and the fmt package to print the response on the console. With the examples given above, you should be able to start making GET requests in your Golang projects.