HTTP Get Request with Timeout

· 260 words · 2 minutes read

We’ve already covered how to download a file, but this post covers it a little further by specifying the maximum time attempted on the request. Adding timeouts are often important to stop your program coming to a halt.

To do this we make our own http client, giving it our custom timeout value. We can then use this client to make our requests. If a timeout is reached, the Get() function will return with an error. Our code is set to a very short timeout of 5 milliseconds to demo the error, but this can be set to any duration you need.

Illustrating the Error

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
package main

import (
	"net/http"
	"log"
	"time"
)

func main() {

	client := http.Client{
		Timeout: 5 * time.Millisecond,
	}

	// Will throw error as it's not quick enough
	_, err := client.Get("https://golangcode.com/robots.txt")
	if err != nil {
		log.Fatal(err)
	}
}

error thrown from request with short timeout

Successful Example

For the successful example we change the timeout to 10 seconds, which gives it enough time to connect and get a response.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package main

import (
	"io/ioutil"
	"net/http"
	"log"
	"time"
)

func main() {

	client := http.Client{
		Timeout: 10 * time.Second,
	}

	resp, err := client.Get("https://golangcode.com/robots.txt")
	if err != nil {
		log.Fatal(err)
	}

	html, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}

	log.Println(string(html))
}

successful get request with timeout

Image of Author Edd Turtle

Author:  Edd Turtle

Edd is the Lead Developer at Hoowla, a prop-tech startup, where he spends much of his time working on production-ready Go and PHP code. He loves coding, but also enjoys cycling and camping in his spare time.

See something which isn't right? You can contribute to this page on GitHub or just let us know in the comments below - Thanks for reading!