WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Go · Intermediate · question 29 of 100

How would you handle timeouts in HTTP requests in a Go application?

📕 Buy this interview preparation book: 100 Go questions & answers — PDF + EPUB for $5

Handling timeouts in HTTP requests in a Go application is crucial to ensure that your application is resilient and does not hang indefinitely while waiting for a response from a server. You can achieve this by setting a timeout value while creating an HTTP client and then using that client to make requests.

The default ‘http.Client‘ used by the ‘http.Get‘, ‘http.Post‘, and other functions does not have any timeout. So, it’s recommended to create a custom client with a timeout using ‘http.Client‘.

Here’s a step-by-step explanation of how to do this:

1. Import the necessary packages:

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

2. Create a new ‘http.Client‘ with a specified timeout:

client := &http.Client{
    Timeout: time.Second * 5,  // Set the timeout to 5 seconds
}

3. Use the custom client to make an HTTP GET request:

response, err := client.Get("https://example.com")
if err != nil {
    fmt.Printf("Error making HTTP request: %vn", err)
    return
}
defer response.Body.Close()

// Process the response as needed.

Here’s a complete example:

package main

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

func main() {
    client := &http.Client{
        Timeout: time.Second * 5,  // Set the timeout to 5 seconds 
    }

    response, err := client.Get("https://example.com")
    if err != nil {
        fmt.Printf("Error making HTTP request: %vn", err)
        return
    }
    defer response.Body.Close()

    body, err := ioutil.ReadAll(response.Body)
    if err != nil {
        fmt.Printf("Error reading response body: %vn", err)
        return
    }

    fmt.Printf("Response: %sn", body)
}

In the example above, we set a 5-second timeout for our HTTP requests. If the server does not respond within 5 seconds, the request results in an error.

Remember that it’s best practice to use a custom client and avoid using ‘http.Get‘, ‘http.Post‘ and other similar functions, since they use the default client without any timeout.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Go interview — then scores it.
📞 Practice Go — free 15 min
📕 Buy this interview preparation book: 100 Go questions & answers — PDF + EPUB for $5

All 100 Go questions · All topics