阅读量:289
在Golang中,缓存策略通常是通过设置HTTP客户端(http.Client)的Transport属性来实现的。以下是一个示例,展示了如何在CentOS上设置Golang HTTP客户端的缓存策略:
首先,确保已经安装了Golang。如果还没有安装,请访问官方网站()下载并安装。
创建一个名为main.go的文件,并在其中编写以下代码:
package main
import (
"fmt"
"net/http"
"time"
)
func main() {
client := &http.Client{
Transport: &http.Transport{
DisableCompression: true,
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}).DialContext,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
},
}
// 设置缓存策略
cacheControl := "public, max-age=3600"
client.Transport.(*http.Transport).ResponseHeaderTimeout = 5 * time.Second
client.Transport.(*http.Transport).IdleConnTimeout = 90 * time.Second
// 发送请求
req, err := http.NewRequest("GET", "https://example.com", nil)
if err != nil {
fmt.Println("Error creating request:", err)
return
}
req.Header.Set("Cache-Control", cacheControl)
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error making request:", err)
return
}
defer resp.Body.Close()
fmt.Println("Response status:", resp.Status)
}
在这个示例中,我们设置了以下缓存策略:
保存文件并运行程序:
go run main.go