DEV Community

Kiran
Kiran

Posted on • Updated on • Originally published at kirandev.com

Make an HTTP GET request in Go

We’ll explore how to make an HTTP GET request in Go. We will fetch the JSON content from an API endpoint and display the results on the console.

Create a new folder called http-request.

mkdir http-request

cd http-request

touch main.go
Enter fullscreen mode Exit fullscreen mode

Open the main.go and import the necessary packages.

package main

import (
    "encoding/json"
    "fmt"
    "net/http"
)
Enter fullscreen mode Exit fullscreen mode

Make the HTTP request to https://jsonplaceholder.cypress.io/todos/11

func main() {
    resp, err := http.Get("https://jsonplaceholder.cypress.io/todos/11")
    if err != nil {
        print(err)
    }

    defer resp.Body.Close()
}
Enter fullscreen mode Exit fullscreen mode

Create a struct that models the data received from the API.

type PostResponse struct {
    UserId    int    `json:"userId"`
    Id        int    `json:"id"`
    Title     string `json:"title"`
    Completed bool   `json:"completed"`
}

func main() {
    ...
}
Enter fullscreen mode Exit fullscreen mode

Let's decode the JSON response using json.NewDecoder function that takes in the response body and a decode function that takes in a variable of type PostResponse.

var post PostResponse

if err := json.NewDecoder(resp.Body).Decode(&post); err != nil {
    print(err)
}

fmt.Printf("UserId: %v\n", post.UserId)
fmt.Printf("Id: %v\n", post.Id)
fmt.Printf("Title: %v\n", post.Title)
fmt.Printf("Completed: %v\n", post.Completed)
Enter fullscreen mode Exit fullscreen mode

Here is the complete working code.

package main

import (
    "encoding/json"
    "fmt"
    "net/http"
)

type PostResponse struct {
    UserId    int    `json:"userId"`
    Id        int    `json:"id"`
    Title     string `json:"title"`
    Completed bool   `json:"completed"`
}

func main() {
    // Make the http request
    resp, err := http.Get("https://jsonplaceholder.cypress.io/todos/11")
    if err != nil {
        print(err)
    }

    // Close the body
    defer resp.Body.Close()

    var post PostResponse

    // Decode the JSON response
    if err := json.NewDecoder(resp.Body).Decode(&post); err != nil {
        print(err)
    }

    // Print the result on the console
    fmt.Printf("UserId: %v\n", post.UserId)
    fmt.Printf("Id: %v\n", post.Id)
    fmt.Printf("Title: %v\n", post.Title)
    fmt.Printf("Completed: %v\n", post.Completed)
}
Enter fullscreen mode Exit fullscreen mode

I hope you found this article insightful.

Let's connect 🌎

Discussion (0)