How to use a custom go http client with the client side go code generated from openapi spec

564 Views Asked by At

I am working on generating an http client library from an API specification which is in open api format.

The command I am using to generate this is similar to this

openapi-generator generate -g go -i spec.yaml -o code-gen-go -p packageName=mypackage

This creates a struct like the one below in the generated code


type Configuration struct {
    Host             string            `json:"host,omitempty"`
    Scheme           string            `json:"scheme,omitempty"`
    DefaultHeader    map[string]string `json:"defaultHeader,omitempty"`
    UserAgent        string            `json:"userAgent,omitempty"`
    Debug            bool              `json:"debug,omitempty"`
    Servers          ServerConfigurations
    OperationServers map[string]ServerConfigurations
    HTTPClient       *http.Client
}

where HTTPClient field here will be used to make requests. Ideally, one should import this package, assign a client to the HTTPClient field and they should be able to make http requests via this.

But in my case, I have to use a custom library to make requests. Let's say my library is customHttp. I have to use this library to create a client of the type *customHttp.Client ( which is simply a client of type *http.Client but with some additional plugins ). How can I do this? Is it possible to do this without manually updating the auto-generated code?

I figure if I can get it to generate code that the type of HTTPClient is an interface that implements Do method, I will be able to assign my client with it? but I could not figure out how to do that either.

1

There are 1 best solutions below

0
On BEST ANSWER

It is possible to customise the generated code by modifying the Mustache templates for the Go client

Fetch the templates from the repository:

openapi-generator-cli author template -g go -o tmp/mygotemplates

You have now a local copy: modify the templates you want to customise, in this case, it is configuration.mustache.
Here you can import the code and modules you need, renaming existing code too if necessary. Add you custom Client library.

Go on and generate the code using your own templates:

openapi-generator-cli generate \
-i openapi.yaml \
-t tmp/mygotemplates \
-g go \
-p packageName=myPackage \
-o src

The generated code now includes your custom code and libraries. The approach gives the flexibility you need but comes at the price of maintaining a custom version of the templates (which you might need to update in future for example).

Here is an article about code generation as a reference.