Can I subclass and override a method in Golang?

I am using the Github client which makes it easier for me to use the github API methods.

This library allows me to provide my own *http.Client

when I initialize it:

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

      

It works great, but now I need something else. I want to configure the client so that every request (i.e. Method Do

) will add the added custom header.

I read a bit about nesting and this is what I have 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 won't let me use my own MyClient

instead of the standard one:

httpClient := &trackerapi.MyClient{}

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

      

I'm a bit new to golang, so my question is, am I doing what I want the right way, and if not, what's the recommended approach?

+3


source to share


1 answer


Can I subclass ... in Golang?

Short answer: No. Go is not object oriented, so it has no classes, so subclassing is categorically impossible.

Longer answer:



You're on the right track with an investment, but you won't be able to replace your custom client with whatever expects *http.Client

. This requires Go interfaces. But the standard library does not use an interface here (it does for some things where it makes sense).

Another possible approach that may work, depending on your specific needs, is to use a custom transport rather than a custom client. It uses the interface. You can use a custom RoundTripper that adds the required headers and this can be assigned to the structure *http.Client

.

+6


source







All Articles