dongzhent208577 2017-04-02 20:10
浏览 159
已采纳

我可以在Golang中继承并重新定义方法吗?

I'm using a Github Client that allows me to call github API methods more easily.

This library allows me to provide my own *http.Client when I initialize it:

httpClient := &http.Client{}
githubClient := github.NewClient(httpClient)

It works fine but now I need something else. I want to customize the Client so that every request (i.e. the Do method) gets a custom header added.

I've read a bit about embedding and this is what I've tried so far:

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)

}

But the compiler does not let me use my custom MyClient in place of the default one:

httpClient := &trackerapi.MyClient{}

// ERROR: Cannot use httpClient (type *MyClient) as type 
//*http.Client. 
githubClient := github.NewClient(httpClient)

I'm a bit of a golang newbie so my question is: Is this the right way to do what I want to and, if not, what's the recommended approach?

  • 写回答

1条回答 默认 最新

  • duandi5328 2017-04-02 20:22
    关注

    Can I subclass ... in Golang?

    Short answer: No. Go is not object oriented, therefore it has no classes, therefore subclassing is categorically an impossibility.

    Longer answer:

    You're on the right track with embedding, but you won't be able to substitute your custom client for anything that expects an *http.Client. This is what Go interfaces are for. But the standard library doesn't use an interface here (it does for some things, where it makes sense).

    Another possible approach which may, depending on exact needs, work, is to use a custom transport, rather than a custom client. This does use an interface. You may be able to use a custom RoundTripper that adds the necessary headers, and this you can assign to an *http.Client struct.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改
  • ¥15 Windows 系统cmd后提示“加载用户设置时遇到错误”
  • ¥50 vue router 动态路由问题
  • ¥15 关于#.net#的问题:End Function
  • ¥15 无法import pycausal
  • ¥15 VS2022创建MVC framework提示:预安装的程序包具有对缺少的注册表值的引用
  • ¥15 weditor无法连接模拟器Local server not started, start with?
  • ¥20 6-3 String类定义
  • ¥15 嵌入式--定时器使用