[go-experimental] Support selection and formatting of endpoint servers (#4755)

* [Go] Support server URLs in runtime

* [Go] Regenerate experimental clients

* Rename Url to URL

* Remove BaseBase from go-experimental
This commit is contained in:
Jiri Kuncar 2019-12-18 02:41:52 +01:00 committed by Jim Schubert
parent 83cb4206cd
commit 617904c876
23 changed files with 1040 additions and 246 deletions

View File

@ -34,6 +34,47 @@ Put the package under your project folder and add the following in import:
import sw "./{{packageName}}"
```
## Configuration of Server URL
Default configuration comes with `Servers` field that contains server objects as defined in the OpenAPI specification.
### Select Server Configuration
For using other server than the one defined on index 0 set context value `sw.ContextServerIndex` of type `int`.
```golang
ctx := context.WithValue(context.Background(), sw.ContextServerIndex, 1)
```
### Templated Server URL
Templated server URL is formatted using default variables from configuration or from context value `sw.ContextServerVariables` of type `map[string]string`.
```golang
ctx := context.WithValue(context.Background(), sw.ContextServerVariables, map[string]string{
"basePath": "v2",
})
```
Note, enum values are always validated and all unused variables are silently ignored.
### URLs Configuration per Operation
Each operation can use different server URL defined using `OperationServers` map in the `Configuration`.
An operation is uniquely identifield by `"{classname}Service.{nickname}"` string.
Similar rules for overriding default operation server index and variables applies by using `sw.ContextOperationServerIndices` and `sw.ContextOperationServerVariables` context maps.
```
ctx := context.WithValue(context.Background(), sw.ContextOperationServerIndices, map[string]int{
"{classname}Service.{nickname}": 2,
})
ctx = context.WithValue(context.Background(), sw.ContextOperationServerVariables, map[string]map[string]string{
"{classname}Service.{nickname}": {
"port": "8443",
},
})
```
## Documentation for API Endpoints
All URIs are relative to *{{basePath}}*

View File

@ -76,10 +76,13 @@ func (a *{{{classname}}}Service) {{{nickname}}}(ctx _context.Context{{#hasParams
{{/returnType}}
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "{{{path}}}"{{#pathParams}}
localVarPath = strings.Replace(localVarPath, "{"+"{{baseName}}"+"}", _neturl.QueryEscape(parameterToString({{paramName}}, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}")) , -1)
{{/pathParams}}
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "{{{classname}}}Service.{{{nickname}}}")
if err != nil {
return {{#returnType}}localVarReturnValue, {{/returnType}}nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "{{{path}}}"{{#pathParams}}
localVarPath = strings.Replace(localVarPath, "{"+"{{baseName}}"+"}", _neturl.QueryEscape(parameterToString({{paramName}}, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}")) , -1){{/pathParams}}
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}

View File

@ -186,11 +186,6 @@ func (c *APIClient) callAPI(request *http.Request) (*http.Response, error) {
return resp, err
}
// ChangeBasePath changes base path to allow switching to mocks
func (c *APIClient) ChangeBasePath(path string) {
c.cfg.BasePath = path
}
// Allow modification of underlying config for alternate implementations and testing
// Caution: modifying the configuration while live can cause data races and potentially unwanted behavior
func (c *APIClient) GetConfig() *Configuration {

View File

@ -2,6 +2,7 @@
package {{packageName}}
import (
"context"
"fmt"
"net/http"
"strings"
@ -29,6 +30,18 @@ var (
// ContextAPIKeys takes a string apikey as authentication for the request
ContextAPIKeys = contextKey("apiKeys")
// ContextServerIndex uses a server configuration from the index.
ContextServerIndex = contextKey("serverIndex")
// ContextOperationServerIndices uses a server configuration from the index mapping.
ContextOperationServerIndices = contextKey("serverOperationIndices")
// ContextServerVariables overrides a server configuration variables.
ContextServerVariables = contextKey("serverVariables")
// ContextOperationServerVariables overrides a server configuration variables using operation specific values.
ContextOperationServerVariables = contextKey("serverOperationVariables")
)
// BasicAuth provides basic http authentication to a request passed via context using ContextBasicAuth
@ -52,35 +65,38 @@ type ServerVariable struct {
// ServerConfiguration stores the information about a server
type ServerConfiguration struct {
Url string
URL string
Description string
Variables map[string]ServerVariable
}
// ServerConfigurations stores multiple ServerConfiguration items
type ServerConfigurations []ServerConfiguration
// Configuration stores the configuration of the API client
type Configuration struct {
BasePath string `json:"basePath,omitempty"`
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 []ServerConfiguration
HTTPClient *http.Client
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
}
// NewConfiguration returns a new Configuration object
func NewConfiguration() *Configuration {
cfg := &Configuration{
BasePath: "{{{basePath}}}",
DefaultHeader: make(map[string]string),
UserAgent: "{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}OpenAPI-Generator/{{{packageVersion}}}/go{{/httpUserAgent}}",
Debug: false,
DefaultHeader: make(map[string]string),
UserAgent: "{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}OpenAPI-Generator/{{{packageVersion}}}/go{{/httpUserAgent}}",
Debug: false,
{{#servers}}
{{#-first}}
Servers: []ServerConfiguration{{
Servers: ServerConfigurations{
{{/-first}}
Url: "{{{url}}}",
{
URL: "{{{url}}}",
Description: "{{{description}}}{{^description}}No description provided{{/description}}",
{{#variables}}
{{#-first}}
@ -108,6 +124,49 @@ func NewConfiguration() *Configuration {
},
{{/-last}}
{{/servers}}
{{#apiInfo}}
OperationServers: map[string]ServerConfigurations{
{{#apis}}
{{#operations}}
{{#operation}}
{{#servers}}
{{#-first}}
"{{{classname}}}Service.{{{nickname}}}": {
{{/-first}}
{
URL: "{{{url}}}",
Description: "{{{description}}}{{^description}}No description provided{{/description}}",
{{#variables}}
{{#-first}}
Variables: map[string]ServerVariable{
{{/-first}}
"{{{name}}}": ServerVariable{
Description: "{{{description}}}{{^description}}No description provided{{/description}}",
DefaultValue: "{{{defaultValue}}}",
{{#enumValues}}
{{#-first}}
EnumValues: []string{
{{/-first}}
"{{{.}}}",
{{#-last}}
},
{{/-last}}
{{/enumValues}}
},
{{#-last}}
},
{{/-last}}
{{/variables}}
},
{{#-last}}
},
{{/-last}}
{{/servers}}
{{/operation}}
{{/operations}}
{{/apis}}
},
{{/apiInfo}}
}
return cfg
}
@ -117,13 +176,13 @@ func (c *Configuration) AddDefaultHeader(key string, value string) {
c.DefaultHeader[key] = value
}
// ServerUrl returns URL based on server settings
func (c *Configuration) ServerUrl(index int, variables map[string]string) (string, error) {
if index < 0 || len(c.Servers) <= index {
return "", fmt.Errorf("Index %v out of range %v", index, len(c.Servers) - 1)
// URL formats template on a index using given variables
func (sc ServerConfigurations) URL(index int, variables map[string]string) (string, error) {
if index < 0 || len(sc) <= index {
return "", fmt.Errorf("Index %v out of range %v", index, len(sc)-1)
}
server := c.Servers[index]
url := server.Url
server := sc[index]
url := server.URL
// go through variables and replace placeholders
for name, variable := range server.Variables {
@ -144,3 +203,84 @@ func (c *Configuration) ServerUrl(index int, variables map[string]string) (strin
}
return url, nil
}
// ServerURL returns URL based on server settings
func (c *Configuration) ServerURL(index int, variables map[string]string) (string, error) {
return c.Servers.URL(index, variables)
}
func getServerIndex(ctx context.Context) (int, error) {
si := ctx.Value(ContextServerIndex)
if si != nil {
if index, ok := si.(int); ok {
return index, nil
}
return 0, reportError("Invalid type %T should be int", si)
}
return 0, nil
}
func getServerOperationIndex(ctx context.Context, endpoint string) (int, error) {
osi := ctx.Value(ContextOperationServerIndices)
if osi != nil {
if operationIndices, ok := osi.(map[string]int); !ok {
return 0, reportError("Invalid type %T should be map[string]int", osi)
} else {
index, ok := operationIndices[endpoint]
if ok {
return index, nil
}
}
}
return getServerIndex(ctx)
}
func getServerVariables(ctx context.Context) (map[string]string, error) {
sv := ctx.Value(ContextServerVariables)
if sv != nil {
if variables, ok := sv.(map[string]string); ok {
return variables, nil
}
return nil, reportError("ctx value of ContextServerVariables has invalid type %T should be map[string]string", sv)
}
return nil, nil
}
func getServerOperationVariables(ctx context.Context, endpoint string) (map[string]string, error) {
osv := ctx.Value(ContextOperationServerVariables)
if osv != nil {
if operationVariables, ok := osv.(map[string]map[string]string); !ok {
return nil, reportError("ctx value of ContextOperationServerVariables has invalid type %T should be map[string]map[string]string", osv)
} else {
variables, ok := operationVariables[endpoint]
if ok {
return variables, nil
}
}
}
return getServerVariables(ctx)
}
// ServerURLWithContext returns a new server URL given an endpoint
func (c *Configuration) ServerURLWithContext(ctx context.Context, endpoint string) (string, error) {
sc, ok := c.OperationServers[endpoint]
if !ok {
sc = c.Servers
}
if ctx == nil {
return sc.URL(0, nil)
}
index, err := getServerOperationIndex(ctx, endpoint)
if err != nil {
return "", err
}
variables, err := getServerOperationVariables(ctx, endpoint)
if err != nil {
return "", err
}
return sc.URL(index, variables)
}

View File

@ -26,6 +26,47 @@ Put the package under your project folder and add the following in import:
import sw "./petstore"
```
## Configuration of Server URL
Default configuration comes with `Servers` field that contains server objects as defined in the OpenAPI specification.
### Select Server Configuration
For using other server than the one defined on index 0 set context value `sw.ContextServerIndex` of type `int`.
```golang
ctx := context.WithValue(context.Background(), sw.ContextServerIndex, 1)
```
### Templated Server URL
Templated server URL is formatted using default variables from configuration or from context value `sw.ContextServerVariables` of type `map[string]string`.
```golang
ctx := context.WithValue(context.Background(), sw.ContextServerVariables, map[string]string{
"basePath": "v2",
})
```
Note, enum values are always validated and all unused variables are silently ignored.
### URLs Configuration per Operation
Each operation can use different server URL defined using `OperationServers` map in the `Configuration`.
An operation is uniquely identifield by `"{classname}Service.{nickname}"` string.
Similar rules for overriding default operation server index and variables applies by using `sw.ContextOperationServerIndices` and `sw.ContextOperationServerVariables` context maps.
```
ctx := context.WithValue(context.Background(), sw.ContextOperationServerIndices, map[string]int{
"{classname}Service.{nickname}": 2,
})
ctx = context.WithValue(context.Background(), sw.ContextOperationServerVariables, map[string]map[string]string{
"{classname}Service.{nickname}": {
"port": "8443",
},
})
```
## Documentation for API Endpoints
All URIs are relative to *http://petstore.swagger.io:80/v2*

View File

@ -41,8 +41,13 @@ func (a *AnotherFakeApiService) Call123TestSpecialTags(ctx _context.Context, bod
localVarReturnValue Client
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/another-fake/dummy"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "AnotherFakeApiService.Call123TestSpecialTags")
if err != nil {
return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/another-fake/dummy"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}

View File

@ -42,8 +42,13 @@ func (a *FakeApiService) CreateXmlItem(ctx _context.Context, xmlItem XmlItem) (*
localVarFileBytes []byte
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/fake/create_xml_item"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeApiService.CreateXmlItem")
if err != nil {
return nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/fake/create_xml_item"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
@ -117,8 +122,13 @@ func (a *FakeApiService) FakeOuterBooleanSerialize(ctx _context.Context, localVa
localVarReturnValue bool
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/fake/outer/boolean"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeApiService.FakeOuterBooleanSerialize")
if err != nil {
return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/fake/outer/boolean"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
@ -213,8 +223,13 @@ func (a *FakeApiService) FakeOuterCompositeSerialize(ctx _context.Context, local
localVarReturnValue OuterComposite
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/fake/outer/composite"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeApiService.FakeOuterCompositeSerialize")
if err != nil {
return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/fake/outer/composite"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
@ -313,8 +328,13 @@ func (a *FakeApiService) FakeOuterNumberSerialize(ctx _context.Context, localVar
localVarReturnValue float32
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/fake/outer/number"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeApiService.FakeOuterNumberSerialize")
if err != nil {
return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/fake/outer/number"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
@ -409,8 +429,13 @@ func (a *FakeApiService) FakeOuterStringSerialize(ctx _context.Context, localVar
localVarReturnValue string
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/fake/outer/string"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeApiService.FakeOuterStringSerialize")
if err != nil {
return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/fake/outer/string"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
@ -497,8 +522,13 @@ func (a *FakeApiService) TestBodyWithFileSchema(ctx _context.Context, body FileS
localVarFileBytes []byte
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/fake/body-with-file-schema"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeApiService.TestBodyWithFileSchema")
if err != nil {
return nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/fake/body-with-file-schema"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
@ -564,8 +594,13 @@ func (a *FakeApiService) TestBodyWithQueryParams(ctx _context.Context, query str
localVarFileBytes []byte
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/fake/body-with-query-params"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeApiService.TestBodyWithQueryParams")
if err != nil {
return nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/fake/body-with-query-params"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
@ -634,8 +669,13 @@ func (a *FakeApiService) TestClientModel(ctx _context.Context, body Client) (Cli
localVarReturnValue Client
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/fake"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeApiService.TestClientModel")
if err != nil {
return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/fake"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
@ -747,8 +787,13 @@ func (a *FakeApiService) TestEndpointParameters(ctx _context.Context, number flo
localVarFileBytes []byte
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/fake"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeApiService.TestEndpointParameters")
if err != nil {
return nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/fake"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
@ -890,8 +935,13 @@ func (a *FakeApiService) TestEnumParameters(ctx _context.Context, localVarOption
localVarFileBytes []byte
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/fake"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeApiService.TestEnumParameters")
if err != nil {
return nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/fake"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
@ -992,8 +1042,13 @@ func (a *FakeApiService) TestGroupParameters(ctx _context.Context, requiredStrin
localVarFileBytes []byte
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/fake"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeApiService.TestGroupParameters")
if err != nil {
return nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/fake"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
@ -1068,8 +1123,13 @@ func (a *FakeApiService) TestInlineAdditionalProperties(ctx _context.Context, pa
localVarFileBytes []byte
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/fake/inline-additionalProperties"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeApiService.TestInlineAdditionalProperties")
if err != nil {
return nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/fake/inline-additionalProperties"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
@ -1135,8 +1195,13 @@ func (a *FakeApiService) TestJsonFormData(ctx _context.Context, param string, pa
localVarFileBytes []byte
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/fake/jsonFormData"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeApiService.TestJsonFormData")
if err != nil {
return nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/fake/jsonFormData"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
@ -1206,8 +1271,13 @@ func (a *FakeApiService) TestQueryParameterCollectionFormat(ctx _context.Context
localVarFileBytes []byte
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/fake/test-query-paramters"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeApiService.TestQueryParameterCollectionFormat")
if err != nil {
return nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/fake/test-query-paramters"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}

View File

@ -41,8 +41,13 @@ func (a *FakeClassnameTags123ApiService) TestClassname(ctx _context.Context, bod
localVarReturnValue Client
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/fake_classname_test"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeClassnameTags123ApiService.TestClassname")
if err != nil {
return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/fake_classname_test"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}

View File

@ -41,8 +41,13 @@ func (a *PetApiService) AddPet(ctx _context.Context, body Pet) (*_nethttp.Respon
localVarFileBytes []byte
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/pet"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "PetApiService.AddPet")
if err != nil {
return nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/pet"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
@ -114,8 +119,12 @@ func (a *PetApiService) DeletePet(ctx _context.Context, petId int64, localVarOpt
localVarFileBytes []byte
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/pet/{petId}"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "PetApiService.DeletePet")
if err != nil {
return nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/pet/{petId}"
localVarPath = strings.Replace(localVarPath, "{"+"petId"+"}", _neturl.QueryEscape(parameterToString(petId, "")) , -1)
localVarHeaderParams := make(map[string]string)
@ -186,8 +195,13 @@ func (a *PetApiService) FindPetsByStatus(ctx _context.Context, status []string)
localVarReturnValue []Pet
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/pet/findByStatus"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "PetApiService.FindPetsByStatus")
if err != nil {
return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/pet/findByStatus"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
@ -273,8 +287,13 @@ func (a *PetApiService) FindPetsByTags(ctx _context.Context, tags []string) ([]P
localVarReturnValue []Pet
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/pet/findByTags"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "PetApiService.FindPetsByTags")
if err != nil {
return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/pet/findByTags"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
@ -360,8 +379,12 @@ func (a *PetApiService) GetPetById(ctx _context.Context, petId int64) (Pet, *_ne
localVarReturnValue Pet
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/pet/{petId}"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "PetApiService.GetPetById")
if err != nil {
return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/pet/{petId}"
localVarPath = strings.Replace(localVarPath, "{"+"petId"+"}", _neturl.QueryEscape(parameterToString(petId, "")) , -1)
localVarHeaderParams := make(map[string]string)
@ -459,8 +482,13 @@ func (a *PetApiService) UpdatePet(ctx _context.Context, body Pet) (*_nethttp.Res
localVarFileBytes []byte
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/pet"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "PetApiService.UpdatePet")
if err != nil {
return nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/pet"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
@ -534,8 +562,12 @@ func (a *PetApiService) UpdatePetWithForm(ctx _context.Context, petId int64, loc
localVarFileBytes []byte
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/pet/{petId}"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "PetApiService.UpdatePetWithForm")
if err != nil {
return nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/pet/{petId}"
localVarPath = strings.Replace(localVarPath, "{"+"petId"+"}", _neturl.QueryEscape(parameterToString(petId, "")) , -1)
localVarHeaderParams := make(map[string]string)
@ -617,8 +649,12 @@ func (a *PetApiService) UploadFile(ctx _context.Context, petId int64, localVarOp
localVarReturnValue ApiResponse
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/pet/{petId}/uploadImage"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "PetApiService.UploadFile")
if err != nil {
return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/pet/{petId}/uploadImage"
localVarPath = strings.Replace(localVarPath, "{"+"petId"+"}", _neturl.QueryEscape(parameterToString(petId, "")) , -1)
localVarHeaderParams := make(map[string]string)
@ -729,8 +765,12 @@ func (a *PetApiService) UploadFileWithRequiredFile(ctx _context.Context, petId i
localVarReturnValue ApiResponse
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/fake/{petId}/uploadImageWithRequiredFile"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "PetApiService.UploadFileWithRequiredFile")
if err != nil {
return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/fake/{petId}/uploadImageWithRequiredFile"
localVarPath = strings.Replace(localVarPath, "{"+"petId"+"}", _neturl.QueryEscape(parameterToString(petId, "")) , -1)
localVarHeaderParams := make(map[string]string)

View File

@ -40,8 +40,12 @@ func (a *StoreApiService) DeleteOrder(ctx _context.Context, orderId string) (*_n
localVarFileBytes []byte
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/store/order/{order_id}"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "StoreApiService.DeleteOrder")
if err != nil {
return nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/store/order/{order_id}"
localVarPath = strings.Replace(localVarPath, "{"+"order_id"+"}", _neturl.QueryEscape(parameterToString(orderId, "")) , -1)
localVarHeaderParams := make(map[string]string)
@ -108,8 +112,13 @@ func (a *StoreApiService) GetInventory(ctx _context.Context) (map[string]int32,
localVarReturnValue map[string]int32
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/store/inventory"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "StoreApiService.GetInventory")
if err != nil {
return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/store/inventory"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
@ -207,8 +216,12 @@ func (a *StoreApiService) GetOrderById(ctx _context.Context, orderId int64) (Ord
localVarReturnValue Order
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/store/order/{order_id}"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "StoreApiService.GetOrderById")
if err != nil {
return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/store/order/{order_id}"
localVarPath = strings.Replace(localVarPath, "{"+"order_id"+"}", _neturl.QueryEscape(parameterToString(orderId, "")) , -1)
localVarHeaderParams := make(map[string]string)
@ -300,8 +313,13 @@ func (a *StoreApiService) PlaceOrder(ctx _context.Context, body Order) (Order, *
localVarReturnValue Order
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/store/order"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "StoreApiService.PlaceOrder")
if err != nil {
return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/store/order"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}

View File

@ -40,8 +40,13 @@ func (a *UserApiService) CreateUser(ctx _context.Context, body User) (*_nethttp.
localVarFileBytes []byte
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/user"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "UserApiService.CreateUser")
if err != nil {
return nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/user"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
@ -106,8 +111,13 @@ func (a *UserApiService) CreateUsersWithArrayInput(ctx _context.Context, body []
localVarFileBytes []byte
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/user/createWithArray"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "UserApiService.CreateUsersWithArrayInput")
if err != nil {
return nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/user/createWithArray"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
@ -172,8 +182,13 @@ func (a *UserApiService) CreateUsersWithListInput(ctx _context.Context, body []U
localVarFileBytes []byte
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/user/createWithList"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "UserApiService.CreateUsersWithListInput")
if err != nil {
return nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/user/createWithList"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
@ -239,8 +254,12 @@ func (a *UserApiService) DeleteUser(ctx _context.Context, username string) (*_ne
localVarFileBytes []byte
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/user/{username}"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "UserApiService.DeleteUser")
if err != nil {
return nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/user/{username}"
localVarPath = strings.Replace(localVarPath, "{"+"username"+"}", _neturl.QueryEscape(parameterToString(username, "")) , -1)
localVarHeaderParams := make(map[string]string)
@ -307,8 +326,12 @@ func (a *UserApiService) GetUserByName(ctx _context.Context, username string) (U
localVarReturnValue User
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/user/{username}"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "UserApiService.GetUserByName")
if err != nil {
return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/user/{username}"
localVarPath = strings.Replace(localVarPath, "{"+"username"+"}", _neturl.QueryEscape(parameterToString(username, "")) , -1)
localVarHeaderParams := make(map[string]string)
@ -395,8 +418,13 @@ func (a *UserApiService) LoginUser(ctx _context.Context, username string, passwo
localVarReturnValue string
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/user/login"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "UserApiService.LoginUser")
if err != nil {
return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/user/login"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
@ -479,8 +507,13 @@ func (a *UserApiService) LogoutUser(ctx _context.Context) (*_nethttp.Response, e
localVarFileBytes []byte
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/user/logout"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "UserApiService.LogoutUser")
if err != nil {
return nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/user/logout"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
@ -545,8 +578,12 @@ func (a *UserApiService) UpdateUser(ctx _context.Context, username string, body
localVarFileBytes []byte
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/user/{username}"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "UserApiService.UpdateUser")
if err != nil {
return nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/user/{username}"
localVarPath = strings.Replace(localVarPath, "{"+"username"+"}", _neturl.QueryEscape(parameterToString(username, "")) , -1)
localVarHeaderParams := make(map[string]string)

View File

@ -197,11 +197,6 @@ func (c *APIClient) callAPI(request *http.Request) (*http.Response, error) {
return resp, err
}
// ChangeBasePath changes base path to allow switching to mocks
func (c *APIClient) ChangeBasePath(path string) {
c.cfg.BasePath = path
}
// Allow modification of underlying config for alternate implementations and testing
// Caution: modifying the configuration while live can cause data races and potentially unwanted behavior
func (c *APIClient) GetConfig() *Configuration {

View File

@ -10,6 +10,7 @@
package petstore
import (
"context"
"fmt"
"net/http"
"strings"
@ -37,6 +38,18 @@ var (
// ContextAPIKeys takes a string apikey as authentication for the request
ContextAPIKeys = contextKey("apiKeys")
// ContextServerIndex uses a server configuration from the index.
ContextServerIndex = contextKey("serverIndex")
// ContextOperationServerIndices uses a server configuration from the index mapping.
ContextOperationServerIndices = contextKey("serverOperationIndices")
// ContextServerVariables overrides a server configuration variables.
ContextServerVariables = contextKey("serverVariables")
// ContextOperationServerVariables overrides a server configuration variables using operation specific values.
ContextOperationServerVariables = contextKey("serverOperationVariables")
)
// BasicAuth provides basic http authentication to a request passed via context using ContextBasicAuth
@ -60,35 +73,40 @@ type ServerVariable struct {
// ServerConfiguration stores the information about a server
type ServerConfiguration struct {
Url string
URL string
Description string
Variables map[string]ServerVariable
}
// ServerConfigurations stores multiple ServerConfiguration items
type ServerConfigurations []ServerConfiguration
// Configuration stores the configuration of the API client
type Configuration struct {
BasePath string `json:"basePath,omitempty"`
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 []ServerConfiguration
HTTPClient *http.Client
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
}
// NewConfiguration returns a new Configuration object
func NewConfiguration() *Configuration {
cfg := &Configuration{
BasePath: "http://petstore.swagger.io:80/v2",
DefaultHeader: make(map[string]string),
UserAgent: "OpenAPI-Generator/1.0.0/go",
Debug: false,
Servers: []ServerConfiguration{{
Url: "http://petstore.swagger.io:80/v2",
DefaultHeader: make(map[string]string),
UserAgent: "OpenAPI-Generator/1.0.0/go",
Debug: false,
Servers: ServerConfigurations{
{
URL: "http://petstore.swagger.io:80/v2",
Description: "No description provided",
},
},
OperationServers: map[string]ServerConfigurations{
},
}
return cfg
}
@ -98,13 +116,13 @@ func (c *Configuration) AddDefaultHeader(key string, value string) {
c.DefaultHeader[key] = value
}
// ServerUrl returns URL based on server settings
func (c *Configuration) ServerUrl(index int, variables map[string]string) (string, error) {
if index < 0 || len(c.Servers) <= index {
return "", fmt.Errorf("Index %v out of range %v", index, len(c.Servers) - 1)
// URL formats template on a index using given variables
func (sc ServerConfigurations) URL(index int, variables map[string]string) (string, error) {
if index < 0 || len(sc) <= index {
return "", fmt.Errorf("Index %v out of range %v", index, len(sc)-1)
}
server := c.Servers[index]
url := server.Url
server := sc[index]
url := server.URL
// go through variables and replace placeholders
for name, variable := range server.Variables {
@ -125,3 +143,84 @@ func (c *Configuration) ServerUrl(index int, variables map[string]string) (strin
}
return url, nil
}
// ServerURL returns URL based on server settings
func (c *Configuration) ServerURL(index int, variables map[string]string) (string, error) {
return c.Servers.URL(index, variables)
}
func getServerIndex(ctx context.Context) (int, error) {
si := ctx.Value(ContextServerIndex)
if si != nil {
if index, ok := si.(int); ok {
return index, nil
}
return 0, reportError("Invalid type %T should be int", si)
}
return 0, nil
}
func getServerOperationIndex(ctx context.Context, endpoint string) (int, error) {
osi := ctx.Value(ContextOperationServerIndices)
if osi != nil {
if operationIndices, ok := osi.(map[string]int); !ok {
return 0, reportError("Invalid type %T should be map[string]int", osi)
} else {
index, ok := operationIndices[endpoint]
if ok {
return index, nil
}
}
}
return getServerIndex(ctx)
}
func getServerVariables(ctx context.Context) (map[string]string, error) {
sv := ctx.Value(ContextServerVariables)
if sv != nil {
if variables, ok := sv.(map[string]string); ok {
return variables, nil
}
return nil, reportError("ctx value of ContextServerVariables has invalid type %T should be map[string]string", sv)
}
return nil, nil
}
func getServerOperationVariables(ctx context.Context, endpoint string) (map[string]string, error) {
osv := ctx.Value(ContextOperationServerVariables)
if osv != nil {
if operationVariables, ok := osv.(map[string]map[string]string); !ok {
return nil, reportError("ctx value of ContextOperationServerVariables has invalid type %T should be map[string]map[string]string", osv)
} else {
variables, ok := operationVariables[endpoint]
if ok {
return variables, nil
}
}
}
return getServerVariables(ctx)
}
// ServerURLWithContext returns a new server URL given an endpoint
func (c *Configuration) ServerURLWithContext(ctx context.Context, endpoint string) (string, error) {
sc, ok := c.OperationServers[endpoint]
if !ok {
sc = c.Servers
}
if ctx == nil {
return sc.URL(0, nil)
}
index, err := getServerOperationIndex(ctx, endpoint)
if err != nil {
return "", err
}
variables, err := getServerOperationVariables(ctx, endpoint)
if err != nil {
return "", err
}
return sc.URL(index, variables)
}

View File

@ -26,6 +26,47 @@ Put the package under your project folder and add the following in import:
import sw "./openapi"
```
## Configuration of Server URL
Default configuration comes with `Servers` field that contains server objects as defined in the OpenAPI specification.
### Select Server Configuration
For using other server than the one defined on index 0 set context value `sw.ContextServerIndex` of type `int`.
```golang
ctx := context.WithValue(context.Background(), sw.ContextServerIndex, 1)
```
### Templated Server URL
Templated server URL is formatted using default variables from configuration or from context value `sw.ContextServerVariables` of type `map[string]string`.
```golang
ctx := context.WithValue(context.Background(), sw.ContextServerVariables, map[string]string{
"basePath": "v2",
})
```
Note, enum values are always validated and all unused variables are silently ignored.
### URLs Configuration per Operation
Each operation can use different server URL defined using `OperationServers` map in the `Configuration`.
An operation is uniquely identifield by `"{classname}Service.{nickname}"` string.
Similar rules for overriding default operation server index and variables applies by using `sw.ContextOperationServerIndices` and `sw.ContextOperationServerVariables` context maps.
```
ctx := context.WithValue(context.Background(), sw.ContextOperationServerIndices, map[string]int{
"{classname}Service.{nickname}": 2,
})
ctx = context.WithValue(context.Background(), sw.ContextOperationServerVariables, map[string]map[string]string{
"{classname}Service.{nickname}": {
"port": "8443",
},
})
```
## Documentation for API Endpoints
All URIs are relative to *http://petstore.swagger.io:80/v2*

View File

@ -41,8 +41,12 @@ func (a *AnotherFakeApiService) Call123TestSpecialTags(ctx _context.Context, cli
localVarReturnValue Client
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/another-fake/dummy"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "AnotherFakeApiService.Call123TestSpecialTags")
if err != nil {
return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/another-fake/dummy"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}

View File

@ -39,8 +39,12 @@ func (a *DefaultApiService) FooGet(ctx _context.Context) (InlineResponseDefault,
localVarReturnValue InlineResponseDefault
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/foo"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "DefaultApiService.FooGet")
if err != nil {
return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/foo"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}

View File

@ -42,8 +42,12 @@ func (a *FakeApiService) FakeHealthGet(ctx _context.Context) (HealthCheckResult,
localVarReturnValue HealthCheckResult
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/fake/health"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeApiService.FakeHealthGet")
if err != nil {
return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/fake/health"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
@ -134,8 +138,12 @@ func (a *FakeApiService) FakeOuterBooleanSerialize(ctx _context.Context, localVa
localVarReturnValue bool
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/fake/outer/boolean"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeApiService.FakeOuterBooleanSerialize")
if err != nil {
return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/fake/outer/boolean"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
@ -231,8 +239,12 @@ func (a *FakeApiService) FakeOuterCompositeSerialize(ctx _context.Context, local
localVarReturnValue OuterComposite
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/fake/outer/composite"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeApiService.FakeOuterCompositeSerialize")
if err != nil {
return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/fake/outer/composite"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
@ -332,8 +344,12 @@ func (a *FakeApiService) FakeOuterNumberSerialize(ctx _context.Context, localVar
localVarReturnValue float32
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/fake/outer/number"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeApiService.FakeOuterNumberSerialize")
if err != nil {
return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/fake/outer/number"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
@ -429,8 +445,12 @@ func (a *FakeApiService) FakeOuterStringSerialize(ctx _context.Context, localVar
localVarReturnValue string
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/fake/outer/string"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeApiService.FakeOuterStringSerialize")
if err != nil {
return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/fake/outer/string"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
@ -518,8 +538,12 @@ func (a *FakeApiService) TestBodyWithFileSchema(ctx _context.Context, fileSchema
localVarFileBytes []byte
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/fake/body-with-file-schema"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeApiService.TestBodyWithFileSchema")
if err != nil {
return nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/fake/body-with-file-schema"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
@ -586,8 +610,12 @@ func (a *FakeApiService) TestBodyWithQueryParams(ctx _context.Context, query str
localVarFileBytes []byte
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/fake/body-with-query-params"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeApiService.TestBodyWithQueryParams")
if err != nil {
return nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/fake/body-with-query-params"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
@ -657,8 +685,12 @@ func (a *FakeApiService) TestClientModel(ctx _context.Context, client Client) (C
localVarReturnValue Client
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/fake"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeApiService.TestClientModel")
if err != nil {
return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/fake"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
@ -771,8 +803,12 @@ func (a *FakeApiService) TestEndpointParameters(ctx _context.Context, number flo
localVarFileBytes []byte
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/fake"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeApiService.TestEndpointParameters")
if err != nil {
return nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/fake"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
@ -915,8 +951,12 @@ func (a *FakeApiService) TestEnumParameters(ctx _context.Context, localVarOption
localVarFileBytes []byte
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/fake"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeApiService.TestEnumParameters")
if err != nil {
return nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/fake"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
@ -1026,8 +1066,12 @@ func (a *FakeApiService) TestGroupParameters(ctx _context.Context, requiredStrin
localVarFileBytes []byte
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/fake"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeApiService.TestGroupParameters")
if err != nil {
return nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/fake"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
@ -1103,8 +1147,12 @@ func (a *FakeApiService) TestInlineAdditionalProperties(ctx _context.Context, re
localVarFileBytes []byte
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/fake/inline-additionalProperties"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeApiService.TestInlineAdditionalProperties")
if err != nil {
return nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/fake/inline-additionalProperties"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
@ -1171,8 +1219,12 @@ func (a *FakeApiService) TestJsonFormData(ctx _context.Context, param string, pa
localVarFileBytes []byte
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/fake/jsonFormData"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeApiService.TestJsonFormData")
if err != nil {
return nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/fake/jsonFormData"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
@ -1243,8 +1295,12 @@ func (a *FakeApiService) TestQueryParameterCollectionFormat(ctx _context.Context
localVarFileBytes []byte
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/fake/test-query-paramters"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeApiService.TestQueryParameterCollectionFormat")
if err != nil {
return nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/fake/test-query-paramters"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}

View File

@ -41,8 +41,12 @@ func (a *FakeClassnameTags123ApiService) TestClassname(ctx _context.Context, cli
localVarReturnValue Client
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/fake_classname_test"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeClassnameTags123ApiService.TestClassname")
if err != nil {
return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/fake_classname_test"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}

View File

@ -14,7 +14,6 @@ import (
_ioutil "io/ioutil"
_nethttp "net/http"
_neturl "net/url"
"fmt"
"strings"
"github.com/antihax/optional"
"os"
@ -42,8 +41,12 @@ func (a *PetApiService) AddPet(ctx _context.Context, pet Pet) (*_nethttp.Respons
localVarFileBytes []byte
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/pet"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "PetApiService.AddPet")
if err != nil {
return nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/pet"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
@ -116,9 +119,13 @@ func (a *PetApiService) DeletePet(ctx _context.Context, petId int64, localVarOpt
localVarFileBytes []byte
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/pet/{petId}"
localVarPath = strings.Replace(localVarPath, "{"+"petId"+"}", _neturl.QueryEscape(fmt.Sprintf("%v", petId)), -1)
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "PetApiService.DeletePet")
if err != nil {
return nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/pet/{petId}"
localVarPath = strings.Replace(localVarPath, "{"+"petId"+"}", _neturl.QueryEscape(parameterToString(petId, "")) , -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
@ -188,8 +195,12 @@ func (a *PetApiService) FindPetsByStatus(ctx _context.Context, status []string)
localVarReturnValue []Pet
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/pet/findByStatus"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "PetApiService.FindPetsByStatus")
if err != nil {
return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/pet/findByStatus"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
@ -276,8 +287,12 @@ func (a *PetApiService) FindPetsByTags(ctx _context.Context, tags []string) ([]P
localVarReturnValue []Pet
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/pet/findByTags"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "PetApiService.FindPetsByTags")
if err != nil {
return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/pet/findByTags"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
@ -364,9 +379,13 @@ func (a *PetApiService) GetPetById(ctx _context.Context, petId int64) (Pet, *_ne
localVarReturnValue Pet
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/pet/{petId}"
localVarPath = strings.Replace(localVarPath, "{"+"petId"+"}", _neturl.QueryEscape(fmt.Sprintf("%v", petId)), -1)
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "PetApiService.GetPetById")
if err != nil {
return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/pet/{petId}"
localVarPath = strings.Replace(localVarPath, "{"+"petId"+"}", _neturl.QueryEscape(parameterToString(petId, "")) , -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
@ -463,8 +482,12 @@ func (a *PetApiService) UpdatePet(ctx _context.Context, pet Pet) (*_nethttp.Resp
localVarFileBytes []byte
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/pet"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "PetApiService.UpdatePet")
if err != nil {
return nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/pet"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
@ -539,9 +562,13 @@ func (a *PetApiService) UpdatePetWithForm(ctx _context.Context, petId int64, loc
localVarFileBytes []byte
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/pet/{petId}"
localVarPath = strings.Replace(localVarPath, "{"+"petId"+"}", _neturl.QueryEscape(fmt.Sprintf("%v", petId)), -1)
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "PetApiService.UpdatePetWithForm")
if err != nil {
return nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/pet/{petId}"
localVarPath = strings.Replace(localVarPath, "{"+"petId"+"}", _neturl.QueryEscape(parameterToString(petId, "")) , -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
@ -622,9 +649,13 @@ func (a *PetApiService) UploadFile(ctx _context.Context, petId int64, localVarOp
localVarReturnValue ApiResponse
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/pet/{petId}/uploadImage"
localVarPath = strings.Replace(localVarPath, "{"+"petId"+"}", _neturl.QueryEscape(fmt.Sprintf("%v", petId)), -1)
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "PetApiService.UploadFile")
if err != nil {
return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/pet/{petId}/uploadImage"
localVarPath = strings.Replace(localVarPath, "{"+"petId"+"}", _neturl.QueryEscape(parameterToString(petId, "")) , -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
@ -734,9 +765,13 @@ func (a *PetApiService) UploadFileWithRequiredFile(ctx _context.Context, petId i
localVarReturnValue ApiResponse
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/fake/{petId}/uploadImageWithRequiredFile"
localVarPath = strings.Replace(localVarPath, "{"+"petId"+"}", _neturl.QueryEscape(fmt.Sprintf("%v", petId)), -1)
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "PetApiService.UploadFileWithRequiredFile")
if err != nil {
return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/fake/{petId}/uploadImageWithRequiredFile"
localVarPath = strings.Replace(localVarPath, "{"+"petId"+"}", _neturl.QueryEscape(parameterToString(petId, "")) , -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}

View File

@ -14,7 +14,6 @@ import (
_ioutil "io/ioutil"
_nethttp "net/http"
_neturl "net/url"
"fmt"
"strings"
)
@ -41,9 +40,13 @@ func (a *StoreApiService) DeleteOrder(ctx _context.Context, orderId string) (*_n
localVarFileBytes []byte
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/store/order/{order_id}"
localVarPath = strings.Replace(localVarPath, "{"+"order_id"+"}", _neturl.QueryEscape(fmt.Sprintf("%v", orderId)), -1)
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "StoreApiService.DeleteOrder")
if err != nil {
return nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/store/order/{order_id}"
localVarPath = strings.Replace(localVarPath, "{"+"order_id"+"}", _neturl.QueryEscape(parameterToString(orderId, "")) , -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
@ -109,8 +112,12 @@ func (a *StoreApiService) GetInventory(ctx _context.Context) (map[string]int32,
localVarReturnValue map[string]int32
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/store/inventory"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "StoreApiService.GetInventory")
if err != nil {
return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/store/inventory"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
@ -209,9 +216,13 @@ func (a *StoreApiService) GetOrderById(ctx _context.Context, orderId int64) (Ord
localVarReturnValue Order
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/store/order/{order_id}"
localVarPath = strings.Replace(localVarPath, "{"+"order_id"+"}", _neturl.QueryEscape(fmt.Sprintf("%v", orderId)), -1)
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "StoreApiService.GetOrderById")
if err != nil {
return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/store/order/{order_id}"
localVarPath = strings.Replace(localVarPath, "{"+"order_id"+"}", _neturl.QueryEscape(parameterToString(orderId, "")) , -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
@ -302,8 +313,12 @@ func (a *StoreApiService) PlaceOrder(ctx _context.Context, order Order) (Order,
localVarReturnValue Order
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/store/order"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "StoreApiService.PlaceOrder")
if err != nil {
return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/store/order"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}

View File

@ -14,7 +14,6 @@ import (
_ioutil "io/ioutil"
_nethttp "net/http"
_neturl "net/url"
"fmt"
"strings"
)
@ -41,8 +40,12 @@ func (a *UserApiService) CreateUser(ctx _context.Context, user User) (*_nethttp.
localVarFileBytes []byte
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/user"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "UserApiService.CreateUser")
if err != nil {
return nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/user"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
@ -108,8 +111,12 @@ func (a *UserApiService) CreateUsersWithArrayInput(ctx _context.Context, user []
localVarFileBytes []byte
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/user/createWithArray"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "UserApiService.CreateUsersWithArrayInput")
if err != nil {
return nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/user/createWithArray"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
@ -175,8 +182,12 @@ func (a *UserApiService) CreateUsersWithListInput(ctx _context.Context, user []U
localVarFileBytes []byte
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/user/createWithList"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "UserApiService.CreateUsersWithListInput")
if err != nil {
return nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/user/createWithList"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
@ -243,9 +254,13 @@ func (a *UserApiService) DeleteUser(ctx _context.Context, username string) (*_ne
localVarFileBytes []byte
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/user/{username}"
localVarPath = strings.Replace(localVarPath, "{"+"username"+"}", _neturl.QueryEscape(fmt.Sprintf("%v", username)), -1)
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "UserApiService.DeleteUser")
if err != nil {
return nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/user/{username}"
localVarPath = strings.Replace(localVarPath, "{"+"username"+"}", _neturl.QueryEscape(parameterToString(username, "")) , -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
@ -311,9 +326,13 @@ func (a *UserApiService) GetUserByName(ctx _context.Context, username string) (U
localVarReturnValue User
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/user/{username}"
localVarPath = strings.Replace(localVarPath, "{"+"username"+"}", _neturl.QueryEscape(fmt.Sprintf("%v", username)), -1)
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "UserApiService.GetUserByName")
if err != nil {
return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/user/{username}"
localVarPath = strings.Replace(localVarPath, "{"+"username"+"}", _neturl.QueryEscape(parameterToString(username, "")) , -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
@ -399,8 +418,12 @@ func (a *UserApiService) LoginUser(ctx _context.Context, username string, passwo
localVarReturnValue string
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/user/login"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "UserApiService.LoginUser")
if err != nil {
return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/user/login"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
@ -484,8 +507,12 @@ func (a *UserApiService) LogoutUser(ctx _context.Context) (*_nethttp.Response, e
localVarFileBytes []byte
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/user/logout"
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "UserApiService.LogoutUser")
if err != nil {
return nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/user/logout"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
@ -551,9 +578,13 @@ func (a *UserApiService) UpdateUser(ctx _context.Context, username string, user
localVarFileBytes []byte
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/user/{username}"
localVarPath = strings.Replace(localVarPath, "{"+"username"+"}", _neturl.QueryEscape(fmt.Sprintf("%v", username)), -1)
localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "UserApiService.UpdateUser")
if err != nil {
return nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/user/{username}"
localVarPath = strings.Replace(localVarPath, "{"+"username"+"}", _neturl.QueryEscape(parameterToString(username, "")) , -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}

View File

@ -200,11 +200,6 @@ func (c *APIClient) callAPI(request *http.Request) (*http.Response, error) {
return resp, err
}
// ChangeBasePath changes base path to allow switching to mocks
func (c *APIClient) ChangeBasePath(path string) {
c.cfg.BasePath = path
}
// Allow modification of underlying config for alternate implementations and testing
// Caution: modifying the configuration while live can cause data races and potentially unwanted behavior
func (c *APIClient) GetConfig() *Configuration {

View File

@ -10,6 +10,7 @@
package openapi
import (
"context"
"fmt"
"net/http"
"strings"
@ -37,6 +38,18 @@ var (
// ContextAPIKeys takes a string apikey as authentication for the request
ContextAPIKeys = contextKey("apiKeys")
// ContextServerIndex uses a server configuration from the index.
ContextServerIndex = contextKey("serverIndex")
// ContextOperationServerIndices uses a server configuration from the index mapping.
ContextOperationServerIndices = contextKey("serverOperationIndices")
// ContextServerVariables overrides a server configuration variables.
ContextServerVariables = contextKey("serverVariables")
// ContextOperationServerVariables overrides a server configuration variables using operation specific values.
ContextOperationServerVariables = contextKey("serverOperationVariables")
)
// BasicAuth provides basic http authentication to a request passed via context using ContextBasicAuth
@ -60,32 +73,35 @@ type ServerVariable struct {
// ServerConfiguration stores the information about a server
type ServerConfiguration struct {
Url string
URL string
Description string
Variables map[string]ServerVariable
}
// ServerConfigurations stores multiple ServerConfiguration items
type ServerConfigurations []ServerConfiguration
// Configuration stores the configuration of the API client
type Configuration struct {
BasePath string `json:"basePath,omitempty"`
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 []ServerConfiguration
HTTPClient *http.Client
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
}
// NewConfiguration returns a new Configuration object
func NewConfiguration() *Configuration {
cfg := &Configuration{
BasePath: "http://petstore.swagger.io:80/v2",
DefaultHeader: make(map[string]string),
UserAgent: "OpenAPI-Generator/1.0.0/go",
Debug: false,
Servers: []ServerConfiguration{{
Url: "http://{server}.swagger.io:{port}/v2",
DefaultHeader: make(map[string]string),
UserAgent: "OpenAPI-Generator/1.0.0/go",
Debug: false,
Servers: ServerConfigurations{
{
URL: "http://{server}.swagger.io:{port}/v2",
Description: "petstore server",
Variables: map[string]ServerVariable{
"server": ServerVariable{
@ -107,7 +123,8 @@ func NewConfiguration() *Configuration {
},
},
},
Url: "https://localhost:8080/{version}",
{
URL: "https://localhost:8080/{version}",
Description: "The local server",
Variables: map[string]ServerVariable{
"version": ServerVariable{
@ -121,6 +138,28 @@ func NewConfiguration() *Configuration {
},
},
},
OperationServers: map[string]ServerConfigurations{
"PetApiService.AddPet": {
{
URL: "http://petstore.swagger.io/v2",
Description: "No description provided",
},
{
URL: "http://path-server-test.petstore.local/v2",
Description: "No description provided",
},
},
"PetApiService.UpdatePet": {
{
URL: "http://petstore.swagger.io/v2",
Description: "No description provided",
},
{
URL: "http://path-server-test.petstore.local/v2",
Description: "No description provided",
},
},
},
}
return cfg
}
@ -130,13 +169,13 @@ func (c *Configuration) AddDefaultHeader(key string, value string) {
c.DefaultHeader[key] = value
}
// ServerUrl returns URL based on server settings
func (c *Configuration) ServerUrl(index int, variables map[string]string) (string, error) {
if index < 0 || len(c.Servers) <= index {
return "", fmt.Errorf("Index %v out of range %v", index, len(c.Servers) - 1)
// URL formats template on a index using given variables
func (sc ServerConfigurations) URL(index int, variables map[string]string) (string, error) {
if index < 0 || len(sc) <= index {
return "", fmt.Errorf("Index %v out of range %v", index, len(sc)-1)
}
server := c.Servers[index]
url := server.Url
server := sc[index]
url := server.URL
// go through variables and replace placeholders
for name, variable := range server.Variables {
@ -157,3 +196,84 @@ func (c *Configuration) ServerUrl(index int, variables map[string]string) (strin
}
return url, nil
}
// ServerURL returns URL based on server settings
func (c *Configuration) ServerURL(index int, variables map[string]string) (string, error) {
return c.Servers.URL(index, variables)
}
func getServerIndex(ctx context.Context) (int, error) {
si := ctx.Value(ContextServerIndex)
if si != nil {
if index, ok := si.(int); ok {
return index, nil
}
return 0, reportError("Invalid type %T should be int", si)
}
return 0, nil
}
func getServerOperationIndex(ctx context.Context, endpoint string) (int, error) {
osi := ctx.Value(ContextOperationServerIndices)
if osi != nil {
if operationIndices, ok := osi.(map[string]int); !ok {
return 0, reportError("Invalid type %T should be map[string]int", osi)
} else {
index, ok := operationIndices[endpoint]
if ok {
return index, nil
}
}
}
return getServerIndex(ctx)
}
func getServerVariables(ctx context.Context) (map[string]string, error) {
sv := ctx.Value(ContextServerVariables)
if sv != nil {
if variables, ok := sv.(map[string]string); ok {
return variables, nil
}
return nil, reportError("ctx value of ContextServerVariables has invalid type %T should be map[string]string", sv)
}
return nil, nil
}
func getServerOperationVariables(ctx context.Context, endpoint string) (map[string]string, error) {
osv := ctx.Value(ContextOperationServerVariables)
if osv != nil {
if operationVariables, ok := osv.(map[string]map[string]string); !ok {
return nil, reportError("ctx value of ContextOperationServerVariables has invalid type %T should be map[string]map[string]string", osv)
} else {
variables, ok := operationVariables[endpoint]
if ok {
return variables, nil
}
}
}
return getServerVariables(ctx)
}
// ServerURLWithContext returns a new server URL given an endpoint
func (c *Configuration) ServerURLWithContext(ctx context.Context, endpoint string) (string, error) {
sc, ok := c.OperationServers[endpoint]
if !ok {
sc = c.Servers
}
if ctx == nil {
return sc.URL(0, nil)
}
index, err := getServerOperationIndex(ctx, endpoint)
if err != nil {
return "", err
}
variables, err := getServerOperationVariables(ctx, endpoint)
if err != nil {
return "", err
}
return sc.URL(index, variables)
}