我可以在 Golang 中子类化并重新定义一个方法吗?
Can I subclass and redefine a method in Golang?
我正在使用 Github 客户端,它允许我更轻松地调用 github API 方法。
这个库允许我在初始化时提供我自己的*http.Client
:
httpClient := &http.Client{}
githubClient := github.NewClient(httpClient)
它工作正常,但现在我需要别的东西。我想自定义客户端,以便每个请求(即 Do
方法)都添加自定义 header。
我已经阅读了一些关于 嵌入 的内容,这是我目前尝试过的方法:
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 新手所以我的问题是:这是做我想做的事情的正确方法吗?如果不是,推荐的方法是什么?
Can I subclass ... in Golang?
简短回答:不。Go 不是 object 导向的,因此它没有 类,因此子类化绝对是不可能的。
更长的答案:
您在嵌入方面走在了正确的轨道上,但是您将无法用您的自定义客户端替换任何需要 *http.Client
的内容。这就是 Go 接口的用途。但是标准库在这里不使用接口(它在某些有意义的地方使用)。
根据具体需要,另一种可行的方法是使用自定义传输,而不是自定义客户端。这确实使用了一个接口。您可以使用添加必要的 headers 的自定义 RoundTripper,并且您可以将其分配给 *http.Client
结构。
我正在使用 Github 客户端,它允许我更轻松地调用 github API 方法。
这个库允许我在初始化时提供我自己的*http.Client
:
httpClient := &http.Client{}
githubClient := github.NewClient(httpClient)
它工作正常,但现在我需要别的东西。我想自定义客户端,以便每个请求(即 Do
方法)都添加自定义 header。
我已经阅读了一些关于 嵌入 的内容,这是我目前尝试过的方法:
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 新手所以我的问题是:这是做我想做的事情的正确方法吗?如果不是,推荐的方法是什么?
Can I subclass ... in Golang?
简短回答:不。Go 不是 object 导向的,因此它没有 类,因此子类化绝对是不可能的。
更长的答案:
您在嵌入方面走在了正确的轨道上,但是您将无法用您的自定义客户端替换任何需要 *http.Client
的内容。这就是 Go 接口的用途。但是标准库在这里不使用接口(它在某些有意义的地方使用)。
根据具体需要,另一种可行的方法是使用自定义传输,而不是自定义客户端。这确实使用了一个接口。您可以使用添加必要的 headers 的自定义 RoundTripper,并且您可以将其分配给 *http.Client
结构。