Welcome To Golang By Example

Golang net/http Package – Detecting Timeout

Below is a sample code piece to know if there is a timeout for an upstream call that is using net/http package. Http Client is created with 1 nanosecond timeout so that it always times out on google.com

package main

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

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

	_, err := client.Get("https://google.com")

	isTimeout := false
	if os.IsTimeout(err) {
		isTimeout = true
	}

	fmt.Println("isTimeout)
}

Output: true