gpt4 book ai didi

http - 使用 HTTPRoundTripper 重试

转载 作者:行者123 更新时间:2023-12-03 00:31:00 29 4
gpt4 key购买 nike

http.RoundTripper在 Go 中基于 HTTP 状态代码(例如 429)实现 http GET 请求重试机制的正确位置?

它在某种程度上“感觉正确”( Go Playground )并且不会将现有接口(interface)更改为 http.Clienthttp.Request/http.Response 。然而,documentation explicitly states :

RoundTrip should not attempt to interpret the response.

RoundTrip should not modify the request, except for consuming and closing the Request's Body.

当我使用 http.RoundTripper 执行此操作时,我是否已经通过评估 HTTP 状态代码和/或通过重新发送失败的 HTTP 请求来修改请求来解释响应,因此违背了 http.RoundTripper ?为什么这是一个坏主意(如果是的话)?

最佳答案

从我的角度来看,应该在您的应用程序中明确处理重试。

修改 Roundtripper 的风险在于,您将重试逻辑隐藏在代码中最重要的位置:当某人(包括 6 个月后的您)试图找出应用程序的用途时。

明显存在重试逻辑被遗漏的风险,并且有人看到隐式假设请求成功的代码 - 并在代码中的不同点编写重试逻辑/错误处理。

编辑

至于重试和退避,我倾向于使用 https://gopkg.in/cenkalti/backoff.v3 ,这使得重试操作变得简单而简洁

var (
resp *http.Response
err error
)

operation := func() error {
resp, err = http.Get("http://example.com/")
// Handle Retry-After here, if you wish...
// If err is nil, no retry will occur
return err
}

err := backoff.Retry(operation, backoff.NewExponentialBackOff())
if err != nil {
panic("getting resource: permanent error during backoff")
}

// resp is non-nil

关于http - 使用 HTTPRoundTripper 重试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58929585/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com