MST

星途 面试题库

面试题:Go中如何实现HTTP请求的超时控制

在Go语言里,假设你要发起一个HTTP GET请求,并且希望设置10秒的超时时间,该如何实现?请写出主要的代码片段。
28.2万 热度难度
编程语言Go

知识考点

AI 面试

面试题答案

一键面试
package main

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

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 10*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 {
        fmt.Println("请求失败:", err)
        return
    }
    defer resp.Body.Close()

    // 处理响应
}