I am trying to generate an http client library based on the API specification of the Open API format.
The command I used to generate it is similar to this
openapi-generator generate-g go -i spec.yaml -o code-gen-go -p packagename=mypackage
This will create a structure similar to the following 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 }
The httpclient
field will be used to make the request. Ideally, this package should be imported, clients assigned to the httpclient
field, and they should be able to make http requests through this.
But in my case, I have to use a custom library to make the request. Let's say my library is customhttp
. I have to use this library to create a *customhttp.client
type client (which is just a *http.client
type client but with some additional plugins). How can I do this? Is it possible to do this without manually updating the automatically generated code?
I guess if I could get it to generate code that the type of httpclient
is an interface that implements the do
method, I would be able to allocate my client with it? But I don't know what to do either.
can be modified by go client
Get the template from the repository:
openapi-generator-cli author template -g go -o tmp/mygotemplates
You now have a local copy: modify the template you want to customize, in this case configuration.mustache
.
Here you can import the required code and modules and rename existing code if necessary. Add your custom client library.
Continue using your own template to generate code:
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. This approach provides the flexibility you need, but at the cost of maintaining a customized version of the template (which you may need to update in the future, for example).
This is an article about code generation as a reference.
The above is the detailed content of How to use a custom go http client with client go code generated from the openapi specification. For more information, please follow other related articles on the PHP Chinese website!