How to use context to implement request timeout control in Go

WBOY
Release: 2023-07-21 12:18:22
Original
2443 people have browsed it

How to use context to implement request timeout control in Go

Introduction:
When we make network requests, we often encounter the problem of request timeout. A network request that does not respond for a long time will not only waste server resources, but also affect overall performance. In order to solve this problem, the Go language introduced the context package, which can be used to implement request timeout control. This article will introduce how to use the context package to implement request timeout control in Go, and attach corresponding code examples.

1. Understanding the context package
The context package is a package provided by the Go language standard library and is used to manage context information related to requests. Through the context package, we can implement functions such as timeout control of requests, cancellation of requests, and transfer of context information between requests.

Before using the context package, we need to first understand some commonly used functions and types in the context package:

  • WithCancel(parent Context) (ctx Context, cancel CancelFunc): Returns a Subcontext with cancellation function. When the cancel function is called, the context and its subcontexts are canceled.
  • WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc): Returns a sub-context with deadline. When the deadline is reached, the context and its subcontexts are canceled.
  • WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc): Returns a sub-context with a timeout. When the timeout is reached, the context and its subcontexts are canceled.
  • WithValue(parent Context, key interface{}, val interface{}) Context: Returns a sub-context with key-value pairs.

2. Use the context package to implement request timeout control
The following is a sample code that uses the context package to implement request timeout control:

package main

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

func main() {
    // 创建一个带有超时时间的上下文对象
    ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
    defer cancel()

    // 创建一个带有上下文的http请求
    req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://www.example.com", nil)
    if err != nil {
        fmt.Println("创建请求失败:", err)
        return
    }

    // 发送请求并得到响应
    client := http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        fmt.Println("发送请求失败:", err)
        return
    }

    defer resp.Body.Close()

    fmt.Println("请求成功!")
}
Copy after login

In the above example code, we first A context object with a 3 second timeout is created by calling context.WithTimeout. Then, we use the http.NewRequestWithContext method to create an http request object with context and send the request. Finally, we send the request by calling the client.Do method and get the response.

Note that when using the http request object with context, we need to use the http.NewRequestWithContext method instead of the original http.NewRequest method to create the request object. to pass contextual information to the request.

3. Principle of request timeout control implementation
When we use the http request object with context to send a request, before the request is sent, we will first check whether the context object has expired (i.e., timed out). If the timeout has occurred, the request will be canceled and no network request will be made. This implements request timeout control.

4. Summary
Using the context package can easily implement request timeout control. In actual development, we can set a reasonable timeout as needed to help us avoid unnecessary long waiting and resource waste. By rationally utilizing the context package, we can more flexibly control the execution time of requests and improve the stability and performance of the system.

The above is an introduction to using the context package to implement request timeout control in Go. I hope it will be helpful to you!

The above is the detailed content of How to use context to implement request timeout control in Go. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!