MST

星途 面试题库

面试题:Go中context API函数在并发任务控制里的基础运用

在Go语言中,假设你有多个并发的HTTP请求任务,为了防止任务执行时间过长,需要设置一个超时时间。请使用context API函数来实现这个功能,并简要说明`context.WithTimeout`函数的参数及返回值的含义。
24.3万 热度难度
编程语言Go

知识考点

AI 面试

面试题答案

一键面试
package main

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

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()

    req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://example.com", nil)
    if err != nil {
        fmt.Println("创建请求失败:", err)
        return
    }

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        if err, ok := err.(context.Canceled); ok {
            fmt.Println("请求被取消:", err)
        } else if err, ok := err.(context.DeadlineExceeded); ok {
            fmt.Println("请求超时:", err)
        } else {
            fmt.Println("请求发生其他错误:", err)
        }
        return
    }
    defer resp.Body.Close()

    // 处理响应
    fmt.Println("请求成功:", resp.StatusCode)
}

context.WithTimeout函数的参数及返回值含义如下:

  • 参数
    • 第一个参数parent:表示父context,通常使用context.Background()作为顶级context
    • 第二个参数timeout:表示设置的超时时间,是一个time.Duration类型,如5*time.Second表示5秒超时。
  • 返回值
    • 第一个返回值ctx:是带有超时设置的context,可以传递给需要控制超时的操作,如HTTP请求。
    • 第二个返回值cancel:是一个取消函数,用于手动取消context,在使用完毕后应该调用此函数以释放资源,通常使用defer cancel()来确保函数结束时取消操作被执行。