使用Hashcorp的cleanhttp

缘起 早上在某地方看到这样一张图 大意是说任何第三方库都可以拦截您的所有 HTTP 调用,然后推荐了一个库 cleanhttp 官网的介绍: Functions for accessing “clean” Go http.Client values 用于访问“干净”Go http.Client 值的函数 The Go standard library contains a default http.Client called http.DefaultClient. It is a common idiom in Go code to start with http.DefaultClient and tweak it as necessary, and in fact, this is encouraged; from the http package documentation: Go 标准库包含一个名为 http.DefaultClient 的默认 http.Client 。在 Go 代码中,以 http.DefaultClient 开头并根据需要进行调整是一种常见的习惯用法,事实上,这是值得鼓励的;来自 http 包文档: The Client’s Transport typically has internal state (cached TCP connections), so Clients should be reused instead of created as needed. Clients are safe for concurrent use by multiple goroutines. 客户端的传输通常具有内部状态(缓存的 TCP 连接),因此客户端应该被重用,而不是根据需要创建。多个 goroutine 并发使用客户端是安全的。 ...

2023-08-23 · 4 分钟 · czyt

【译】如何使用 http.ResponseController 类型

本文原文地址 https://www.alexedwards.net/blog/how-to-use-the-http-responsecontroller-type ,使用chatGPT翻译 One of my favorite things about the recent Go 1.20 release is the new http.ResponseController type, which brings with it three nice benefits: 关于最近的 Go 1.20 版本,我最喜欢的事情之一是新的 http.ResponseController 类型,它带来了三个好处: You can now override your server-wide read and write deadlines on a per request basis. 您现在可以根据每个请求覆盖服务器范围内的读取和写入截止日期。 The pattern for using the http.Flusher and http.Hijacker interfaces is clearer and feels less hacky. No more type assertions necessary! 使用 http.Flusher 和 http.Hijacker 接口的模式更清晰,感觉更轻松。不再需要类型断言! It makes it easier and safer to create and use custom http.ResponseWriter implementations. 它使创建和使用自定义 http.ResponseWriter 实现变得更容易和更安全。 The first two benefits are mentioned in the release notes, but the third one seems to have gone under the radar a bit… which is a shame, because it’s very helpful! 发行说明中提到了前两个好处,但第三个好处似乎有点不为人知……这很遗憾,因为它非常有帮助! ...

2023-03-09 · 6 分钟 · czyt