Fel*_*ida 4 subclass embedding go
我正在使用Github客户端,它允许我更轻松地调用github API方法.
这个库允许我*http.Client在初始化时提供自己的库:
httpClient := &http.Client{}
githubClient := github.NewClient(httpClient)
Run Code Online (Sandbox Code Playgroud)
它工作正常,但现在我需要别的东西.我想自定义客户端,以便每个请求(即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)
}
Run Code Online (Sandbox Code Playgroud)
但编译器不允许我使用我的自定义MyClient代替默认的自定义:
httpClient := &trackerapi.MyClient{}
// ERROR: Cannot use httpClient (type *MyClient) as type
//*http.Client.
githubClient := github.NewClient(httpClient)
Run Code Online (Sandbox Code Playgroud)
我是一个golang新手所以我的问题是:这是正确的方式来做我想要的,如果不是,推荐的方法是什么?
我可以在Golang中进行子类化吗?
简短回答:不.Go不是面向对象的,因此它没有类,因此子类化绝对是不可能的.
更长的回答:
您正在使用嵌入的正确轨道,但您将无法替换您的自定义客户端以获得任何期望的内容*http.Client.这就是Go接口的用途.但是标准库在这里不使用接口(它适用于某些有意义的事情).
根据确切需要,可能的另一种可能的方法是使用自定义传输,而不是自定义客户端.这确实使用了一个界面.您可以使用添加必要标头的自定义RoundTripper,这可以分配给*http.Client结构.
| 归档时间: |
|
| 查看次数: |
489 次 |
| 最近记录: |