Trusted answers to developer questions

How can we make HTTP GET request in Golang

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

The HTTP GET method is used for requesting data from the server or some other source. In this shot, we will learn how to fetch data with the GET method in Golang.

1. Create a Golang file

Let’s name this file main.go and import the necessary packages:

package main

import (
   "fmt"
   "net/http"
)

The net/http package provides all the utilities that we need to make HTTP requests.

2. Make a GET request

The net/http package has a Get() method, which is used for making GET requests that accept a URL and return a response and an error. When the error is nil, the response returned will contain a response body and vice versa.

response, error := http.Get("https://reqres.in/api/products")

if error != nil {
   fmt.Println(error)
}

fmt.Println(response)

Note: At this point, the response contains a large amount of incoherent data, like the header and properties of the request.

Code

package main
import (
"fmt"
"net/http"
)
func main() {
// make GET request
response, error := http.Get("https://reqres.in/api/products")
if error != nil {
fmt.Println(error)
}
// print response
fmt.Println(response)
}

As can be seen in the code given above, we made a GET request to this URL and then output the response on the console.

RELATED TAGS

golang
go

CONTRIBUTOR

Shubham Singh Kshatriya
Did you find this helpful?