Sitemap

How to make a Web Request in GO

2 min readDec 31, 2025

--

Press enter or click to view image in full size

To make a web request in Golang, we mainly use the following packages:

  • net/http — to make HTTP requests
  • ioutil — to read response data bytes (deprecated but still works)
  • fmt — to print the output

The http package supports all common HTTP methods such as GET, POST, PUT, and DELETE.

Here, we are making a GET request using the Get() function from the http package.

response, err := http.Get(url)

Here, url is the server address.

The response variable stores a pointer to an http.Response structure, which contains the response sent by the server.

If any error occurs during the request (network issue, invalid URL, etc.), it is stored in err.

Errors are handled using a conditional statement:

if err != nil {
panic(err)
}

If an error occurs, the panic() function stops program execution by crashing the program, preventing further incorrect execution.

If the request is successful, the response contains the complete HTTP response, including:

  • response.Status
  • response.StatusCode
  • response.Body
  • response.Header
  • response.Request

It is very important to close the response body after use:

defer response.Body.Close()

Why response.Body Does Not Print Data Directly

If we try to print response.Body directly, it will not print the actual data.

Get Warhadeyash31@gmail.com’s stories in your inbox

Join Medium for free to get updates from this writer.

Instead, it prints the address of the body reader, because response.Body is a stream interface, not a data container.

A stream interface means data is received little by little, not all at once.

Simple example

Imagine drinking water through a straw:

  • Straw → stream
  • Water → data
  • You sip little by little
  • You don’t get all the water at once

That is how a stream works.

Reading the Actual Response Data

To get the actual data from the stream, we use ioutil.ReadAll():

dataBytes, err := ioutil.ReadAll(response.Body)
  • ioutil.ReadAll() reads the entire stream
  • It consumes the stream, so it cannot be read again
  • The response data is stored in dataBytes, which can be printed using fmt.Println()
fmt.Println(string(dataBytes))

Note

  • The ioutil package is deprecated since Go 1.16, but it still works.
  • The modern replacement is:
io.ReadAll(response.Body)

--

--