2
我正在使用允許我更輕鬆地調用github API方法的Github客戶端。我可以在Golang中繼承和重新定義方法嗎?
這個庫可以讓我當我初始化它提供我自己的*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新手,所以我的問題是:這是做什麼我想和正確的方式,如果不是,有什麼建議的方法?