Make http GET request with Go

How to make http GET request with Go using the net/http go module. You will also see how to define a custom http client with a predefined timeout. Go has a great build in http module. In this example you will learn how to do a simple http get request, how to release the resources once are not needed anymore, how to convert the io.ReadCloser to a []byte object. Finally you will learn how to convert the byte data to a string and display it.

Code

Here is the baisc way to do a simple http get request in go.

response, err := http.Get(url)

Example

package main

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

func main(){
    client := &http.Client{
        Timeout: time.Second * 30,
    }

    if response, err := client.Get("http://mockbin.com/request"); err == nil{
        defer response.Body.Close()
        if body, err := io.ReadAll(response.Body); err == nil {
            fmt.Println(string(body))
        }
    }else {
        panic(err)
    }
}

Other articles