Home >Backend Development >Golang >How can I effectively cancel HTTP requests in Go when a timeout occurs?

How can I effectively cancel HTTP requests in Go when a timeout occurs?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-29 18:11:04852browse

How can I effectively cancel HTTP requests in Go when a timeout occurs?

Understanding Goroutine Timeout

In your provided code, you have implemented a timeout mechanism using a select statement to handle either the result from the findCicCode() function or a timeout of 50 milliseconds. However, you expressed concerns about the potential for resource leakage if the HTTP calls continue to execute even after the timeout.

Utilizing Context for HTTP Request Cancelation

To address this issue, you can leverage the concept of context in Go. Context provides a way to associate context-specific values with goroutines and allows for cancelation. With context, you can cancel ongoing HTTP calls when a timeout occurs.

Here's an example of how you can implement context cancelation for HTTP requests:

<code class="go">package main

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

type Response struct {
    data   interface{}
    status bool
}

func Find() (interface{}, bool) {
    ch := make(chan Response, 1)

    ctx, cancel := context.WithTimeout(context.Background(), time.Second)
    defer cancel() // Ensure cancelation when the function exits

    go func() {
        data, status := findCicCode(ctx)
        ch <- Response{data: data, status: status}
    }()

    select {
    case response := <-ch:
        return response.data, response.status
    case <-time.After(50 * time.Millisecond):
        return "Request timed out", false
    }
}

func main() {
    data, timedOut := Find()
    fmt.Println(data, timedOut)
}</code>

In this modified code:

  • A context.Context is created along with a cancel function.
  • The findCicCode() function is passed the ctx to cancel ongoing requests if the timeout occurs.
  • Each HTTP request created within the findCicCode() function is assigned the ctx using req.WithContext(ctx).
  • If the timeout occurs, the cancel function is called, which in turn cancels all ongoing HTTP requests associated with the ctx.

By using this approach, you ensure that any ongoing HTTP requests are canceled when the timeout is reached, preventing unnecessary resource consumption.

The above is the detailed content of How can I effectively cancel HTTP requests in Go when a timeout occurs?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn