【发布时间】:2017-04-02 20:10:32
【问题描述】:
我正在使用一个 Github 客户端,它允许我更轻松地调用 github API 方法。
这个库允许我在初始化它时提供我自己的*http.Client:
httpClient := &http.Client{}
githubClient := github.NewClient(httpClient)
它工作正常,但现在我需要别的东西。我想自定义客户端,以便每个请求(即Do 方法)都添加一个自定义标头。
我已经阅读了一些关于 嵌入 的内容,这是我迄今为止尝试过的:
package trackerapi
import(
"net/http"
)
type MyClient struct{
*http.Client
}
func (my *MyClient)Do(req *http.Request) (*http.Response, error){
req.Header.Set("cache-control","max-stale=3600")
return my.Client.Do(req)
}
但是编译器不允许我使用自定义的MyClient 代替默认值:
httpClient := &trackerapi.MyClient{}
// ERROR: Cannot use httpClient (type *MyClient) as type
//*http.Client.
githubClient := github.NewClient(httpClient)
我是一个 golang 新手,所以我的问题是:这是做我想做的事情的正确方法吗?如果不是,推荐的方法是什么?
【问题讨论】: