我正在创建一个具有调用一些api的函数的类,到目前为止我有:
var client *http.Client
func getClient() *http.Client {
if client == nil {
client = &http.Client{
Timeout: time.Second * 30,
Transport: &http.Transport{
Dial: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}).Dial,
TLSHandshakeTimeout: 10 * time.Second,
},
}
}
return client
}
然后创建一个执行调用的函数:func CallRestApi(request Request) (response Response) {
getClient()
req, err := http.NewRequest(request.Method, url, bytes.NewBuffer(request.Params))
resp, err := client.Do(req)
...
}
我不确定这样我是否会创建一个单例 client
实例,以便从执行此函数的任何模块中,如果该实例已存在,则将使用该实例。
最佳答案
这是一种更简单的方法:
var Client *http.Client= &http.Client{
Timeout: time.Second * 30,
Transport: &http.Transport{
Dial: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}).Dial,
TLSHandshakeTimeout: 10 * time.Second,
},
}
}
您不需要单独的初始化函数来初始化变量。
关于go - 单例 http 客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62904351/