Making GET Requests and Handling Responses in Go

Making GET Requests and Handling Responses

Welcome to the second lesson in our journey of interacting with APIs using Go. In the previous lesson, we established a strong understanding of RESTful APIs and how HTTP requests facilitate interactions with them. We used curl to interact directly with an API endpoint. Now, we will automate this process using Go's net/http package. This lesson will guide you through making HTTP requests in Go, equipping you with essential skills for web development and API integration.

Setting Up the Environment

To make HTTP requests in Go, we'll use the standard library's net/http package, which is powerful and does not require any third-party installation. If you're developing locally, make sure you have Go installed on your system. You can download and install it from the official website. Once installed, verify your installation by running:

go version

This command should show the currently installed version of Go. With Go set up, you're ready to write and run scripts that automate HTTP requests, saving time and boosting efficiency.

Defining the Base URL

In Go, we'll define a base URL for the API service we are using. This approach keeps our code modular and maintainable.

package main

import (
    "fmt"
)

const baseURL = "http://localhost:8000"

func main() {
    fmt.Println("Base URL is set to:", baseURL)
}

By defining the base URL this way, we can easily append endpoints for different API services, keeping our code clean and adaptable.

Performing a Basic GET Request

Let's move on to fetching data from an API using Go's http.Get() function. Our goal is to retrieve a list of to-do items from the /todos endpoint.

package main

import (
    "fmt"
    "io"
    "log"
    "net/http"
)

func main() {
    resp, err := http.Get(baseURL + "/todos")
    if err != nil {
        log.Fatalf("Failed to get todos: %v", err)
    }

    body, err := io.ReadAll(resp.Body)
    if err != nil {
        log.Fatalf("Failed to read response body: %v", err)
    }

    fmt.Println("Raw Response:")
    fmt.Println(string(body))
}

Here, http.Get() sends the GET request, and io.ReadAll() reads the response body. We print the raw response as a string, giving us the immediate result returned by the server.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal