From 3ed1aa8e79687bed63dfa064de27317273080471 Mon Sep 17 00:00:00 2001 From: antihax Date: Fri, 21 Apr 2017 12:17:18 -0500 Subject: [PATCH] Rewrite of Go Client #2 (#5037) * Rewrite of Go Client * Revert to older version of context.Context * Clean and bulk up concurrency test. * Correct {{path}} to {{{path}}} * change custom date type to string. * Add APIKey authentication * Correct missing line from resolving conflicts. Correct missing line from resolving conflicts. --- bin/go-petstore-server.sh | 3 +- .../codegen/languages/GoClientCodegen.java | 11 +- .../codegen/languages/GoServerCodegen.java | 67 +- .../src/main/resources/go/README.mustache | 45 +- .../src/main/resources/go/api.mustache | 234 ++++--- .../src/main/resources/go/api_client.mustache | 415 +++++++++-- .../src/main/resources/go/api_doc.mustache | 26 +- .../main/resources/go/configuration.mustache | 57 +- .../petstore-security-test/go/README.md | 30 +- .../petstore-security-test/go/api_client.go | 403 +++++++++-- .../go/configuration.go | 56 +- .../petstore-security-test/go/docs/FakeApi.md | 15 +- .../petstore-security-test/go/fake_api.go | 87 ++- samples/client/petstore/go/auth_test.go | 245 +++++++ .../client/petstore/go/go-petstore/README.md | 38 +- .../petstore/go/go-petstore/api_client.go | 411 +++++++++-- .../petstore/go/go-petstore/configuration.go | 57 +- .../petstore/go/go-petstore/docs/FakeApi.md | 79 ++- .../docs/Fake_classname_tags123Api.md | 8 +- .../go/go-petstore/docs/FormatTest.md | 2 +- .../petstore/go/go-petstore/docs/PetApi.md | 108 +-- .../petstore/go/go-petstore/docs/StoreApi.md | 32 +- .../petstore/go/go-petstore/docs/UserApi.md | 76 +-- .../petstore/go/go-petstore/fake_api.go | 398 ++++++----- .../go-petstore/fake_classname_tags123_api.go | 89 ++- .../petstore/go/go-petstore/format_test.go | 2 +- .../client/petstore/go/go-petstore/pet_api.go | 645 +++++++++--------- .../petstore/go/go-petstore/store_api.go | 315 +++++---- .../petstore/go/go-petstore/user_api.go | 544 ++++++++------- samples/client/petstore/go/pet_api_test.go | 223 +++--- samples/client/petstore/go/pom.xml | 28 + samples/client/petstore/go/user_api_test.go | 276 ++++---- .../petstore/go-api-server/go/README.md | 2 +- 33 files changed, 3139 insertions(+), 1888 deletions(-) create mode 100644 samples/client/petstore/go/auth_test.go diff --git a/bin/go-petstore-server.sh b/bin/go-petstore-server.sh index d0c2d74b8d3..2099d5acbf0 100755 --- a/bin/go-petstore-server.sh +++ b/bin/go-petstore-server.sh @@ -26,6 +26,7 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l go-server -o samples/server/petstore/go-api-server -DpackageName=petstoreserver --additional-properties hideGenerationTimestamp=true " + +ags="$@ generate -t modules/swagger-codegen/src/main/resources/go-server -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l go-server -o samples/server/petstore/go-api-server -DpackageName=petstoreserver --additional-properties hideGenerationTimestamp=true" java $JAVA_OPTS -Dservice -jar $executable $ags diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java index dab49acd9ac..b031f520d96 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java @@ -97,7 +97,7 @@ public GoClientCodegen() { typeMapping.put("boolean", "bool"); typeMapping.put("string", "string"); typeMapping.put("UUID", "string"); - typeMapping.put("date", "time.Time"); + typeMapping.put("date", "string"); typeMapping.put("DateTime", "time.Time"); typeMapping.put("password", "string"); typeMapping.put("File", "*os.File"); @@ -274,8 +274,6 @@ public String toApiFilename(String name) { return underscore(name) + "_api"; } - - /** * Overrides postProcessParameter to add a vendor extension "x-exportParamName". * This is useful when paramName starts with a lowercase letter, but we need that @@ -303,7 +301,6 @@ public void postProcessParameter(CodegenParameter parameter){ parameter.vendorExtensions.put("x-exportParamName", sb.toString()); } - @Override public String apiDocFileFolder() { return (outputFolder + "/" + apiDocPath).replace('/', File.separatorChar); @@ -406,9 +403,10 @@ public Map postProcessOperations(Map objs) { if (_import.startsWith(apiPackage())) iterator.remove(); } - // if the return type is not primitive, import encoding/json + + // if their is a return type, import encoding/json for (CodegenOperation operation : operations) { - if(operation.returnBaseType != null && needToImport(operation.returnBaseType)) { + if(operation.returnBaseType != null ) { imports.add(createMapping("import", "encoding/json")); break; //just need to import once } @@ -422,7 +420,6 @@ public Map postProcessOperations(Map objs) { } } - // recursively add import for mapping one type to multiple imports List> recursiveImports = (List>) objs.get("imports"); if (recursiveImports == null) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoServerCodegen.java index caf5765e247..e4baf148623 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoServerCodegen.java @@ -11,6 +11,11 @@ import io.swagger.codegen.*; import io.swagger.models.*; import io.swagger.util.Yaml; +import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.MapProperty; +import io.swagger.models.properties.Property; +import io.swagger.models.parameters.Parameter; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -64,6 +69,11 @@ public GoServerCodegen() { */ setReservedWordsLowerCase( Arrays.asList( + // data type + "string", "bool", "uint", "uint8", "uint16", "uint32", "uint64", + "int", "int8", "int16", "int32", "int64", "float32", "float64", + "complex64", "complex128", "rune", "byte", "uintptr", + "break", "default", "func", "interface", "select", "case", "defer", "go", "map", "struct", "chan", "else", "goto", "package", "switch", @@ -108,7 +118,8 @@ public GoServerCodegen() { typeMapping.put("double", "float64"); typeMapping.put("boolean", "bool"); typeMapping.put("string", "string"); - typeMapping.put("date", "time.Time"); + typeMapping.put("UUID", "string"); + typeMapping.put("date", "string"); typeMapping.put("DateTime", "time.Time"); typeMapping.put("password", "string"); typeMapping.put("File", "*os.File"); @@ -117,6 +128,7 @@ public GoServerCodegen() { // the correct solution is to use []byte typeMapping.put("binary", "string"); typeMapping.put("ByteArray", "string"); + typeMapping.put("object", "interface{}"); importMapping = new HashMap(); importMapping.put("time.Time", "time"); @@ -243,11 +255,11 @@ public String toOperationId(String operationId) { @Override public String toModelFilename(String name) { if (!StringUtils.isEmpty(modelNamePrefix)) { - name = modelNamePrefix + "_" + name; + name = modelNamePrefix + name; } if (!StringUtils.isEmpty(modelNameSuffix)) { - name = name + "_" + modelNameSuffix; + name = name + modelNameSuffix; } name = sanitizeName(name); @@ -258,7 +270,54 @@ public String toModelFilename(String name) { name = "model_" + name; // e.g. return => ModelReturn (after camelize) } - return underscore(name); + return camelize(name); + } + + @Override + public String getTypeDeclaration(Property p) { + if(p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return "[]" + getTypeDeclaration(inner); + } + else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + + return getSwaggerType(p) + "[string]" + getTypeDeclaration(inner); + } + //return super.getTypeDeclaration(p); + + // Not using the supertype invocation, because we want to UpperCamelize + // the type. + String swaggerType = getSwaggerType(p); + if (typeMapping.containsKey(swaggerType)) { + return typeMapping.get(swaggerType); + } + + if(typeMapping.containsValue(swaggerType)) { + return swaggerType; + } + + if(languageSpecificPrimitives.contains(swaggerType)) { + return swaggerType; + } + + return toModelName(swaggerType); + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if(typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if(languageSpecificPrimitives.contains(type)) + return (type); + } + else + type = swaggerType; + return type; } @Override diff --git a/modules/swagger-codegen/src/main/resources/go/README.mustache b/modules/swagger-codegen/src/main/resources/go/README.mustache index 190beb68810..0e89ca61846 100644 --- a/modules/swagger-codegen/src/main/resources/go/README.mustache +++ b/modules/swagger-codegen/src/main/resources/go/README.mustache @@ -38,16 +38,31 @@ Class | Method | HTTP request | Description {{/model}}{{/models}} ## Documentation For Authorization - -{{^authMethods}} All endpoints do not require authorization. +{{^authMethods}} Endpoints do not require authorization. {{/authMethods}}{{#authMethods}}{{#last}} Authentication schemes defined for the API:{{/last}}{{/authMethods}} -{{#authMethods}}## {{{name}}} - +{{#authMethods}} +## {{{name}}} {{#isApiKey}}- **Type**: API key -- **API key parameter name**: {{{keyParamName}}} -- **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}} + +Example +``` + auth := context.WithValue(context.TODO(), sw.ContextAPIKey, sw.APIKey{ + Key: "APIKEY", + Prefix: "Bearer", // Omit if not necessary. + }) + r, err := client.Service.Operation(auth, args) +``` {{/isApiKey}} {{#isBasic}}- **Type**: HTTP basic authentication + +Example +``` + auth := context.WithValue(context.TODO(), sw.ContextBasicAuth, sw.BasicAuth{ + UserName: "username", + Password: "password", + }) + r, err := client.Service.Operation(auth, args) +``` {{/isBasic}} {{#isOAuth}}- **Type**: OAuth - **Flow**: {{{flow}}} @@ -55,8 +70,24 @@ Class | Method | HTTP request | Description - **Scopes**: {{^scopes}}N/A{{/scopes}} {{#scopes}} - **{{{scope}}}**: {{{description}}} {{/scopes}} -{{/isOAuth}} +Example +``` + auth := context.WithValue(context.TODO(), sw.ContextAccessToken, "ACCESSTOKENSTRING") + r, err := client.Service.Operation(auth, args) +``` + +Or via OAuth2 module to automaticly refresh tokens and perform user authentication. +``` + import "golang.org/x/oauth2" + + / .. Perform OAuth2 round trip request and obtain a token .. // + + tokenSource := oauth2cfg.TokenSource(createContext(httpClient), &token) + auth := context.WithValue(oauth2.NoContext, sw.ContextOAuth2, tokenSource) + r, err := client.Service.Operation(auth, args) +``` +{{/isOAuth}} {{/authMethods}} ## Author diff --git a/modules/swagger-codegen/src/main/resources/go/api.mustache b/modules/swagger-codegen/src/main/resources/go/api.mustache index 0f78c9f37d3..d02bb0a75e0 100644 --- a/modules/swagger-codegen/src/main/resources/go/api.mustache +++ b/modules/swagger-codegen/src/main/resources/go/api.mustache @@ -4,117 +4,123 @@ package {{packageName}} {{#operations}} import ( "net/url" + "net/http" "strings" + "golang.org/x/net/context" {{#imports}} "{{import}}" {{/imports}} ) -type {{classname}} struct { - Configuration *Configuration -} - -func New{{classname}}() *{{classname}} { - configuration := NewConfiguration() - return &{{classname}}{ - Configuration: configuration, - } -} +// Linger please +var ( + _ context.Context +) -func New{{classname}}WithBasePath(basePath string) *{{classname}} { - configuration := NewConfiguration() - configuration.BasePath = basePath +type {{classname}}Service service - return &{{classname}}{ - Configuration: configuration, - } -} {{#operation}} -/** - * {{summary}}{{#notes}} - * {{notes}}{{/notes}} - * -{{#allParams}}{{#required}} * @param {{paramName}} {{description}} -{{/required}}{{/allParams}}{{#hasOptionalParams}} * @param optional (nil or map[string]interface{}) with one or more of: -{{#allParams}}{{^required}} * @param "{{paramName}}" ({{dataType}}) {{description}} -{{/required}}{{/allParams}}{{/hasOptionalParams}} * @return {{#returnType}}{{^isListContainer}}*{{/isListContainer}}{{{returnType}}}{{/returnType}} - */ -func (a {{{classname}}}) {{{nickname}}}({{#allParams}}{{#required}}{{paramName}} {{{dataType}}}{{#hasMore}}, {{/hasMore}}{{/required}}{{/allParams}}{{#hasOptionalParams}}localVarOptionals map[string]interface{}{{/hasOptionalParams}}) ({{#returnType}}{{^isListContainer}}*{{/isListContainer}}{{{returnType}}}, {{/returnType}}*APIResponse, error) { +/* {{{classname}}}Service {{summary}}{{#notes}} + {{notes}}{{/notes}} +{{#hasAuthMethods}} * @param ctx context.Context Authentication Context {{/hasAuthMethods}} +{{#allParams}}{{#required}} @param {{paramName}} {{description}} +{{/required}}{{/allParams}}{{#hasOptionalParams}} @param optional (nil or map[string]interface{}) with one or more of: +{{#allParams}}{{^required}} @param "{{paramName}}" ({{dataType}}) {{description}} +{{/required}}{{/allParams}}{{/hasOptionalParams}} @return {{#returnType}}{{{returnType}}}{{/returnType}}*/ +func (a *{{{classname}}}Service) {{{nickname}}}({{#hasAuthMethods}}ctx context.Context, {{/hasAuthMethods}}{{#allParams}}{{#required}}{{paramName}} {{{dataType}}}{{#hasMore}}, {{/hasMore}}{{/required}}{{/allParams}}{{#hasOptionalParams}}localVarOptionals map[string]interface{}{{/hasOptionalParams}}) ({{#returnType}}{{{returnType}}}, {{/returnType}} *http.Response, error) { + var ( + localVarHttpMethod = strings.ToUpper("{{httpMethod}}") + localVarPostBody interface{} + localVarFileName string + localVarFileBytes []byte +{{#returnType}} + successPayload {{returnType}} +{{/returnType}} + ) - var localVarHttpMethod = strings.ToUpper("{{httpMethod}}") // create path and map variables - localVarPath := a.Configuration.BasePath + "{{{path}}}"{{#pathParams}} + localVarPath := a.client.cfg.BasePath + "{{{path}}}"{{#pathParams}} localVarPath = strings.Replace(localVarPath, "{"+"{{baseName}}"+"}", fmt.Sprintf("%v", {{paramName}}), -1){{/pathParams}} localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} - localVarFormParams := make(map[string]string) - var localVarPostBody interface{} - var localVarFileName string - var localVarFileBytes []byte -{{#authMethods}} - // authentication '({{name}})' required -{{#isApiKey}} -{{#isKeyInHeader}} - // set key with prefix in header - localVarHeaderParams["{{keyParamName}}"] = a.Configuration.GetAPIKeyWithPrefix("{{keyParamName}}") -{{/isKeyInHeader}} -{{#isKeyInQuery}} - // set key with prefix in query string - localVarQueryParams["{{keyParamName}}"] = a.Configuration.GetAPIKeyWithPrefix("{{keyParamName}}") -{{/isKeyInQuery}} -{{/isApiKey}} -{{#isBasic}} - // http basic authentication required - if a.Configuration.Username != "" || a.Configuration.Password != ""{ - localVarHeaderParams["Authorization"] = "Basic " + a.Configuration.GetBasicAuthEncodedString() - } -{{/isBasic}} -{{#isOAuth}} - // oauth required - if a.Configuration.AccessToken != ""{ - localVarHeaderParams["Authorization"] = "Bearer " + a.Configuration.AccessToken - } -{{/isOAuth}} -{{/authMethods}} - // add default headers if any - for key := range a.Configuration.DefaultHeader { - localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] - } - {{#hasQueryParams}} - {{#queryParams}} - {{#isListContainer}} - var {{paramName}}CollectionFormat = "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}" - {{#required}} - localVarQueryParams.Add("{{baseName}}", a.Configuration.APIClient.ParameterToString({{paramName}}, {{paramName}}CollectionFormat)) - {{/required}} + localVarFormParams := url.Values{} + + {{#allParams}} {{^required}} - if localVarTempParam, localVarOk := localVarOptionals["{{paramName}}"].({{dataType}}); localVarOptionals != nil && localVarOk { - localVarQueryParams.Add("{{baseName}}", a.Configuration.APIClient.ParameterToString(localVarTempParam, {{paramName}}CollectionFormat)) + {{#isPrimitiveType}} + if err := typeCheckParameter(localVarOptionals["{{paramName}}"], "{{{dataType}}}", "{{paramName}}"); err != nil { + return {{#returnType}}successPayload, {{/returnType}}nil, err } + {{/isPrimitiveType}} + {{/required}} + {{#required}} + {{#minItems}} + if len({{paramName}}) < {{minItems}} { + return {{#returnType}}successPayload, {{/returnType}}nil, reportError("{{paramName}} must have at least {{minItems}} elements") + } + {{/minItems}} + {{#maxItems}} + if len({{paramName}}) > {{maxItems}} { + return {{#returnType}}successPayload, {{/returnType}}nil, reportError("{{paramName}} must have less than {{maxItems}} elements") + } + {{/maxItems}} + {{#minLength}} + if strlen({{paramName}}) < {{minLength}} { + return {{#returnType}}successPayload, {{/returnType}}nil, reportError("{{paramName}} must have at least {{minLength}} elements") + } + {{/minLength}} + {{#maxLength}} + if strlen({{paramName}}) > {{maxLength}} { + return {{#returnType}}successPayload, {{/returnType}}nil, reportError("{{paramName}} must have less than {{maxLength}} elements") + } + {{/maxLength}} + {{#minimum}} + {{#isString}} + {{paramName}}Txt, err := atoi({{paramName}}) + if {{paramName}}Txt < {{minimum}} { + {{/isString}} + {{^isString}} + if {{paramName}} < {{minimum}} { + {{/isString}} + return {{#returnType}}successPayload, {{/returnType}}nil, reportError("{{paramName}} must be greater than {{minimum}}") + } + {{/minimum}} + {{#maximum}} + {{#isString}} + {{paramName}}Txt, err := atoi({{paramName}}) + if {{paramName}}Txt > {{maximum}} { + {{/isString}} + {{^isString}} + if {{paramName}} > {{maximum}} { + {{/isString}} + return {{#returnType}}successPayload, {{/returnType}}nil, reportError("{{paramName}} must be less than {{maximum}}") + } + {{/maximum}} {{/required}} - {{/isListContainer}} - {{^isListContainer}} + {{/allParams}} + + {{#hasQueryParams}} + {{#queryParams}} {{#required}} - localVarQueryParams.Add("{{baseName}}", a.Configuration.APIClient.ParameterToString({{paramName}}, "")) + localVarQueryParams.Add("{{baseName}}", parameterToString({{paramName}}, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}")) {{/required}} {{^required}} - if localVarTempParam, localVarOk := localVarOptionals["{{paramName}}"].({{dataType}}); localVarOptionals != nil && localVarOk { - localVarQueryParams.Add("{{baseName}}", a.Configuration.APIClient.ParameterToString(localVarTempParam, "")) + if localVarTempParam, localVarOk := localVarOptionals["{{paramName}}"].({{dataType}}); localVarOk { + localVarQueryParams.Add("{{baseName}}", parameterToString(localVarTempParam, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}")) } {{/required}} - {{/isListContainer}} {{/queryParams}} {{/hasQueryParams}} - // to determine the Content-Type header localVarHttpContentTypes := []string{ {{#consumes}}"{{{mediaType}}}", {{/consumes}} } // set Content-Type header - localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) + localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } + // to determine the Accept header localVarHttpHeaderAccepts := []string{ {{#produces}} @@ -123,18 +129,18 @@ func (a {{{classname}}}) {{{nickname}}}({{#allParams}}{{#required}}{{paramName}} } // set Accept header - localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) + localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } {{#hasHeaderParams}} {{#headerParams}} {{#required}} - localVarHeaderParams["{{baseName}}"] = a.Configuration.APIClient.ParameterToString({{paramName}}, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}") + localVarHeaderParams["{{baseName}}"] = parameterToString({{paramName}}, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}") {{/required}} {{^required}} - if localVarTempParam, localVarOk := localVarOptionals["{{paramName}}"].({{dataType}}); localVarOptionals != nil && localVarOk { - localVarHeaderParams["{{baseName}}"] = a.Configuration.APIClient.ParameterToString(localVarTempParam, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}") + if localVarTempParam, localVarOk := localVarOptionals["{{paramName}}"].({{dataType}}); localVarOk { + localVarHeaderParams["{{baseName}}"] = parameterToString(localVarTempParam, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}") } {{/required}} {{/headerParams}} @@ -144,7 +150,7 @@ func (a {{{classname}}}) {{{nickname}}}({{#allParams}}{{#required}}{{paramName}} {{#isFile}} {{^required}} var file ({{dataType}}) - if localVarTempParam, localVarOk := localVarOptionals["{{paramName}}"].({{dataType}}); localVarOptionals != nil && localVarOk { + if localVarTempParam, localVarOk := localVarOptionals["{{paramName}}"].({{dataType}}); localVarOk { file = localVarTempParam } {{/required}} @@ -152,15 +158,16 @@ func (a {{{classname}}}) {{{nickname}}}({{#allParams}}{{#required}}{{paramName}} fbs, _ := ioutil.ReadAll(file) localVarFileBytes = fbs localVarFileName = file.Name() + file.Close() } {{/isFile}} {{^isFile}} {{#required}} - localVarFormParams["{{baseName}}"] = a.Configuration.APIClient.ParameterToString({{paramName}}, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}") + localVarFormParams.Add("{{baseName}}", parameterToString({{paramName}}, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}")) {{/required}} {{^required}} - if localVarTempParam, localVarOk := localVarOptionals["{{paramName}}"].({{dataType}}); localVarOptionals != nil && localVarOk { - localVarFormParams["{{baseName}}"] = a.Configuration.APIClient.ParameterToString(localVarTempParam, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}") + if localVarTempParam, localVarOk := localVarOptionals["{{paramName}}"].({{dataType}}); localVarOk { + localVarFormParams.Add("{{baseName}}", parameterToString(localVarTempParam, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}")) } {{/required}} {{/isFile}} @@ -169,33 +176,52 @@ func (a {{{classname}}}) {{{nickname}}}({{#allParams}}{{#required}}{{paramName}} {{#hasBodyParam}} {{#bodyParams}} // body params {{#required}} - localVarPostBody = &{{paramName}}{{/required}} + localVarPostBody = &{{paramName}} +{{/required}} {{^required}} - if localVarTempParam, localVarOk := localVarOptionals["{{paramName}}"].({{dataType}}); localVarOptionals != nil && localVarOk { + if localVarTempParam, localVarOk := localVarOptionals["{{paramName}}"].({{dataType}}); localVarOk { localVarPostBody = &localVarTempParam } {{/required}} {{/bodyParams}} {{/hasBodyParam}} -{{#returnType}} - var successPayload = new({{returnType}}) -{{/returnType}} - localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - - var localVarURL, _ = url.Parse(localVarPath) - localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "{{operationId}}", Method: localVarHttpMethod, RequestURL: localVarURL.String()} - if localVarHttpResponse != nil { - localVarAPIResponse.Response = localVarHttpResponse.RawResponse - localVarAPIResponse.Payload = localVarHttpResponse.Body() +{{#authMethods}} +{{#isApiKey}} + if ctx != nil { + // API Key Authentication + if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { + var key string + if auth.Prefix != "" { + key = auth.Prefix + " " + auth.Key + } else { + key = auth.Key + } + {{#isKeyInHeader}}localVarHeaderParams["{{keyParamName}}"] = key{{/isKeyInHeader}}{{#isKeyInQuery}}localVarQueryParams['{{keyParamName}}'] = key{{/isKeyInQuery}} + } } - +{{/isApiKey}} +{{/authMethods}} + r, err := a.client.prepareRequest({{#hasAuthMethods}}ctx, {{/hasAuthMethods}}{{^hasAuthMethods}}nil, {{/hasAuthMethods}}localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { - return {{#returnType}}{{#isListContainer}}*{{/isListContainer}}successPayload, {{/returnType}}localVarAPIResponse, err + return {{#returnType}}successPayload, {{/returnType}}nil, err } + + localVarHttpResponse, err := a.client.callAPI(r) + if err != nil || localVarHttpResponse == nil { + return {{#returnType}}successPayload, {{/returnType}}localVarHttpResponse, err + } + defer localVarHttpResponse.Body.Close() + if localVarHttpResponse.StatusCode >= 300 { + return {{#returnType}}successPayload, {{/returnType}}localVarHttpResponse, reportError(localVarHttpResponse.Status) + } {{#returnType}} - err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) + + if err = json.NewDecoder(localVarHttpResponse.Body).Decode(&successPayload); err != nil { + return {{#returnType}}successPayload, {{/returnType}}localVarHttpResponse, err + } + {{/returnType}} - return {{#returnType}}{{#isListContainer}}*{{/isListContainer}}successPayload, {{/returnType}}localVarAPIResponse, err + + return {{#returnType}}successPayload, {{/returnType}}localVarHttpResponse, err } {{/operation}}{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/go/api_client.mustache b/modules/swagger-codegen/src/main/resources/go/api_client.mustache index e4ae2d09904..eac78242445 100644 --- a/modules/swagger-codegen/src/main/resources/go/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/go/api_client.mustache @@ -3,21 +3,81 @@ package {{packageName}} import ( "bytes" + "encoding/json" + "encoding/xml" "fmt" + "errors" + "io" + "mime/multipart" + "golang.org/x/oauth2" + "golang.org/x/net/context" + "net/http" + "net/url" + "time" + "os" "path/filepath" "reflect" + "regexp" "strings" - "net/url" - "io/ioutil" - "github.com/go-resty/resty" + "unicode/utf8" + "strconv" +) + +var ( + jsonCheck = regexp.MustCompile("(?i:[application|text]/json)") + xmlCheck = regexp.MustCompile("(?i:[application|text]/xml)") ) +// APIClient manages communication with the {{appName}} API v{{version}} +// In most cases there should be only one, shared, APIClient. type APIClient struct { - config *Configuration + cfg *Configuration + common service // Reuse a single struct instead of allocating one for each service on the heap. + + // API Services +{{#apiInfo}} +{{#apis}} +{{#operations}} + {{classname}} *{{classname}}Service +{{/operations}} +{{/apis}} +{{/apiInfo}} +} + +type service struct { + client *APIClient +} + +// NewAPIClient creates a new API client. Requires a userAgent string describing your application. +// optionally a custom http.Client to allow for advanced features such as caching. +func NewAPIClient(cfg *Configuration) *APIClient { + if cfg.HTTPClient == nil { + cfg.HTTPClient = http.DefaultClient + } + + c := &APIClient{} + c.cfg = cfg + c.common.client = c + +{{#apiInfo}} + // API Services +{{#apis}} +{{#operations}} + c.{{classname}} = (*{{classname}}Service)(&c.common) +{{/operations}} +{{/apis}} +{{/apiInfo}} + + return c +} + +func atoi(in string) (int, error) { + return strconv.Atoi(in) } -func (c *APIClient) SelectHeaderContentType(contentTypes []string) string { +// selectHeaderContentType select a content type from the available list. +func selectHeaderContentType(contentTypes []string) string { if len(contentTypes) == 0 { return "" } @@ -27,17 +87,20 @@ func (c *APIClient) SelectHeaderContentType(contentTypes []string) string { return contentTypes[0] // use the first content type specified in 'consumes' } -func (c *APIClient) SelectHeaderAccept(accepts []string) string { - +// selectHeaderAccept join all accept types and return +func selectHeaderAccept(accepts []string) string { if len(accepts) == 0 { return "" } + if contains(accepts, "application/json") { return "application/json" } + return strings.Join(accepts, ",") } +// contains is a case insenstive match, finding needle in a haystack func contains(haystack []string, needle string) bool { for _, a := range haystack { if strings.ToLower(a) == strings.ToLower(needle) { @@ -47,40 +110,24 @@ func contains(haystack []string, needle string) bool { return false } -func (c *APIClient) CallAPI(path string, method string, - postBody interface{}, - headerParams map[string]string, - queryParams url.Values, - formParams map[string]string, - fileName string, - fileBytes []byte) (*resty.Response, error) { - - rClient := c.prepareClient() - request := c.prepareRequest(rClient, postBody, headerParams, queryParams, formParams, fileName, fileBytes) - - switch strings.ToUpper(method) { - case "GET": - response, err := request.Get(path) - return response, err - case "POST": - response, err := request.Post(path) - return response, err - case "PUT": - response, err := request.Put(path) - return response, err - case "PATCH": - response, err := request.Patch(path) - return response, err - case "DELETE": - response, err := request.Delete(path) - return response, err - } - - return nil, fmt.Errorf("invalid method %v", method) -} - -func (c *APIClient) ParameterToString(obj interface{}, collectionFormat string) string { - delimiter := "" +// Verify optional parameters are of the correct type. +func typeCheckParameter(obj interface{}, expected string, name string) error { + // Make sure there is an object. + if obj == nil { + return nil + } + + // Check the type is as expected. + if reflect.TypeOf(obj).String() != expected { + return fmt.Errorf("Expected %s to be of type %s but received %s.", name, expected, reflect.TypeOf(obj).String()) + } + return nil +} + +// parameterToString convert interface{} parameters to string, using a delimiter if format is provided. +func parameterToString(obj interface{}, collectionFormat string) string { + var delimiter string + switch collectionFormat { case "pipes": delimiter = "|" @@ -99,57 +146,277 @@ func (c *APIClient) ParameterToString(obj interface{}, collectionFormat string) return fmt.Sprintf("%v", obj) } -func (c *APIClient) prepareClient() *resty.Client { - - rClient := resty.New() - - rClient.SetDebug(c.config.Debug) - if c.config.Transport != nil { - rClient.SetTransport(c.config.Transport) - } +// callAPI do the request. +func (c *APIClient) callAPI(request *http.Request) (*http.Response, error) { + return c.cfg.HTTPClient.Do(request) +} - if c.config.Timeout != nil { - rClient.SetTimeout(*c.config.Timeout) - } - rClient.SetLogger(ioutil.Discard) - return rClient +// Change base path to allow switching to mocks +func (c *APIClient) ChangeBasePath (path string) { + c.cfg.BasePath = path } -func (c *APIClient) prepareRequest( - rClient *resty.Client, +// prepareRequest build the request +func (c *APIClient) prepareRequest ( + ctx context.Context, + path string, method string, postBody interface{}, headerParams map[string]string, queryParams url.Values, - formParams map[string]string, + formParams url.Values, fileName string, - fileBytes []byte) *resty.Request { + fileBytes []byte) (localVarRequest *http.Request, err error) { + var body *bytes.Buffer - request := rClient.R() - request.SetBody(postBody) + // Detect postBody type and post. + if postBody != nil { + contentType := headerParams["Content-Type"] + if contentType == "" { + contentType = detectContentType(postBody) + headerParams["Content-Type"] = contentType + } - if c.config.UserAgent != "" { - request.SetHeader("User-Agent", c.config.UserAgent) + body, err = setBody(postBody, contentType) + if err != nil { + return nil, err + } } - // add header parameter, if any + // add form paramters and file if available. + if len(formParams) > 0 || (len(fileBytes) > 0 && fileName != "") { + if body != nil { + return nil, errors.New("Cannot specify postBody and multipart form at the same time.") + } + body = &bytes.Buffer{} + w := multipart.NewWriter(body) + + for k, v := range formParams { + for _, iv := range v { + if strings.HasPrefix(k, "@") { // file + err = addFile(w, k[1:], iv) + if err != nil { + return nil, err + } + } else { // form value + w.WriteField(k, iv) + } + } + } + if len(fileBytes) > 0 && fileName != "" { + w.Boundary() + //_, fileNm := filepath.Split(fileName) + part, err := w.CreateFormFile("file", filepath.Base(fileName)) + if err != nil { + return nil, err + } + _, err = part.Write(fileBytes) + if err != nil { + return nil, err + } + // Set the Boundary in the Content-Type + headerParams["Content-Type"] = w.FormDataContentType() + } + + // Set Content-Length + headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len()) + w.Close() + } + + // Setup path and query paramters + url, err := url.Parse(path) + if err != nil { + return nil, err + } + + // Adding Query Param + query := url.Query() + for k, v := range queryParams { + for _, iv := range v { + query.Add(k, iv) + } + } + + // Encode the parameters. + url.RawQuery = query.Encode() + + // Generate a new request + if body != nil { + localVarRequest, err = http.NewRequest(method, url.String(), body) + } else { + localVarRequest, err = http.NewRequest(method, url.String(), nil) + } + if err != nil { + return nil, err + } + + // add header parameters, if any if len(headerParams) > 0 { - request.SetHeaders(headerParams) + headers := http.Header{} + for h, v := range headerParams { + headers.Set(h, v) + } + localVarRequest.Header = headers + } + + // Add the user agent to the request. + localVarRequest.Header.Add("User-Agent", c.cfg.UserAgent) + + // Walk through any authentication. + if ctx != nil { + // OAuth2 authentication + if tok, ok := ctx.Value(ContextOAuth2).(oauth2.TokenSource); ok { + // We were able to grab an oauth2 token from the context + var latestToken *oauth2.Token + if latestToken, err = tok.Token(); err != nil { + return nil, err + } + + latestToken.SetAuthHeader(localVarRequest) + } + + // Basic HTTP Authentication + if auth, ok := ctx.Value(ContextBasicAuth).(BasicAuth); ok { + localVarRequest.SetBasicAuth(auth.UserName, auth.Password) + } + + // AccessToken Authentication + if auth, ok := ctx.Value(ContextAccessToken).(string); ok { + localVarRequest.Header.Add("Authorization", "Bearer " + auth) + } + } + + for header, value := range c.cfg.DefaultHeader { + localVarRequest.Header.Add(header, value) + } + + return localVarRequest, nil +} + + +// Add a file to the multipart request +func addFile(w *multipart.Writer, fieldName, path string) error { + file, err := os.Open(path) + if err != nil { + return err + } + defer file.Close() + + part, err := w.CreateFormFile(fieldName, filepath.Base(path)) + if err != nil { + return err + } + _, err = io.Copy(part, file) + + return err +} + +// Prevent trying to import "fmt" +func reportError(format string, a ...interface{}) (error) { + return fmt.Errorf(format, a...) +} + +// Set request body from an interface{} +func setBody(body interface{}, contentType string) (bodyBuf *bytes.Buffer, err error) { + if bodyBuf == nil { + bodyBuf = &bytes.Buffer{} + } + + if reader, ok := body.(io.Reader); ok { + _, err = bodyBuf.ReadFrom(reader) + } else if b, ok := body.([]byte); ok { + _, err = bodyBuf.Write(b) + } else if s, ok := body.(string); ok { + _, err = bodyBuf.WriteString(s) + } else if jsonCheck.MatchString(contentType) { + err = json.NewEncoder(bodyBuf).Encode(body) + } else if xmlCheck.MatchString(contentType) { + xml.NewEncoder(bodyBuf).Encode(body) } - // add query parameter, if any - if len(queryParams) > 0 { - request.SetMultiValueQueryParams(queryParams) + if err != nil { + return nil, err } - // add form parameter, if any - if len(formParams) > 0 { - request.SetFormData(formParams) + if bodyBuf.Len() == 0 { + err = fmt.Errorf("Invalid body type %s\n", contentType) + return nil, err } + return bodyBuf, nil +} - if len(fileBytes) > 0 && fileName != "" { - _, fileNm := filepath.Split(fileName) - request.SetFileReader("file", fileNm, bytes.NewReader(fileBytes)) +// detectContentType method is used to figure out `Request.Body` content type for request header +func detectContentType(body interface{}) string { + contentType := "text/plain; charset=utf-8" + kind := reflect.TypeOf(body).Kind() + + switch kind { + case reflect.Struct, reflect.Map, reflect.Ptr: + contentType = "application/json; charset=utf-8" + case reflect.String: + contentType = "text/plain; charset=utf-8" + default: + if b, ok := body.([]byte); ok { + contentType = http.DetectContentType(b) + } else if kind == reflect.Slice { + contentType = "application/json; charset=utf-8" + } } - return request + + return contentType } + + +// Ripped from https://github.com/gregjones/httpcache/blob/master/httpcache.go +type cacheControl map[string]string + +func parseCacheControl(headers http.Header) cacheControl { + cc := cacheControl{} + ccHeader := headers.Get("Cache-Control") + for _, part := range strings.Split(ccHeader, ",") { + part = strings.Trim(part, " ") + if part == "" { + continue + } + if strings.ContainsRune(part, '=') { + keyval := strings.Split(part, "=") + cc[strings.Trim(keyval[0], " ")] = strings.Trim(keyval[1], ",") + } else { + cc[part] = "" + } + } + return cc +} + +// CacheExpires helper function to determine remaining time before repeating a request. +func CacheExpires(r *http.Response) (time.Time) { + // Figure out when the cache expires. + var expires time.Time + now, err := time.Parse(time.RFC1123, r.Header.Get("date")) + if err != nil { + return time.Now() + } + respCacheControl := parseCacheControl(r.Header) + + if maxAge, ok := respCacheControl["max-age"]; ok { + lifetime, err := time.ParseDuration(maxAge + "s") + if err != nil { + expires = now + } + expires = now.Add(lifetime) + } else { + expiresHeader := r.Header.Get("Expires") + if expiresHeader != "" { + expires, err = time.Parse(time.RFC1123, expiresHeader) + if err != nil { + expires = now + } + } + } + return expires +} + +func strlen(s string) (int) { + return utf8.RuneCountInString(s) +} + diff --git a/modules/swagger-codegen/src/main/resources/go/api_doc.mustache b/modules/swagger-codegen/src/main/resources/go/api_doc.mustache index fe361421904..70d0b96ce86 100644 --- a/modules/swagger-codegen/src/main/resources/go/api_doc.mustache +++ b/modules/swagger-codegen/src/main/resources/go/api_doc.mustache @@ -11,27 +11,29 @@ Method | HTTP request | Description {{#operations}} {{#operation}} # **{{{operationId}}}** -> {{#returnType}}{{{returnType}}} {{/returnType}}{{{operationId}}}({{#allParams}}${{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) - +> {{#returnType}}{{{returnType}}} {{/returnType}}{{{operationId}}}({{#authMethods}}ctx, {{/authMethods}}{{#allParams}}{{#required}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/required}}{{/allParams}}{{#hasOptionalParams}}optional{{/hasOptionalParams}}) {{{summary}}}{{#notes}} {{{notes}}}{{/notes}} - -### Parameters +### Required Parameters {{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}} Name | Type | Description | Notes -------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}} -{{#allParams}} **{{paramName}}** | {{#isFile}}**{{dataType}}**{{/isFile}}{{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{^isFile}}[**{{dataType}}**]({{baseType}}.md){{/isFile}}{{/isPrimitiveType}}| {{description}} | {{^required}}[optional] {{/required}}{{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}} -{{/allParams}} -{{#hasOptionalParams}} - -Note: Optional parameters are passed through a map[string]interface{} -{{/hasOptionalParams}} +------------- | ------------- | ------------- | -------------{{#authMethods}} + **ctx** | **context.Context** | context containing the authentication | nil if no authentication{{/authMethods}}{{/-last}}{{/allParams}}{{#allParams}}{{#required}} + **{{paramName}}** | {{#isFile}}**{{dataType}}**{{/isFile}}{{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{^isFile}}[**{{dataType}}**]({{baseType}}.md){{/isFile}}{{/isPrimitiveType}}| {{description}} | {{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}}{{/required}}{{/allParams}}{{#hasOptionalParams}} + **optional** | **map[string]interface{}** | optional parameters | nil if no parameters + +### Optional Parameters +Optional parameters are passed through a map[string]interface{}. +{{#allParams}}{{#-last}} +Name | Type | Description | Notes +------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}}{{#allParams}} + **{{paramName}}** | {{#isFile}}**{{dataType}}**{{/isFile}}{{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{^isFile}}[**{{dataType}}**]({{baseType}}.md){{/isFile}}{{/isPrimitiveType}}| {{description}} | {{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}}{{/allParams}}{{/hasOptionalParams}} ### Return type -{{#returnType}}{{#returnTypeIsPrimitive}}**{{{returnType}}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{{returnType}}}**]({{returnBaseType}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}(empty response body){{/returnType}} +{{#returnType}}{{#returnTypeIsPrimitive}}**{{{returnType}}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{{returnType}}}**]({{returnBaseType}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}} (empty response body){{/returnType}} ### Authorization diff --git a/modules/swagger-codegen/src/main/resources/go/configuration.mustache b/modules/swagger-codegen/src/main/resources/go/configuration.mustache index bd3ce67afca..97bfa891d40 100644 --- a/modules/swagger-codegen/src/main/resources/go/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/go/configuration.mustache @@ -2,57 +2,42 @@ package {{packageName}} import ( - "encoding/base64" "net/http" - "time" ) +const ContextOAuth2 int = 1 +const ContextBasicAuth int = 2 +const ContextAccessToken int = 3 +const ContextAPIKey int = 4 + +type BasicAuth struct { + UserName string `json:"userName,omitempty"` + Password string `json:"password,omitempty"` +} + +type APIKey struct { + Key string + Prefix string +} type Configuration struct { - Username string `json:"userName,omitempty"` - Password string `json:"password,omitempty"` - APIKeyPrefix map[string]string `json:"APIKeyPrefix,omitempty"` - APIKey map[string]string `json:"APIKey,omitempty"` - Debug bool `json:"debug,omitempty"` - DebugFile string `json:"debugFile,omitempty"` - OAuthToken string `json:"oAuthToken,omitempty"` - BasePath string `json:"basePath,omitempty"` - Host string `json:"host,omitempty"` - Scheme string `json:"scheme,omitempty"` - AccessToken string `json:"accessToken,omitempty"` - DefaultHeader map[string]string `json:"defaultHeader,omitempty"` - UserAgent string `json:"userAgent,omitempty"` - APIClient *APIClient - Transport *http.Transport - Timeout *time.Duration `json:"timeout,omitempty"` + 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"` + HTTPClient *http.Client } func NewConfiguration() *Configuration { cfg := &Configuration{ BasePath: "{{{basePath}}}", DefaultHeader: make(map[string]string), - APIKey: make(map[string]string), - APIKeyPrefix: make(map[string]string), UserAgent: "{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}Swagger-Codegen/{{{packageVersion}}}/go{{/httpUserAgent}}", - APIClient: &APIClient{}, } - - cfg.APIClient.config = cfg return cfg } -func (c *Configuration) GetBasicAuthEncodedString() string { - return base64.StdEncoding.EncodeToString([]byte(c.Username + ":" + c.Password)) -} - func (c *Configuration) AddDefaultHeader(key string, value string) { c.DefaultHeader[key] = value -} - -func (c *Configuration) GetAPIKeyWithPrefix(APIKeyIdentifier string) string { - if c.APIKeyPrefix[APIKeyIdentifier] != "" { - return c.APIKeyPrefix[APIKeyIdentifier] + " " + c.APIKey[APIKeyIdentifier] - } - - return c.APIKey[APIKeyIdentifier] -} +} \ No newline at end of file diff --git a/samples/client/petstore-security-test/go/README.md b/samples/client/petstore-security-test/go/README.md index d681fc809f9..4614c5a6cb4 100644 --- a/samples/client/petstore-security-test/go/README.md +++ b/samples/client/petstore-security-test/go/README.md @@ -31,15 +31,18 @@ Class | Method | HTTP request | Description ## Documentation For Authorization - ## api_key - - **Type**: API key -- **API key parameter name**: api_key */ ' " =end -- \r\n \n \r -- **Location**: HTTP header +Example +``` + auth := context.WithValue(context.TODO(), sw.ContextAPIKey, sw.APIKey{ + Key: "APIKEY", + Prefix: "Bearer", // Omit if not necessary. + }) + r, err := client.Service.Operation(auth, args) +``` ## petstore_auth - - **Type**: OAuth - **Flow**: implicit - **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog @@ -47,8 +50,23 @@ Class | Method | HTTP request | Description - **write:pets**: modify pets in your account *_/ ' \" =end -- \\r\\n \\n \\r - **read:pets**: read your pets *_/ ' \" =end -- \\r\\n \\n \\r +Example +``` + auth := context.WithValue(context.TODO(), sw.ContextAccessToken, "ACCESSTOKENSTRING") + r, err := client.Service.Operation(auth, args) +``` -## Author +Or via OAuth2 module to automaticly refresh tokens and perform user authentication. +``` + import "golang.org/x/oauth2" + + / .. Perform OAuth2 round trip request and obtain a token .. // + tokenSource := oauth2cfg.TokenSource(createContext(httpClient), &token) + auth := context.WithValue(oauth2.NoContext, sw.ContextOAuth2, tokenSource) + r, err := client.Service.Operation(auth, args) +``` + +## Author apiteam@swagger.io *_/ ' \" =end -- \\r\\n \\n \\r diff --git a/samples/client/petstore-security-test/go/api_client.go b/samples/client/petstore-security-test/go/api_client.go index 5b7295c680a..98cbc1f1c26 100644 --- a/samples/client/petstore-security-test/go/api_client.go +++ b/samples/client/petstore-security-test/go/api_client.go @@ -12,21 +12,69 @@ package swagger import ( "bytes" + "encoding/json" + "encoding/xml" "fmt" + "errors" + "io" + "mime/multipart" + "golang.org/x/oauth2" + "golang.org/x/net/context" + "net/http" + "net/url" + "time" + "os" "path/filepath" "reflect" + "regexp" "strings" - "net/url" - "io/ioutil" - "github.com/go-resty/resty" + "unicode/utf8" + "strconv" +) + +var ( + jsonCheck = regexp.MustCompile("(?i:[application|text]/json)") + xmlCheck = regexp.MustCompile("(?i:[application|text]/xml)") ) +// APIClient manages communication with the Swagger Petstore *_/ ' \" =end -- \\r\\n \\n \\r API v1.0.0 *_/ ' \" =end -- \\r\\n \\n \\r +// In most cases there should be only one, shared, APIClient. type APIClient struct { - config *Configuration + cfg *Configuration + common service // Reuse a single struct instead of allocating one for each service on the heap. + + // API Services + FakeApi *FakeApiService +} + +type service struct { + client *APIClient +} + +// NewAPIClient creates a new API client. Requires a userAgent string describing your application. +// optionally a custom http.Client to allow for advanced features such as caching. +func NewAPIClient(cfg *Configuration) *APIClient { + if cfg.HTTPClient == nil { + cfg.HTTPClient = http.DefaultClient + } + + c := &APIClient{} + c.cfg = cfg + c.common.client = c + + // API Services + c.FakeApi = (*FakeApiService)(&c.common) + + return c +} + +func atoi(in string) (int, error) { + return strconv.Atoi(in) } -func (c *APIClient) SelectHeaderContentType(contentTypes []string) string { +// selectHeaderContentType select a content type from the available list. +func selectHeaderContentType(contentTypes []string) string { if len(contentTypes) == 0 { return "" } @@ -36,17 +84,20 @@ func (c *APIClient) SelectHeaderContentType(contentTypes []string) string { return contentTypes[0] // use the first content type specified in 'consumes' } -func (c *APIClient) SelectHeaderAccept(accepts []string) string { - +// selectHeaderAccept join all accept types and return +func selectHeaderAccept(accepts []string) string { if len(accepts) == 0 { return "" } + if contains(accepts, "application/json") { return "application/json" } + return strings.Join(accepts, ",") } +// contains is a case insenstive match, finding needle in a haystack func contains(haystack []string, needle string) bool { for _, a := range haystack { if strings.ToLower(a) == strings.ToLower(needle) { @@ -56,40 +107,24 @@ func contains(haystack []string, needle string) bool { return false } -func (c *APIClient) CallAPI(path string, method string, - postBody interface{}, - headerParams map[string]string, - queryParams url.Values, - formParams map[string]string, - fileName string, - fileBytes []byte) (*resty.Response, error) { - - rClient := c.prepareClient() - request := c.prepareRequest(rClient, postBody, headerParams, queryParams, formParams, fileName, fileBytes) - - switch strings.ToUpper(method) { - case "GET": - response, err := request.Get(path) - return response, err - case "POST": - response, err := request.Post(path) - return response, err - case "PUT": - response, err := request.Put(path) - return response, err - case "PATCH": - response, err := request.Patch(path) - return response, err - case "DELETE": - response, err := request.Delete(path) - return response, err - } - - return nil, fmt.Errorf("invalid method %v", method) -} - -func (c *APIClient) ParameterToString(obj interface{}, collectionFormat string) string { - delimiter := "" +// Verify optional parameters are of the correct type. +func typeCheckParameter(obj interface{}, expected string, name string) error { + // Make sure there is an object. + if obj == nil { + return nil + } + + // Check the type is as expected. + if reflect.TypeOf(obj).String() != expected { + return fmt.Errorf("Expected %s to be of type %s but received %s.", name, expected, reflect.TypeOf(obj).String()) + } + return nil +} + +// parameterToString convert interface{} parameters to string, using a delimiter if format is provided. +func parameterToString(obj interface{}, collectionFormat string) string { + var delimiter string + switch collectionFormat { case "pipes": delimiter = "|" @@ -108,57 +143,277 @@ func (c *APIClient) ParameterToString(obj interface{}, collectionFormat string) return fmt.Sprintf("%v", obj) } -func (c *APIClient) prepareClient() *resty.Client { - - rClient := resty.New() - - rClient.SetDebug(c.config.Debug) - if c.config.Transport != nil { - rClient.SetTransport(c.config.Transport) - } +// callAPI do the request. +func (c *APIClient) callAPI(request *http.Request) (*http.Response, error) { + return c.cfg.HTTPClient.Do(request) +} - if c.config.Timeout != nil { - rClient.SetTimeout(*c.config.Timeout) - } - rClient.SetLogger(ioutil.Discard) - return rClient +// Change base path to allow switching to mocks +func (c *APIClient) ChangeBasePath (path string) { + c.cfg.BasePath = path } -func (c *APIClient) prepareRequest( - rClient *resty.Client, +// prepareRequest build the request +func (c *APIClient) prepareRequest ( + ctx context.Context, + path string, method string, postBody interface{}, headerParams map[string]string, queryParams url.Values, - formParams map[string]string, + formParams url.Values, fileName string, - fileBytes []byte) *resty.Request { + fileBytes []byte) (localVarRequest *http.Request, err error) { + var body *bytes.Buffer - request := rClient.R() - request.SetBody(postBody) + // Detect postBody type and post. + if postBody != nil { + contentType := headerParams["Content-Type"] + if contentType == "" { + contentType = detectContentType(postBody) + headerParams["Content-Type"] = contentType + } - if c.config.UserAgent != "" { - request.SetHeader("User-Agent", c.config.UserAgent) + body, err = setBody(postBody, contentType) + if err != nil { + return nil, err + } } - // add header parameter, if any + // add form paramters and file if available. + if len(formParams) > 0 || (len(fileBytes) > 0 && fileName != "") { + if body != nil { + return nil, errors.New("Cannot specify postBody and multipart form at the same time.") + } + body = &bytes.Buffer{} + w := multipart.NewWriter(body) + + for k, v := range formParams { + for _, iv := range v { + if strings.HasPrefix(k, "@") { // file + err = addFile(w, k[1:], iv) + if err != nil { + return nil, err + } + } else { // form value + w.WriteField(k, iv) + } + } + } + if len(fileBytes) > 0 && fileName != "" { + w.Boundary() + //_, fileNm := filepath.Split(fileName) + part, err := w.CreateFormFile("file", filepath.Base(fileName)) + if err != nil { + return nil, err + } + _, err = part.Write(fileBytes) + if err != nil { + return nil, err + } + // Set the Boundary in the Content-Type + headerParams["Content-Type"] = w.FormDataContentType() + } + + // Set Content-Length + headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len()) + w.Close() + } + + // Setup path and query paramters + url, err := url.Parse(path) + if err != nil { + return nil, err + } + + // Adding Query Param + query := url.Query() + for k, v := range queryParams { + for _, iv := range v { + query.Add(k, iv) + } + } + + // Encode the parameters. + url.RawQuery = query.Encode() + + // Generate a new request + if body != nil { + localVarRequest, err = http.NewRequest(method, url.String(), body) + } else { + localVarRequest, err = http.NewRequest(method, url.String(), nil) + } + if err != nil { + return nil, err + } + + // add header parameters, if any if len(headerParams) > 0 { - request.SetHeaders(headerParams) + headers := http.Header{} + for h, v := range headerParams { + headers.Set(h, v) + } + localVarRequest.Header = headers + } + + // Add the user agent to the request. + localVarRequest.Header.Add("User-Agent", c.cfg.UserAgent) + + // Walk through any authentication. + if ctx != nil { + // OAuth2 authentication + if tok, ok := ctx.Value(ContextOAuth2).(oauth2.TokenSource); ok { + // We were able to grab an oauth2 token from the context + var latestToken *oauth2.Token + if latestToken, err = tok.Token(); err != nil { + return nil, err + } + + latestToken.SetAuthHeader(localVarRequest) + } + + // Basic HTTP Authentication + if auth, ok := ctx.Value(ContextBasicAuth).(BasicAuth); ok { + localVarRequest.SetBasicAuth(auth.UserName, auth.Password) + } + + // AccessToken Authentication + if auth, ok := ctx.Value(ContextAccessToken).(string); ok { + localVarRequest.Header.Add("Authorization", "Bearer " + auth) + } + } + + for header, value := range c.cfg.DefaultHeader { + localVarRequest.Header.Add(header, value) + } + + return localVarRequest, nil +} + + +// Add a file to the multipart request +func addFile(w *multipart.Writer, fieldName, path string) error { + file, err := os.Open(path) + if err != nil { + return err + } + defer file.Close() + + part, err := w.CreateFormFile(fieldName, filepath.Base(path)) + if err != nil { + return err + } + _, err = io.Copy(part, file) + + return err +} + +// Prevent trying to import "fmt" +func reportError(format string, a ...interface{}) (error) { + return fmt.Errorf(format, a...) +} + +// Set request body from an interface{} +func setBody(body interface{}, contentType string) (bodyBuf *bytes.Buffer, err error) { + if bodyBuf == nil { + bodyBuf = &bytes.Buffer{} + } + + if reader, ok := body.(io.Reader); ok { + _, err = bodyBuf.ReadFrom(reader) + } else if b, ok := body.([]byte); ok { + _, err = bodyBuf.Write(b) + } else if s, ok := body.(string); ok { + _, err = bodyBuf.WriteString(s) + } else if jsonCheck.MatchString(contentType) { + err = json.NewEncoder(bodyBuf).Encode(body) + } else if xmlCheck.MatchString(contentType) { + xml.NewEncoder(bodyBuf).Encode(body) } - // add query parameter, if any - if len(queryParams) > 0 { - request.SetMultiValueQueryParams(queryParams) + if err != nil { + return nil, err } - // add form parameter, if any - if len(formParams) > 0 { - request.SetFormData(formParams) + if bodyBuf.Len() == 0 { + err = fmt.Errorf("Invalid body type %s\n", contentType) + return nil, err } + return bodyBuf, nil +} - if len(fileBytes) > 0 && fileName != "" { - _, fileNm := filepath.Split(fileName) - request.SetFileReader("file", fileNm, bytes.NewReader(fileBytes)) +// detectContentType method is used to figure out `Request.Body` content type for request header +func detectContentType(body interface{}) string { + contentType := "text/plain; charset=utf-8" + kind := reflect.TypeOf(body).Kind() + + switch kind { + case reflect.Struct, reflect.Map, reflect.Ptr: + contentType = "application/json; charset=utf-8" + case reflect.String: + contentType = "text/plain; charset=utf-8" + default: + if b, ok := body.([]byte); ok { + contentType = http.DetectContentType(b) + } else if kind == reflect.Slice { + contentType = "application/json; charset=utf-8" + } } - return request + + return contentType } + + +// Ripped from https://github.com/gregjones/httpcache/blob/master/httpcache.go +type cacheControl map[string]string + +func parseCacheControl(headers http.Header) cacheControl { + cc := cacheControl{} + ccHeader := headers.Get("Cache-Control") + for _, part := range strings.Split(ccHeader, ",") { + part = strings.Trim(part, " ") + if part == "" { + continue + } + if strings.ContainsRune(part, '=') { + keyval := strings.Split(part, "=") + cc[strings.Trim(keyval[0], " ")] = strings.Trim(keyval[1], ",") + } else { + cc[part] = "" + } + } + return cc +} + +// CacheExpires helper function to determine remaining time before repeating a request. +func CacheExpires(r *http.Response) (time.Time) { + // Figure out when the cache expires. + var expires time.Time + now, err := time.Parse(time.RFC1123, r.Header.Get("date")) + if err != nil { + return time.Now() + } + respCacheControl := parseCacheControl(r.Header) + + if maxAge, ok := respCacheControl["max-age"]; ok { + lifetime, err := time.ParseDuration(maxAge + "s") + if err != nil { + expires = now + } + expires = now.Add(lifetime) + } else { + expiresHeader := r.Header.Get("Expires") + if expiresHeader != "" { + expires, err = time.Parse(time.RFC1123, expiresHeader) + if err != nil { + expires = now + } + } + } + return expires +} + +func strlen(s string) (int) { + return utf8.RuneCountInString(s) +} + diff --git a/samples/client/petstore-security-test/go/configuration.go b/samples/client/petstore-security-test/go/configuration.go index 4e4098025a7..f5eda77c282 100644 --- a/samples/client/petstore-security-test/go/configuration.go +++ b/samples/client/petstore-security-test/go/configuration.go @@ -11,57 +11,43 @@ package swagger import ( - "encoding/base64" "net/http" - "time" ) +const ContextOAuth2 int = 1 +const ContextBasicAuth int = 2 +const ContextAccessToken int = 3 +const ContextAPIKey int = 4 + +type BasicAuth struct { + UserName string `json:"userName,omitempty"` + Password string `json:"password,omitempty"` +} + +type APIKey struct { + Key string + Prefix string +} type Configuration struct { - Username string `json:"userName,omitempty"` - Password string `json:"password,omitempty"` - APIKeyPrefix map[string]string `json:"APIKeyPrefix,omitempty"` - APIKey map[string]string `json:"APIKey,omitempty"` - Debug bool `json:"debug,omitempty"` - DebugFile string `json:"debugFile,omitempty"` - OAuthToken string `json:"oAuthToken,omitempty"` - BasePath string `json:"basePath,omitempty"` - Host string `json:"host,omitempty"` - Scheme string `json:"scheme,omitempty"` - AccessToken string `json:"accessToken,omitempty"` - DefaultHeader map[string]string `json:"defaultHeader,omitempty"` - UserAgent string `json:"userAgent,omitempty"` - APIClient *APIClient - Transport *http.Transport - Timeout *time.Duration `json:"timeout,omitempty"` + 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"` + HTTPClient *http.Client } func NewConfiguration() *Configuration { cfg := &Configuration{ BasePath: "https://petstore.swagger.io *_/ ' \" =end -- \\r\\n \\n \\r/v2 *_/ ' \" =end -- \\r\\n \\n \\r", DefaultHeader: make(map[string]string), - APIKey: make(map[string]string), - APIKeyPrefix: make(map[string]string), UserAgent: "Swagger-Codegen/1.0.0/go", APIClient: &APIClient{}, } - - cfg.APIClient.config = cfg return cfg } -func (c *Configuration) GetBasicAuthEncodedString() string { - return base64.StdEncoding.EncodeToString([]byte(c.Username + ":" + c.Password)) -} - func (c *Configuration) AddDefaultHeader(key string, value string) { c.DefaultHeader[key] = value -} - -func (c *Configuration) GetAPIKeyWithPrefix(APIKeyIdentifier string) string { - if c.APIKeyPrefix[APIKeyIdentifier] != "" { - return c.APIKeyPrefix[APIKeyIdentifier] + " " + c.APIKey[APIKeyIdentifier] - } - - return c.APIKey[APIKeyIdentifier] -} +} \ No newline at end of file diff --git a/samples/client/petstore-security-test/go/docs/FakeApi.md b/samples/client/petstore-security-test/go/docs/FakeApi.md index cd8cb6fb039..acabe8a096a 100644 --- a/samples/client/petstore-security-test/go/docs/FakeApi.md +++ b/samples/client/petstore-security-test/go/docs/FakeApi.md @@ -8,20 +8,25 @@ Method | HTTP request | Description # **TestCodeInjectEndRnNR** -> TestCodeInjectEndRnNR($testCodeInjectEndRnNR) - +> TestCodeInjectEndRnNR(optional) To test code injection *_/ ' \" =end -- \\r\\n \\n \\r +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **optional** | **map[string]interface{}** | optional parameters | nil if no parameters -### Parameters +### Optional Parameters +Optional parameters are passed through a map[string]interface{}. Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **testCodeInjectEndRnNR** | **string**| To test code injection *_/ ' \" =end -- \\r\\n \\n \\r | [optional] + **testCodeInjectEndRnNR** | **string**| To test code injection *_/ ' \" =end -- \\r\\n \\n \\r | ### Return type -void (empty response body) + (empty response body) ### Authorization diff --git a/samples/client/petstore-security-test/go/fake_api.go b/samples/client/petstore-security-test/go/fake_api.go index e7469eb6048..b20c99c8014 100644 --- a/samples/client/petstore-security-test/go/fake_api.go +++ b/samples/client/petstore-security-test/go/fake_api.go @@ -12,60 +12,52 @@ package swagger import ( "net/url" + "net/http" "strings" + "golang.org/x/net/context" ) -type FakeApi struct { - Configuration *Configuration -} +// Linger please +var ( + _ context.Context +) -func NewFakeApi() *FakeApi { - configuration := NewConfiguration() - return &FakeApi{ - Configuration: configuration, - } -} +type FakeApiService service -func NewFakeApiWithBasePath(basePath string) *FakeApi { - configuration := NewConfiguration() - configuration.BasePath = basePath - return &FakeApi{ - Configuration: configuration, - } -} +/* FakeApiService To test code injection *_/ ' \" =end -- \\r\\n \\n \\r -/** - * To test code injection *_/ ' \" =end -- \\r\\n \\n \\r - * - * @param testCodeInjectEndRnNR To test code injection *_/ ' \" =end -- \\r\\n \\n \\r - * @return void - */ -func (a FakeApi) TestCodeInjectEndRnNR(testCodeInjectEndRnNR string) (*APIResponse, error) { + @param optional (nil or map[string]interface{}) with one or more of: + @param "testCodeInjectEndRnNR" (string) To test code injection *_/ ' \" =end -- \\r\\n \\n \\r + @return */ +func (a *FakeApiService) TestCodeInjectEndRnNR(localVarOptionals map[string]interface{}) ( *http.Response, error) { + var ( + localVarHttpMethod = strings.ToUpper("Put") + localVarPostBody interface{} + localVarFileName string + localVarFileBytes []byte + ) - var localVarHttpMethod = strings.ToUpper("Put") // create path and map variables - localVarPath := a.Configuration.BasePath + "/fake" + localVarPath := a.client.cfg.BasePath + "/fake" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} - localVarFormParams := make(map[string]string) - var localVarPostBody interface{} - var localVarFileName string - var localVarFileBytes []byte - // add default headers if any - for key := range a.Configuration.DefaultHeader { - localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] + localVarFormParams := url.Values{} + + if err := typeCheckParameter(localVarOptionals["testCodeInjectEndRnNR"], "string", "testCodeInjectEndRnNR"); err != nil { + return nil, err } // to determine the Content-Type header localVarHttpContentTypes := []string{ "application/json", "*_/ ' =end -- ", } // set Content-Type header - localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) + localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } + // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/json", @@ -73,24 +65,27 @@ func (a FakeApi) TestCodeInjectEndRnNR(testCodeInjectEndRnNR string) (*APIRespon } // set Accept header - localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) + localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } - localVarFormParams["testCodeInjectEndRnNR"] = a.Configuration.APIClient.ParameterToString(testCodeInjectEndRnNR, "") - localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - - var localVarURL, _ = url.Parse(localVarPath) - localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "TestCodeInjectEndRnNR", Method: localVarHttpMethod, RequestURL: localVarURL.String()} - if localVarHttpResponse != nil { - localVarAPIResponse.Response = localVarHttpResponse.RawResponse - localVarAPIResponse.Payload = localVarHttpResponse.Body() + if localVarTempParam, localVarOk := localVarOptionals["testCodeInjectEndRnNR"].(string); localVarOk { + localVarFormParams.Add("test code inject */ ' " =end -- \r\n \n \r", parameterToString(localVarTempParam, "")) } - + r, err := a.client.prepareRequest(nil, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { - return localVarAPIResponse, err + return nil, err } - return localVarAPIResponse, err + + localVarHttpResponse, err := a.client.callAPI(r) + if err != nil || localVarHttpResponse == nil { + return localVarHttpResponse, err + } + defer localVarHttpResponse.Body.Close() + if localVarHttpResponse.StatusCode >= 300 { + return localVarHttpResponse, reportError(localVarHttpResponse.Status) + } + + return localVarHttpResponse, err } diff --git a/samples/client/petstore/go/auth_test.go b/samples/client/petstore/go/auth_test.go new file mode 100644 index 00000000000..711896942bb --- /dev/null +++ b/samples/client/petstore/go/auth_test.go @@ -0,0 +1,245 @@ +package main + +import ( + "net/http" + "net/http/httputil" + "strings" + "testing" + "time" + + "golang.org/x/net/context" + + "golang.org/x/oauth2" + + sw "./go-petstore" +) + +func TestOAuth2(t *testing.T) { + // Setup some fake oauth2 configuration + cfg := &oauth2.Config{ + ClientID: "1234567", + ClientSecret: "SuperSecret", + Endpoint: oauth2.Endpoint{ + AuthURL: "https://devnull", + TokenURL: "https://devnull", + }, + RedirectURL: "https://devnull", + } + + // and a fake token + tok := oauth2.Token{ + AccessToken: "FAKE", + RefreshToken: "So Fake", + Expiry: time.Now().Add(time.Hour * 100000), + TokenType: "Bearer", + } + + // then a fake tokenSource + tokenSource := cfg.TokenSource(createContext(nil), &tok) + auth := context.WithValue(oauth2.NoContext, sw.ContextOAuth2, tokenSource) + + newPet := (sw.Pet{Id: 12992, Name: "gopher", + PhotoUrls: []string{"http://1.com", "http://2.com"}, Status: "pending", Tags: []sw.Tag{sw.Tag{Id: 1, Name: "tag2"}}}) + + r, err := client.PetApi.AddPet(nil, newPet) + + if err != nil { + t.Errorf("Error while adding pet") + t.Log(err) + } + if r.StatusCode != 200 { + t.Log(r) + } + + r, err = client.PetApi.DeletePet(auth, 12992, nil) + + if err != nil { + t.Errorf("Error while deleting pet by id") + t.Log(err) + } + if r.StatusCode != 200 { + t.Log(r) + } + reqb, err := httputil.DumpRequest(r.Request, true) + + if !strings.Contains((string)(reqb), "Authorization: Bearer FAKE") { + t.Errorf("OAuth2 Authentication is missing") + } +} + +func TestBasicAuth(t *testing.T) { + + auth := context.WithValue(context.TODO(), sw.ContextBasicAuth, sw.BasicAuth{ + UserName: "fakeUser", + Password: "f4k3p455", + }) + + newPet := (sw.Pet{Id: 12992, Name: "gopher", + PhotoUrls: []string{"http://1.com", "http://2.com"}, Status: "pending", Tags: []sw.Tag{sw.Tag{Id: 1, Name: "tag2"}}}) + + r, err := client.PetApi.AddPet(auth, newPet) + + if err != nil { + t.Errorf("Error while adding pet") + t.Log(err) + } + if r.StatusCode != 200 { + t.Log(r) + } + + r, err = client.PetApi.DeletePet(auth, 12992, nil) + + if err != nil { + t.Errorf("Error while deleting pet by id") + t.Log(err) + } + if r.StatusCode != 200 { + t.Log(r) + } + reqb, err := httputil.DumpRequest(r.Request, true) + if !strings.Contains((string)(reqb), "Authorization: Basic ZmFrZVVzZXI6ZjRrM3A0NTU") { + t.Errorf("Basic Authentication is missing") + } +} + +func TestAccessToken(t *testing.T) { + auth := context.WithValue(context.TODO(), sw.ContextAccessToken, "TESTFAKEACCESSTOKENISFAKE") + + newPet := (sw.Pet{Id: 12992, Name: "gopher", + PhotoUrls: []string{"http://1.com", "http://2.com"}, Status: "pending", Tags: []sw.Tag{sw.Tag{Id: 1, Name: "tag2"}}}) + + r, err := client.PetApi.AddPet(nil, newPet) + + if err != nil { + t.Errorf("Error while adding pet") + t.Log(err) + } + if r.StatusCode != 200 { + t.Log(r) + } + + r, err = client.PetApi.DeletePet(auth, 12992, nil) + + if err != nil { + t.Errorf("Error while deleting pet by id") + t.Log(err) + } + if r.StatusCode != 200 { + t.Log(r) + } + reqb, err := httputil.DumpRequest(r.Request, true) + if !strings.Contains((string)(reqb), "Authorization: Bearer TESTFAKEACCESSTOKENISFAKE") { + t.Errorf("AccessToken Authentication is missing") + } +} + +func TestAPIKeyNoPrefix(t *testing.T) { + auth := context.WithValue(context.TODO(), sw.ContextAPIKey, sw.APIKey{Key: "TEST123"}) + + newPet := (sw.Pet{Id: 12992, Name: "gopher", + PhotoUrls: []string{"http://1.com", "http://2.com"}, Status: "pending", Tags: []sw.Tag{sw.Tag{Id: 1, Name: "tag2"}}}) + + r, err := client.PetApi.AddPet(nil, newPet) + + if err != nil { + t.Errorf("Error while adding pet") + t.Log(err) + } + if r.StatusCode != 200 { + t.Log(r) + } + + _, r, err = client.PetApi.GetPetById(auth, 12992) + if err != nil { + t.Errorf("Error while deleting pet by id") + t.Log(err) + } + + reqb, err := httputil.DumpRequest(r.Request, true) + if !strings.Contains((string)(reqb), "Api_key: TEST123") { + t.Errorf("APIKey Authentication is missing") + } + + r, err = client.PetApi.DeletePet(auth, 12992, nil) + if err != nil { + t.Errorf("Error while deleting pet by id") + t.Log(err) + } + if r.StatusCode != 200 { + t.Log(r) + } +} + +func TestAPIKeyWithPrefix(t *testing.T) { + auth := context.WithValue(context.TODO(), sw.ContextAPIKey, sw.APIKey{Key: "TEST123", Prefix: "Bearer"}) + + newPet := (sw.Pet{Id: 12992, Name: "gopher", + PhotoUrls: []string{"http://1.com", "http://2.com"}, Status: "pending", Tags: []sw.Tag{sw.Tag{Id: 1, Name: "tag2"}}}) + + r, err := client.PetApi.AddPet(nil, newPet) + + if err != nil { + t.Errorf("Error while adding pet") + t.Log(err) + } + if r.StatusCode != 200 { + t.Log(r) + } + + _, r, err = client.PetApi.GetPetById(auth, 12992) + if err != nil { + t.Errorf("Error while deleting pet by id") + t.Log(err) + } + + reqb, err := httputil.DumpRequest(r.Request, true) + if !strings.Contains((string)(reqb), "Api_key: Bearer TEST123") { + t.Errorf("APIKey Authentication is missing") + } + + r, err = client.PetApi.DeletePet(auth, 12992, nil) + if err != nil { + t.Errorf("Error while deleting pet by id") + t.Log(err) + } + if r.StatusCode != 200 { + t.Log(r) + } +} + +func TestDefaultHeader(t *testing.T) { + + newPet := (sw.Pet{Id: 12992, Name: "gopher", + PhotoUrls: []string{"http://1.com", "http://2.com"}, Status: "pending", Tags: []sw.Tag{sw.Tag{Id: 1, Name: "tag2"}}}) + + r, err := client.PetApi.AddPet(nil, newPet) + + if err != nil { + t.Errorf("Error while adding pet") + t.Log(err) + } + if r.StatusCode != 200 { + t.Log(r) + } + + r, err = client.PetApi.DeletePet(nil, 12992, nil) + + if err != nil { + t.Errorf("Error while deleting pet by id") + t.Log(err) + } + if r.StatusCode != 200 { + t.Log(r) + } + reqb, err := httputil.DumpRequest(r.Request, true) + if !strings.Contains((string)(reqb), "Testheader: testvalue") { + t.Errorf("Default Header is missing") + } +} + +// Add custom clients to the context. +func createContext(httpClient *http.Client) context.Context { + parent := oauth2.NoContext + ctx := context.WithValue(parent, oauth2.HTTPClient, httpClient) + return ctx +} diff --git a/samples/client/petstore/go/go-petstore/README.md b/samples/client/petstore/go/go-petstore/README.md index ad8220ac7b2..6e77c9ba9e3 100644 --- a/samples/client/petstore/go/go-petstore/README.md +++ b/samples/client/petstore/go/go-petstore/README.md @@ -85,19 +85,29 @@ Class | Method | HTTP request | Description ## Documentation For Authorization - ## api_key - - **Type**: API key -- **API key parameter name**: api_key -- **Location**: HTTP header +Example +``` + auth := context.WithValue(context.TODO(), sw.ContextAPIKey, sw.APIKey{ + Key: "APIKEY", + Prefix: "Bearer", // Omit if not necessary. + }) + r, err := client.Service.Operation(auth, args) +``` ## http_basic_test - - **Type**: HTTP basic authentication +Example +``` + auth := context.WithValue(context.TODO(), sw.ContextBasicAuth, sw.BasicAuth{ + UserName: "username", + Password: "password", + }) + r, err := client.Service.Operation(auth, args) +``` ## petstore_auth - - **Type**: OAuth - **Flow**: implicit - **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog @@ -105,6 +115,22 @@ Class | Method | HTTP request | Description - **write:pets**: modify pets in your account - **read:pets**: read your pets +Example +``` + auth := context.WithValue(context.TODO(), sw.ContextAccessToken, "ACCESSTOKENSTRING") + r, err := client.Service.Operation(auth, args) +``` + +Or via OAuth2 module to automaticly refresh tokens and perform user authentication. +``` + import "golang.org/x/oauth2" + + / .. Perform OAuth2 round trip request and obtain a token .. // + + tokenSource := oauth2cfg.TokenSource(createContext(httpClient), &token) + auth := context.WithValue(oauth2.NoContext, sw.ContextOAuth2, tokenSource) + r, err := client.Service.Operation(auth, args) +``` ## Author diff --git a/samples/client/petstore/go/go-petstore/api_client.go b/samples/client/petstore/go/go-petstore/api_client.go index a93f346e102..08f7d9c76db 100644 --- a/samples/client/petstore/go/go-petstore/api_client.go +++ b/samples/client/petstore/go/go-petstore/api_client.go @@ -12,21 +12,77 @@ package petstore import ( "bytes" + "encoding/json" + "encoding/xml" "fmt" + "errors" + "io" + "mime/multipart" + "golang.org/x/oauth2" + "golang.org/x/net/context" + "net/http" + "net/url" + "time" + "os" "path/filepath" "reflect" + "regexp" "strings" - "net/url" - "io/ioutil" - "github.com/go-resty/resty" + "unicode/utf8" + "strconv" +) + +var ( + jsonCheck = regexp.MustCompile("(?i:[application|text]/json)") + xmlCheck = regexp.MustCompile("(?i:[application|text]/xml)") ) +// APIClient manages communication with the Swagger Petstore API v1.0.0 +// In most cases there should be only one, shared, APIClient. type APIClient struct { - config *Configuration + cfg *Configuration + common service // Reuse a single struct instead of allocating one for each service on the heap. + + // API Services + FakeApi *FakeApiService + Fake_classname_tags123Api *Fake_classname_tags123ApiService + PetApi *PetApiService + StoreApi *StoreApiService + UserApi *UserApiService +} + +type service struct { + client *APIClient +} + +// NewAPIClient creates a new API client. Requires a userAgent string describing your application. +// optionally a custom http.Client to allow for advanced features such as caching. +func NewAPIClient(cfg *Configuration) *APIClient { + if cfg.HTTPClient == nil { + cfg.HTTPClient = http.DefaultClient + } + + c := &APIClient{} + c.cfg = cfg + c.common.client = c + + // API Services + c.FakeApi = (*FakeApiService)(&c.common) + c.Fake_classname_tags123Api = (*Fake_classname_tags123ApiService)(&c.common) + c.PetApi = (*PetApiService)(&c.common) + c.StoreApi = (*StoreApiService)(&c.common) + c.UserApi = (*UserApiService)(&c.common) + + return c +} + +func atoi(in string) (int, error) { + return strconv.Atoi(in) } -func (c *APIClient) SelectHeaderContentType(contentTypes []string) string { +// selectHeaderContentType select a content type from the available list. +func selectHeaderContentType(contentTypes []string) string { if len(contentTypes) == 0 { return "" } @@ -36,17 +92,20 @@ func (c *APIClient) SelectHeaderContentType(contentTypes []string) string { return contentTypes[0] // use the first content type specified in 'consumes' } -func (c *APIClient) SelectHeaderAccept(accepts []string) string { - +// selectHeaderAccept join all accept types and return +func selectHeaderAccept(accepts []string) string { if len(accepts) == 0 { return "" } + if contains(accepts, "application/json") { return "application/json" } + return strings.Join(accepts, ",") } +// contains is a case insenstive match, finding needle in a haystack func contains(haystack []string, needle string) bool { for _, a := range haystack { if strings.ToLower(a) == strings.ToLower(needle) { @@ -56,40 +115,24 @@ func contains(haystack []string, needle string) bool { return false } -func (c *APIClient) CallAPI(path string, method string, - postBody interface{}, - headerParams map[string]string, - queryParams url.Values, - formParams map[string]string, - fileName string, - fileBytes []byte) (*resty.Response, error) { - - rClient := c.prepareClient() - request := c.prepareRequest(rClient, postBody, headerParams, queryParams, formParams, fileName, fileBytes) - - switch strings.ToUpper(method) { - case "GET": - response, err := request.Get(path) - return response, err - case "POST": - response, err := request.Post(path) - return response, err - case "PUT": - response, err := request.Put(path) - return response, err - case "PATCH": - response, err := request.Patch(path) - return response, err - case "DELETE": - response, err := request.Delete(path) - return response, err - } - - return nil, fmt.Errorf("invalid method %v", method) -} - -func (c *APIClient) ParameterToString(obj interface{}, collectionFormat string) string { - delimiter := "" +// Verify optional parameters are of the correct type. +func typeCheckParameter(obj interface{}, expected string, name string) error { + // Make sure there is an object. + if obj == nil { + return nil + } + + // Check the type is as expected. + if reflect.TypeOf(obj).String() != expected { + return fmt.Errorf("Expected %s to be of type %s but received %s.", name, expected, reflect.TypeOf(obj).String()) + } + return nil +} + +// parameterToString convert interface{} parameters to string, using a delimiter if format is provided. +func parameterToString(obj interface{}, collectionFormat string) string { + var delimiter string + switch collectionFormat { case "pipes": delimiter = "|" @@ -108,57 +151,277 @@ func (c *APIClient) ParameterToString(obj interface{}, collectionFormat string) return fmt.Sprintf("%v", obj) } -func (c *APIClient) prepareClient() *resty.Client { - - rClient := resty.New() - - rClient.SetDebug(c.config.Debug) - if c.config.Transport != nil { - rClient.SetTransport(c.config.Transport) - } +// callAPI do the request. +func (c *APIClient) callAPI(request *http.Request) (*http.Response, error) { + return c.cfg.HTTPClient.Do(request) +} - if c.config.Timeout != nil { - rClient.SetTimeout(*c.config.Timeout) - } - rClient.SetLogger(ioutil.Discard) - return rClient +// Change base path to allow switching to mocks +func (c *APIClient) ChangeBasePath (path string) { + c.cfg.BasePath = path } -func (c *APIClient) prepareRequest( - rClient *resty.Client, +// prepareRequest build the request +func (c *APIClient) prepareRequest ( + ctx context.Context, + path string, method string, postBody interface{}, headerParams map[string]string, queryParams url.Values, - formParams map[string]string, + formParams url.Values, fileName string, - fileBytes []byte) *resty.Request { + fileBytes []byte) (localVarRequest *http.Request, err error) { + var body *bytes.Buffer - request := rClient.R() - request.SetBody(postBody) + // Detect postBody type and post. + if postBody != nil { + contentType := headerParams["Content-Type"] + if contentType == "" { + contentType = detectContentType(postBody) + headerParams["Content-Type"] = contentType + } - if c.config.UserAgent != "" { - request.SetHeader("User-Agent", c.config.UserAgent) + body, err = setBody(postBody, contentType) + if err != nil { + return nil, err + } } - // add header parameter, if any + // add form paramters and file if available. + if len(formParams) > 0 || (len(fileBytes) > 0 && fileName != "") { + if body != nil { + return nil, errors.New("Cannot specify postBody and multipart form at the same time.") + } + body = &bytes.Buffer{} + w := multipart.NewWriter(body) + + for k, v := range formParams { + for _, iv := range v { + if strings.HasPrefix(k, "@") { // file + err = addFile(w, k[1:], iv) + if err != nil { + return nil, err + } + } else { // form value + w.WriteField(k, iv) + } + } + } + if len(fileBytes) > 0 && fileName != "" { + w.Boundary() + //_, fileNm := filepath.Split(fileName) + part, err := w.CreateFormFile("file", filepath.Base(fileName)) + if err != nil { + return nil, err + } + _, err = part.Write(fileBytes) + if err != nil { + return nil, err + } + // Set the Boundary in the Content-Type + headerParams["Content-Type"] = w.FormDataContentType() + } + + // Set Content-Length + headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len()) + w.Close() + } + + // Setup path and query paramters + url, err := url.Parse(path) + if err != nil { + return nil, err + } + + // Adding Query Param + query := url.Query() + for k, v := range queryParams { + for _, iv := range v { + query.Add(k, iv) + } + } + + // Encode the parameters. + url.RawQuery = query.Encode() + + // Generate a new request + if body != nil { + localVarRequest, err = http.NewRequest(method, url.String(), body) + } else { + localVarRequest, err = http.NewRequest(method, url.String(), nil) + } + if err != nil { + return nil, err + } + + // add header parameters, if any if len(headerParams) > 0 { - request.SetHeaders(headerParams) + headers := http.Header{} + for h, v := range headerParams { + headers.Set(h, v) + } + localVarRequest.Header = headers + } + + // Add the user agent to the request. + localVarRequest.Header.Add("User-Agent", c.cfg.UserAgent) + + // Walk through any authentication. + if ctx != nil { + // OAuth2 authentication + if tok, ok := ctx.Value(ContextOAuth2).(oauth2.TokenSource); ok { + // We were able to grab an oauth2 token from the context + var latestToken *oauth2.Token + if latestToken, err = tok.Token(); err != nil { + return nil, err + } + + latestToken.SetAuthHeader(localVarRequest) + } + + // Basic HTTP Authentication + if auth, ok := ctx.Value(ContextBasicAuth).(BasicAuth); ok { + localVarRequest.SetBasicAuth(auth.UserName, auth.Password) + } + + // AccessToken Authentication + if auth, ok := ctx.Value(ContextAccessToken).(string); ok { + localVarRequest.Header.Add("Authorization", "Bearer " + auth) + } + } + + for header, value := range c.cfg.DefaultHeader { + localVarRequest.Header.Add(header, value) + } + + return localVarRequest, nil +} + + +// Add a file to the multipart request +func addFile(w *multipart.Writer, fieldName, path string) error { + file, err := os.Open(path) + if err != nil { + return err + } + defer file.Close() + + part, err := w.CreateFormFile(fieldName, filepath.Base(path)) + if err != nil { + return err + } + _, err = io.Copy(part, file) + + return err +} + +// Prevent trying to import "fmt" +func reportError(format string, a ...interface{}) (error) { + return fmt.Errorf(format, a...) +} + +// Set request body from an interface{} +func setBody(body interface{}, contentType string) (bodyBuf *bytes.Buffer, err error) { + if bodyBuf == nil { + bodyBuf = &bytes.Buffer{} + } + + if reader, ok := body.(io.Reader); ok { + _, err = bodyBuf.ReadFrom(reader) + } else if b, ok := body.([]byte); ok { + _, err = bodyBuf.Write(b) + } else if s, ok := body.(string); ok { + _, err = bodyBuf.WriteString(s) + } else if jsonCheck.MatchString(contentType) { + err = json.NewEncoder(bodyBuf).Encode(body) + } else if xmlCheck.MatchString(contentType) { + xml.NewEncoder(bodyBuf).Encode(body) } - // add query parameter, if any - if len(queryParams) > 0 { - request.SetMultiValueQueryParams(queryParams) + if err != nil { + return nil, err } - // add form parameter, if any - if len(formParams) > 0 { - request.SetFormData(formParams) + if bodyBuf.Len() == 0 { + err = fmt.Errorf("Invalid body type %s\n", contentType) + return nil, err } + return bodyBuf, nil +} - if len(fileBytes) > 0 && fileName != "" { - _, fileNm := filepath.Split(fileName) - request.SetFileReader("file", fileNm, bytes.NewReader(fileBytes)) +// detectContentType method is used to figure out `Request.Body` content type for request header +func detectContentType(body interface{}) string { + contentType := "text/plain; charset=utf-8" + kind := reflect.TypeOf(body).Kind() + + switch kind { + case reflect.Struct, reflect.Map, reflect.Ptr: + contentType = "application/json; charset=utf-8" + case reflect.String: + contentType = "text/plain; charset=utf-8" + default: + if b, ok := body.([]byte); ok { + contentType = http.DetectContentType(b) + } else if kind == reflect.Slice { + contentType = "application/json; charset=utf-8" + } } - return request + + return contentType } + + +// Ripped from https://github.com/gregjones/httpcache/blob/master/httpcache.go +type cacheControl map[string]string + +func parseCacheControl(headers http.Header) cacheControl { + cc := cacheControl{} + ccHeader := headers.Get("Cache-Control") + for _, part := range strings.Split(ccHeader, ",") { + part = strings.Trim(part, " ") + if part == "" { + continue + } + if strings.ContainsRune(part, '=') { + keyval := strings.Split(part, "=") + cc[strings.Trim(keyval[0], " ")] = strings.Trim(keyval[1], ",") + } else { + cc[part] = "" + } + } + return cc +} + +// CacheExpires helper function to determine remaining time before repeating a request. +func CacheExpires(r *http.Response) (time.Time) { + // Figure out when the cache expires. + var expires time.Time + now, err := time.Parse(time.RFC1123, r.Header.Get("date")) + if err != nil { + return time.Now() + } + respCacheControl := parseCacheControl(r.Header) + + if maxAge, ok := respCacheControl["max-age"]; ok { + lifetime, err := time.ParseDuration(maxAge + "s") + if err != nil { + expires = now + } + expires = now.Add(lifetime) + } else { + expiresHeader := r.Header.Get("Expires") + if expiresHeader != "" { + expires, err = time.Parse(time.RFC1123, expiresHeader) + if err != nil { + expires = now + } + } + } + return expires +} + +func strlen(s string) (int) { + return utf8.RuneCountInString(s) +} + diff --git a/samples/client/petstore/go/go-petstore/configuration.go b/samples/client/petstore/go/go-petstore/configuration.go index 7e92b748efd..96275d11ccd 100644 --- a/samples/client/petstore/go/go-petstore/configuration.go +++ b/samples/client/petstore/go/go-petstore/configuration.go @@ -11,57 +11,42 @@ package petstore import ( - "encoding/base64" "net/http" - "time" ) +const ContextOAuth2 int = 1 +const ContextBasicAuth int = 2 +const ContextAccessToken int = 3 +const ContextAPIKey int = 4 + +type BasicAuth struct { + UserName string `json:"userName,omitempty"` + Password string `json:"password,omitempty"` +} + +type APIKey struct { + Key string + Prefix string +} type Configuration struct { - Username string `json:"userName,omitempty"` - Password string `json:"password,omitempty"` - APIKeyPrefix map[string]string `json:"APIKeyPrefix,omitempty"` - APIKey map[string]string `json:"APIKey,omitempty"` - Debug bool `json:"debug,omitempty"` - DebugFile string `json:"debugFile,omitempty"` - OAuthToken string `json:"oAuthToken,omitempty"` - BasePath string `json:"basePath,omitempty"` - Host string `json:"host,omitempty"` - Scheme string `json:"scheme,omitempty"` - AccessToken string `json:"accessToken,omitempty"` - DefaultHeader map[string]string `json:"defaultHeader,omitempty"` - UserAgent string `json:"userAgent,omitempty"` - APIClient *APIClient - Transport *http.Transport - Timeout *time.Duration `json:"timeout,omitempty"` + 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"` + HTTPClient *http.Client } func NewConfiguration() *Configuration { cfg := &Configuration{ BasePath: "http://petstore.swagger.io:80/v2", DefaultHeader: make(map[string]string), - APIKey: make(map[string]string), - APIKeyPrefix: make(map[string]string), UserAgent: "Swagger-Codegen/1.0.0/go", - APIClient: &APIClient{}, } - - cfg.APIClient.config = cfg return cfg } -func (c *Configuration) GetBasicAuthEncodedString() string { - return base64.StdEncoding.EncodeToString([]byte(c.Username + ":" + c.Password)) -} - func (c *Configuration) AddDefaultHeader(key string, value string) { c.DefaultHeader[key] = value -} - -func (c *Configuration) GetAPIKeyWithPrefix(APIKeyIdentifier string) string { - if c.APIKeyPrefix[APIKeyIdentifier] != "" { - return c.APIKeyPrefix[APIKeyIdentifier] + " " + c.APIKey[APIKeyIdentifier] - } - - return c.APIKey[APIKeyIdentifier] -} +} \ No newline at end of file diff --git a/samples/client/petstore/go/go-petstore/docs/FakeApi.md b/samples/client/petstore/go/go-petstore/docs/FakeApi.md index 8316385244c..f7167e26e61 100644 --- a/samples/client/petstore/go/go-petstore/docs/FakeApi.md +++ b/samples/client/petstore/go/go-petstore/docs/FakeApi.md @@ -10,18 +10,16 @@ Method | HTTP request | Description # **TestClientModel** -> Client TestClientModel($body) - +> Client TestClientModel(body) To test \"client\" model To test \"client\" model - -### Parameters +### Required Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**Client**](Client.md)| client model | + **body** | [**Client**](Client.md)| client model | ### Return type @@ -39,14 +37,24 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **TestEndpointParameters** -> TestEndpointParameters($number, $double, $patternWithoutDelimiter, $byte_, $integer, $int32_, $int64_, $float, $string_, $binary, $date, $dateTime, $password, $callback) - +> TestEndpointParameters(ctx, number, double, patternWithoutDelimiter, byte_, optional) Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **ctx** | **context.Context** | context containing the authentication | nil if no authentication + **number** | **float32**| None | + **double** | **float64**| None | + **patternWithoutDelimiter** | **string**| None | + **byte_** | **string**| None | + **optional** | **map[string]interface{}** | optional parameters | nil if no parameters -### Parameters +### Optional Parameters +Optional parameters are passed through a map[string]interface{}. Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- @@ -54,22 +62,20 @@ Name | Type | Description | Notes **double** | **float64**| None | **patternWithoutDelimiter** | **string**| None | **byte_** | **string**| None | - **integer** | **int32**| None | [optional] - **int32_** | **int32**| None | [optional] - **int64_** | **int64**| None | [optional] - **float** | **float32**| None | [optional] - **string_** | **string**| None | [optional] - **binary** | **string**| None | [optional] - **date** | **time.Time**| None | [optional] - **dateTime** | **time.Time**| None | [optional] - **password** | **string**| None | [optional] - **callback** | **string**| None | [optional] - -Note: Optional parameters are passed through a map[string]interface{} + **integer** | **int32**| None | + **int32_** | **int32**| None | + **int64_** | **int64**| None | + **float** | **float32**| None | + **string_** | **string**| None | + **binary** | **string**| None | + **date** | **string**| None | + **dateTime** | **time.Time**| None | + **password** | **string**| None | + **callback** | **string**| None | ### Return type -(empty response body) + (empty response body) ### Authorization @@ -83,31 +89,34 @@ Note: Optional parameters are passed through a map[string]interface{} [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **TestEnumParameters** -> TestEnumParameters($enumFormStringArray, $enumFormString, $enumHeaderStringArray, $enumHeaderString, $enumQueryStringArray, $enumQueryString, $enumQueryInteger, $enumQueryDouble) - +> TestEnumParameters(optional) To test enum parameters To test enum parameters - -### Parameters +### Required Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **enumFormStringArray** | [**[]string**](string.md)| Form parameter enum test (string array) | [optional] - **enumFormString** | **string**| Form parameter enum test (string) | [optional] [default to -efg] - **enumHeaderStringArray** | [**[]string**](string.md)| Header parameter enum test (string array) | [optional] - **enumHeaderString** | **string**| Header parameter enum test (string) | [optional] [default to -efg] - **enumQueryStringArray** | [**[]string**](string.md)| Query parameter enum test (string array) | [optional] - **enumQueryString** | **string**| Query parameter enum test (string) | [optional] [default to -efg] - **enumQueryInteger** | **int32**| Query parameter enum test (double) | [optional] - **enumQueryDouble** | **float64**| Query parameter enum test (double) | [optional] + **optional** | **map[string]interface{}** | optional parameters | nil if no parameters + +### Optional Parameters +Optional parameters are passed through a map[string]interface{}. -Note: Optional parameters are passed through a map[string]interface{} +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **enumFormStringArray** | [**[]string**](string.md)| Form parameter enum test (string array) | + **enumFormString** | **string**| Form parameter enum test (string) | [default to -efg] + **enumHeaderStringArray** | [**[]string**](string.md)| Header parameter enum test (string array) | + **enumHeaderString** | **string**| Header parameter enum test (string) | [default to -efg] + **enumQueryStringArray** | [**[]string**](string.md)| Query parameter enum test (string array) | + **enumQueryString** | **string**| Query parameter enum test (string) | [default to -efg] + **enumQueryInteger** | **int32**| Query parameter enum test (double) | + **enumQueryDouble** | **float64**| Query parameter enum test (double) | ### Return type -(empty response body) + (empty response body) ### Authorization diff --git a/samples/client/petstore/go/go-petstore/docs/Fake_classname_tags123Api.md b/samples/client/petstore/go/go-petstore/docs/Fake_classname_tags123Api.md index bc70731a6d8..8309a56acfd 100644 --- a/samples/client/petstore/go/go-petstore/docs/Fake_classname_tags123Api.md +++ b/samples/client/petstore/go/go-petstore/docs/Fake_classname_tags123Api.md @@ -8,16 +8,14 @@ Method | HTTP request | Description # **TestClassname** -> Client TestClassname($body) - +> Client TestClassname(body) To test class name in snake case - -### Parameters +### Required Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**Client**](Client.md)| client model | + **body** | [**Client**](Client.md)| client model | ### Return type diff --git a/samples/client/petstore/go/go-petstore/docs/FormatTest.md b/samples/client/petstore/go/go-petstore/docs/FormatTest.md index 05f41a8039f..10e6c2ee5da 100644 --- a/samples/client/petstore/go/go-petstore/docs/FormatTest.md +++ b/samples/client/petstore/go/go-petstore/docs/FormatTest.md @@ -12,7 +12,7 @@ Name | Type | Description | Notes **String_** | **string** | | [optional] [default to null] **Byte_** | **string** | | [default to null] **Binary** | **string** | | [optional] [default to null] -**Date** | [**time.Time**](time.Time.md) | | [default to null] +**Date** | **string** | | [default to null] **DateTime** | [**time.Time**](time.Time.md) | | [optional] [default to null] **Uuid** | **string** | | [optional] [default to null] **Password** | **string** | | [default to null] diff --git a/samples/client/petstore/go/go-petstore/docs/PetApi.md b/samples/client/petstore/go/go-petstore/docs/PetApi.md index ebf19df5588..15c34a00142 100644 --- a/samples/client/petstore/go/go-petstore/docs/PetApi.md +++ b/samples/client/petstore/go/go-petstore/docs/PetApi.md @@ -15,22 +15,21 @@ Method | HTTP request | Description # **AddPet** -> AddPet($body) - +> AddPet(ctx, body) Add a new pet to the store - -### Parameters +### Required Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + **ctx** | **context.Context** | context containing the authentication | nil if no authentication + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | ### Return type -(empty response body) + (empty response body) ### Authorization @@ -44,25 +43,30 @@ Name | Type | Description | Notes [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **DeletePet** -> DeletePet($petId, $apiKey) - +> DeletePet(ctx, petId, optional) Deletes a pet +### Required Parameters -### Parameters +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **ctx** | **context.Context** | context containing the authentication | nil if no authentication + **petId** | **int64**| Pet id to delete | + **optional** | **map[string]interface{}** | optional parameters | nil if no parameters + +### Optional Parameters +Optional parameters are passed through a map[string]interface{}. Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **petId** | **int64**| Pet id to delete | - **apiKey** | **string**| | [optional] - -Note: Optional parameters are passed through a map[string]interface{} + **apiKey** | **string**| | ### Return type -(empty response body) + (empty response body) ### Authorization @@ -76,18 +80,17 @@ Note: Optional parameters are passed through a map[string]interface{} [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **FindPetsByStatus** -> []Pet FindPetsByStatus($status) - +> []Pet FindPetsByStatus(ctx, status) Finds Pets by status Multiple status values can be provided with comma separated strings - -### Parameters +### Required Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **status** | [**[]string**](string.md)| Status values that need to be considered for filter | + **ctx** | **context.Context** | context containing the authentication | nil if no authentication + **status** | [**[]string**](string.md)| Status values that need to be considered for filter | ### Return type @@ -105,18 +108,17 @@ Name | Type | Description | Notes [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **FindPetsByTags** -> []Pet FindPetsByTags($tags) - +> []Pet FindPetsByTags(ctx, tags) Finds Pets by tags Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - -### Parameters +### Required Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **tags** | [**[]string**](string.md)| Tags to filter by | + **ctx** | **context.Context** | context containing the authentication | nil if no authentication + **tags** | [**[]string**](string.md)| Tags to filter by | ### Return type @@ -134,18 +136,17 @@ Name | Type | Description | Notes [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **GetPetById** -> Pet GetPetById($petId) - +> Pet GetPetById(ctx, petId) Find pet by ID Returns a single pet - -### Parameters +### Required Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **petId** | **int64**| ID of pet to return | + **ctx** | **context.Context** | context containing the authentication | nil if no authentication + **petId** | **int64**| ID of pet to return | ### Return type @@ -163,22 +164,21 @@ Name | Type | Description | Notes [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **UpdatePet** -> UpdatePet($body) - +> UpdatePet(ctx, body) Update an existing pet - -### Parameters +### Required Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + **ctx** | **context.Context** | context containing the authentication | nil if no authentication + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | ### Return type -(empty response body) + (empty response body) ### Authorization @@ -192,26 +192,31 @@ Name | Type | Description | Notes [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **UpdatePetWithForm** -> UpdatePetWithForm($petId, $name, $status) - +> UpdatePetWithForm(ctx, petId, optional) Updates a pet in the store with form data +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **ctx** | **context.Context** | context containing the authentication | nil if no authentication + **petId** | **int64**| ID of pet that needs to be updated | + **optional** | **map[string]interface{}** | optional parameters | nil if no parameters -### Parameters +### Optional Parameters +Optional parameters are passed through a map[string]interface{}. Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **petId** | **int64**| ID of pet that needs to be updated | - **name** | **string**| Updated name of the pet | [optional] - **status** | **string**| Updated status of the pet | [optional] - -Note: Optional parameters are passed through a map[string]interface{} + **name** | **string**| Updated name of the pet | + **status** | **string**| Updated status of the pet | ### Return type -(empty response body) + (empty response body) ### Authorization @@ -225,22 +230,27 @@ Note: Optional parameters are passed through a map[string]interface{} [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **UploadFile** -> ModelApiResponse UploadFile($petId, $additionalMetadata, $file) - +> ModelApiResponse UploadFile(ctx, petId, optional) uploads an image +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **ctx** | **context.Context** | context containing the authentication | nil if no authentication + **petId** | **int64**| ID of pet to update | + **optional** | **map[string]interface{}** | optional parameters | nil if no parameters -### Parameters +### Optional Parameters +Optional parameters are passed through a map[string]interface{}. Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **petId** | **int64**| ID of pet to update | - **additionalMetadata** | **string**| Additional data to pass to server | [optional] - **file** | ***os.File**| file to upload | [optional] - -Note: Optional parameters are passed through a map[string]interface{} + **additionalMetadata** | **string**| Additional data to pass to server | + **file** | ***os.File**| file to upload | ### Return type diff --git a/samples/client/petstore/go/go-petstore/docs/StoreApi.md b/samples/client/petstore/go/go-petstore/docs/StoreApi.md index af51c30d30b..fcc8d674d25 100644 --- a/samples/client/petstore/go/go-petstore/docs/StoreApi.md +++ b/samples/client/petstore/go/go-petstore/docs/StoreApi.md @@ -11,22 +11,20 @@ Method | HTTP request | Description # **DeleteOrder** -> DeleteOrder($orderId) - +> DeleteOrder(orderId) Delete purchase order by ID For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - -### Parameters +### Required Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **orderId** | **string**| ID of the order that needs to be deleted | + **orderId** | **string**| ID of the order that needs to be deleted | ### Return type -(empty response body) + (empty response body) ### Authorization @@ -40,14 +38,12 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **GetInventory** -> map[string]int32 GetInventory() - +> map[string]int32 GetInventory(ctx, ) Returns pet inventories by status Returns a map of status codes to quantities - -### Parameters +### Required Parameters This endpoint does not need any parameter. ### Return type @@ -66,18 +62,16 @@ This endpoint does not need any parameter. [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **GetOrderById** -> Order GetOrderById($orderId) - +> Order GetOrderById(orderId) Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - -### Parameters +### Required Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **orderId** | **int64**| ID of pet that needs to be fetched | + **orderId** | **int64**| ID of pet that needs to be fetched | ### Return type @@ -95,18 +89,16 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **PlaceOrder** -> Order PlaceOrder($body) - +> Order PlaceOrder(body) Place an order for a pet - -### Parameters +### Required Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**Order**](Order.md)| order placed for purchasing the pet | + **body** | [**Order**](Order.md)| order placed for purchasing the pet | ### Return type diff --git a/samples/client/petstore/go/go-petstore/docs/UserApi.md b/samples/client/petstore/go/go-petstore/docs/UserApi.md index 1e64bb36b83..ff61bdb170e 100644 --- a/samples/client/petstore/go/go-petstore/docs/UserApi.md +++ b/samples/client/petstore/go/go-petstore/docs/UserApi.md @@ -15,22 +15,20 @@ Method | HTTP request | Description # **CreateUser** -> CreateUser($body) - +> CreateUser(body) Create user This can only be done by the logged in user. - -### Parameters +### Required Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**User**](User.md)| Created user object | + **body** | [**User**](User.md)| Created user object | ### Return type -(empty response body) + (empty response body) ### Authorization @@ -44,22 +42,20 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **CreateUsersWithArrayInput** -> CreateUsersWithArrayInput($body) - +> CreateUsersWithArrayInput(body) Creates list of users with given input array - -### Parameters +### Required Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**[]User**](User.md)| List of user object | + **body** | [**[]User**](User.md)| List of user object | ### Return type -(empty response body) + (empty response body) ### Authorization @@ -73,22 +69,20 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **CreateUsersWithListInput** -> CreateUsersWithListInput($body) - +> CreateUsersWithListInput(body) Creates list of users with given input array - -### Parameters +### Required Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**[]User**](User.md)| List of user object | + **body** | [**[]User**](User.md)| List of user object | ### Return type -(empty response body) + (empty response body) ### Authorization @@ -102,22 +96,20 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **DeleteUser** -> DeleteUser($username) - +> DeleteUser(username) Delete user This can only be done by the logged in user. - -### Parameters +### Required Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **username** | **string**| The name that needs to be deleted | + **username** | **string**| The name that needs to be deleted | ### Return type -(empty response body) + (empty response body) ### Authorization @@ -131,18 +123,16 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **GetUserByName** -> User GetUserByName($username) - +> User GetUserByName(username) Get user by user name - -### Parameters +### Required Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **username** | **string**| The name that needs to be fetched. Use user1 for testing. | + **username** | **string**| The name that needs to be fetched. Use user1 for testing. | ### Return type @@ -160,19 +150,17 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **LoginUser** -> string LoginUser($username, $password) - +> string LoginUser(username, password) Logs user into the system - -### Parameters +### Required Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **username** | **string**| The user name for login | - **password** | **string**| The password for login in clear text | + **username** | **string**| The user name for login | + **password** | **string**| The password for login in clear text | ### Return type @@ -191,18 +179,16 @@ No authorization required # **LogoutUser** > LogoutUser() - Logs out current logged in user session - -### Parameters +### Required Parameters This endpoint does not need any parameter. ### Return type -(empty response body) + (empty response body) ### Authorization @@ -216,23 +202,21 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **UpdateUser** -> UpdateUser($username, $body) - +> UpdateUser(username, body) Updated user This can only be done by the logged in user. - -### Parameters +### Required Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **username** | **string**| name that need to be deleted | - **body** | [**User**](User.md)| Updated user object | + **username** | **string**| name that need to be deleted | + **body** | [**User**](User.md)| Updated user object | ### Return type -(empty response body) + (empty response body) ### Authorization diff --git a/samples/client/petstore/go/go-petstore/fake_api.go b/samples/client/petstore/go/go-petstore/fake_api.go index 282c0d50b36..c84371068b1 100644 --- a/samples/client/petstore/go/go-petstore/fake_api.go +++ b/samples/client/petstore/go/go-petstore/fake_api.go @@ -12,144 +12,172 @@ package petstore import ( "net/url" + "net/http" "strings" + "golang.org/x/net/context" "time" "encoding/json" ) -type FakeApi struct { - Configuration *Configuration -} +// Linger please +var ( + _ context.Context +) -func NewFakeApi() *FakeApi { - configuration := NewConfiguration() - return &FakeApi{ - Configuration: configuration, - } -} +type FakeApiService service -func NewFakeApiWithBasePath(basePath string) *FakeApi { - configuration := NewConfiguration() - configuration.BasePath = basePath - return &FakeApi{ - Configuration: configuration, - } -} +/* FakeApiService To test \"client\" model + To test \"client\" model -/** - * To test \"client\" model - * To test \"client\" model - * - * @param body client model - * @return *Client - */ -func (a FakeApi) TestClientModel(body Client) (*Client, *APIResponse, error) { + @param body client model + @return Client*/ +func (a *FakeApiService) TestClientModel(body Client) (Client, *http.Response, error) { + var ( + localVarHttpMethod = strings.ToUpper("Patch") + localVarPostBody interface{} + localVarFileName string + localVarFileBytes []byte + successPayload Client + ) - var localVarHttpMethod = strings.ToUpper("Patch") // create path and map variables - localVarPath := a.Configuration.BasePath + "/fake" + localVarPath := a.client.cfg.BasePath + "/fake" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} - localVarFormParams := make(map[string]string) - var localVarPostBody interface{} - var localVarFileName string - var localVarFileBytes []byte - // add default headers if any - for key := range a.Configuration.DefaultHeader { - localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] - } + localVarFormParams := url.Values{} + // to determine the Content-Type header localVarHttpContentTypes := []string{ "application/json", } // set Content-Type header - localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) + localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } + // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/json", } // set Accept header - localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) + localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // body params localVarPostBody = &body - var successPayload = new(Client) - localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - - var localVarURL, _ = url.Parse(localVarPath) - localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "TestClientModel", Method: localVarHttpMethod, RequestURL: localVarURL.String()} - if localVarHttpResponse != nil { - localVarAPIResponse.Response = localVarHttpResponse.RawResponse - localVarAPIResponse.Payload = localVarHttpResponse.Body() + r, err := a.client.prepareRequest(nil, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + if err != nil { + return successPayload, nil, err } - if err != nil { - return successPayload, localVarAPIResponse, err + localVarHttpResponse, err := a.client.callAPI(r) + if err != nil || localVarHttpResponse == nil { + return successPayload, localVarHttpResponse, err + } + defer localVarHttpResponse.Body.Close() + if localVarHttpResponse.StatusCode >= 300 { + return successPayload, localVarHttpResponse, reportError(localVarHttpResponse.Status) + } + + if err = json.NewDecoder(localVarHttpResponse.Body).Decode(&successPayload); err != nil { + return successPayload, localVarHttpResponse, err } - err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) - return successPayload, localVarAPIResponse, err + + + return successPayload, localVarHttpResponse, err } -/** - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * - * @param number None - * @param double None - * @param patternWithoutDelimiter None - * @param byte_ None - * @param optional (nil or map[string]interface{}) with one or more of: - * @param "integer" (int32) None - * @param "int32_" (int32) None - * @param "int64_" (int64) None - * @param "float" (float32) None - * @param "string_" (string) None - * @param "binary" (string) None - * @param "date" (time.Time) None - * @param "dateTime" (time.Time) None - * @param "password" (string) None - * @param "callback" (string) None - * @return - */ -func (a FakeApi) TestEndpointParameters(number float32, double float64, patternWithoutDelimiter string, byte_ string, localVarOptionals map[string]interface{}) (*APIResponse, error) { +/* FakeApiService Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * @param ctx context.Context Authentication Context + @param number None + @param double None + @param patternWithoutDelimiter None + @param byte_ None + @param optional (nil or map[string]interface{}) with one or more of: + @param "integer" (int32) None + @param "int32_" (int32) None + @param "int64_" (int64) None + @param "float" (float32) None + @param "string_" (string) None + @param "binary" (string) None + @param "date" (string) None + @param "dateTime" (time.Time) None + @param "password" (string) None + @param "callback" (string) None + @return */ +func (a *FakeApiService) TestEndpointParameters(ctx context.Context, number float32, double float64, patternWithoutDelimiter string, byte_ string, localVarOptionals map[string]interface{}) ( *http.Response, error) { + var ( + localVarHttpMethod = strings.ToUpper("Post") + localVarPostBody interface{} + localVarFileName string + localVarFileBytes []byte + ) - var localVarHttpMethod = strings.ToUpper("Post") // create path and map variables - localVarPath := a.Configuration.BasePath + "/fake" + localVarPath := a.client.cfg.BasePath + "/fake" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} - localVarFormParams := make(map[string]string) - var localVarPostBody interface{} - var localVarFileName string - var localVarFileBytes []byte - // authentication '(http_basic_test)' required - // http basic authentication required - if a.Configuration.Username != "" || a.Configuration.Password != ""{ - localVarHeaderParams["Authorization"] = "Basic " + a.Configuration.GetBasicAuthEncodedString() + localVarFormParams := url.Values{} + + if number < 32.10000000000000142108547152020037174224853515625 { + return nil, reportError("number must be greater than 32.10000000000000142108547152020037174224853515625") + } + if number > 543.200000000000045474735088646411895751953125 { + return nil, reportError("number must be less than 543.200000000000045474735088646411895751953125") + } + if double < 67.7999999999999971578290569595992565155029296875 { + return nil, reportError("double must be greater than 67.7999999999999971578290569595992565155029296875") + } + if double > 123.400000000000005684341886080801486968994140625 { + return nil, reportError("double must be less than 123.400000000000005684341886080801486968994140625") + } + if err := typeCheckParameter(localVarOptionals["integer"], "int32", "integer"); err != nil { + return nil, err + } + if err := typeCheckParameter(localVarOptionals["int32_"], "int32", "int32_"); err != nil { + return nil, err + } + if err := typeCheckParameter(localVarOptionals["int64_"], "int64", "int64_"); err != nil { + return nil, err } - // add default headers if any - for key := range a.Configuration.DefaultHeader { - localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] + if err := typeCheckParameter(localVarOptionals["float"], "float32", "float"); err != nil { + return nil, err + } + if err := typeCheckParameter(localVarOptionals["string_"], "string", "string_"); err != nil { + return nil, err + } + if err := typeCheckParameter(localVarOptionals["binary"], "string", "binary"); err != nil { + return nil, err + } + if err := typeCheckParameter(localVarOptionals["date"], "string", "date"); err != nil { + return nil, err + } + if err := typeCheckParameter(localVarOptionals["dateTime"], "time.Time", "dateTime"); err != nil { + return nil, err + } + if err := typeCheckParameter(localVarOptionals["password"], "string", "password"); err != nil { + return nil, err + } + if err := typeCheckParameter(localVarOptionals["callback"], "string", "callback"); err != nil { + return nil, err } // to determine the Content-Type header localVarHttpContentTypes := []string{ "application/xml; charset=utf-8", "application/json; charset=utf-8", } // set Content-Type header - localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) + localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } + // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/xml; charset=utf-8", @@ -157,148 +185,162 @@ func (a FakeApi) TestEndpointParameters(number float32, double float64, patternW } // set Accept header - localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) + localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } - if localVarTempParam, localVarOk := localVarOptionals["integer"].(int32); localVarOptionals != nil && localVarOk { - localVarFormParams["integer"] = a.Configuration.APIClient.ParameterToString(localVarTempParam, "") + if localVarTempParam, localVarOk := localVarOptionals["integer"].(int32); localVarOk { + localVarFormParams.Add("integer", parameterToString(localVarTempParam, "")) } - if localVarTempParam, localVarOk := localVarOptionals["int32_"].(int32); localVarOptionals != nil && localVarOk { - localVarFormParams["int32"] = a.Configuration.APIClient.ParameterToString(localVarTempParam, "") + if localVarTempParam, localVarOk := localVarOptionals["int32_"].(int32); localVarOk { + localVarFormParams.Add("int32", parameterToString(localVarTempParam, "")) } - if localVarTempParam, localVarOk := localVarOptionals["int64_"].(int64); localVarOptionals != nil && localVarOk { - localVarFormParams["int64"] = a.Configuration.APIClient.ParameterToString(localVarTempParam, "") + if localVarTempParam, localVarOk := localVarOptionals["int64_"].(int64); localVarOk { + localVarFormParams.Add("int64", parameterToString(localVarTempParam, "")) } - localVarFormParams["number"] = a.Configuration.APIClient.ParameterToString(number, "") - if localVarTempParam, localVarOk := localVarOptionals["float"].(float32); localVarOptionals != nil && localVarOk { - localVarFormParams["float"] = a.Configuration.APIClient.ParameterToString(localVarTempParam, "") + localVarFormParams.Add("number", parameterToString(number, "")) + if localVarTempParam, localVarOk := localVarOptionals["float"].(float32); localVarOk { + localVarFormParams.Add("float", parameterToString(localVarTempParam, "")) } - localVarFormParams["double"] = a.Configuration.APIClient.ParameterToString(double, "") - if localVarTempParam, localVarOk := localVarOptionals["string_"].(string); localVarOptionals != nil && localVarOk { - localVarFormParams["string"] = a.Configuration.APIClient.ParameterToString(localVarTempParam, "") + localVarFormParams.Add("double", parameterToString(double, "")) + if localVarTempParam, localVarOk := localVarOptionals["string_"].(string); localVarOk { + localVarFormParams.Add("string", parameterToString(localVarTempParam, "")) } - localVarFormParams["pattern_without_delimiter"] = a.Configuration.APIClient.ParameterToString(patternWithoutDelimiter, "") - localVarFormParams["byte"] = a.Configuration.APIClient.ParameterToString(byte_, "") - if localVarTempParam, localVarOk := localVarOptionals["binary"].(string); localVarOptionals != nil && localVarOk { - localVarFormParams["binary"] = a.Configuration.APIClient.ParameterToString(localVarTempParam, "") + localVarFormParams.Add("pattern_without_delimiter", parameterToString(patternWithoutDelimiter, "")) + localVarFormParams.Add("byte", parameterToString(byte_, "")) + if localVarTempParam, localVarOk := localVarOptionals["binary"].(string); localVarOk { + localVarFormParams.Add("binary", parameterToString(localVarTempParam, "")) } - if localVarTempParam, localVarOk := localVarOptionals["date"].(time.Time); localVarOptionals != nil && localVarOk { - localVarFormParams["date"] = a.Configuration.APIClient.ParameterToString(localVarTempParam, "") + if localVarTempParam, localVarOk := localVarOptionals["date"].(string); localVarOk { + localVarFormParams.Add("date", parameterToString(localVarTempParam, "")) } - if localVarTempParam, localVarOk := localVarOptionals["dateTime"].(time.Time); localVarOptionals != nil && localVarOk { - localVarFormParams["dateTime"] = a.Configuration.APIClient.ParameterToString(localVarTempParam, "") + if localVarTempParam, localVarOk := localVarOptionals["dateTime"].(time.Time); localVarOk { + localVarFormParams.Add("dateTime", parameterToString(localVarTempParam, "")) } - if localVarTempParam, localVarOk := localVarOptionals["password"].(string); localVarOptionals != nil && localVarOk { - localVarFormParams["password"] = a.Configuration.APIClient.ParameterToString(localVarTempParam, "") + if localVarTempParam, localVarOk := localVarOptionals["password"].(string); localVarOk { + localVarFormParams.Add("password", parameterToString(localVarTempParam, "")) } - if localVarTempParam, localVarOk := localVarOptionals["callback"].(string); localVarOptionals != nil && localVarOk { - localVarFormParams["callback"] = a.Configuration.APIClient.ParameterToString(localVarTempParam, "") + if localVarTempParam, localVarOk := localVarOptionals["callback"].(string); localVarOk { + localVarFormParams.Add("callback", parameterToString(localVarTempParam, "")) } - localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - - var localVarURL, _ = url.Parse(localVarPath) - localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "TestEndpointParameters", Method: localVarHttpMethod, RequestURL: localVarURL.String()} - if localVarHttpResponse != nil { - localVarAPIResponse.Response = localVarHttpResponse.RawResponse - localVarAPIResponse.Payload = localVarHttpResponse.Body() - } - + r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { - return localVarAPIResponse, err + return nil, err } - return localVarAPIResponse, err + + localVarHttpResponse, err := a.client.callAPI(r) + if err != nil || localVarHttpResponse == nil { + return localVarHttpResponse, err + } + defer localVarHttpResponse.Body.Close() + if localVarHttpResponse.StatusCode >= 300 { + return localVarHttpResponse, reportError(localVarHttpResponse.Status) + } + + return localVarHttpResponse, err } -/** - * To test enum parameters - * To test enum parameters - * - * @param optional (nil or map[string]interface{}) with one or more of: - * @param "enumFormStringArray" ([]string) Form parameter enum test (string array) - * @param "enumFormString" (string) Form parameter enum test (string) - * @param "enumHeaderStringArray" ([]string) Header parameter enum test (string array) - * @param "enumHeaderString" (string) Header parameter enum test (string) - * @param "enumQueryStringArray" ([]string) Query parameter enum test (string array) - * @param "enumQueryString" (string) Query parameter enum test (string) - * @param "enumQueryInteger" (int32) Query parameter enum test (double) - * @param "enumQueryDouble" (float64) Query parameter enum test (double) - * @return - */ -func (a FakeApi) TestEnumParameters(localVarOptionals map[string]interface{}) (*APIResponse, error) { +/* FakeApiService To test enum parameters + To test enum parameters + + @param optional (nil or map[string]interface{}) with one or more of: + @param "enumFormStringArray" ([]string) Form parameter enum test (string array) + @param "enumFormString" (string) Form parameter enum test (string) + @param "enumHeaderStringArray" ([]string) Header parameter enum test (string array) + @param "enumHeaderString" (string) Header parameter enum test (string) + @param "enumQueryStringArray" ([]string) Query parameter enum test (string array) + @param "enumQueryString" (string) Query parameter enum test (string) + @param "enumQueryInteger" (int32) Query parameter enum test (double) + @param "enumQueryDouble" (float64) Query parameter enum test (double) + @return */ +func (a *FakeApiService) TestEnumParameters(localVarOptionals map[string]interface{}) ( *http.Response, error) { + var ( + localVarHttpMethod = strings.ToUpper("Get") + localVarPostBody interface{} + localVarFileName string + localVarFileBytes []byte + ) - var localVarHttpMethod = strings.ToUpper("Get") // create path and map variables - localVarPath := a.Configuration.BasePath + "/fake" + localVarPath := a.client.cfg.BasePath + "/fake" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} - localVarFormParams := make(map[string]string) - var localVarPostBody interface{} - var localVarFileName string - var localVarFileBytes []byte - // add default headers if any - for key := range a.Configuration.DefaultHeader { - localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] + localVarFormParams := url.Values{} + + if err := typeCheckParameter(localVarOptionals["enumFormString"], "string", "enumFormString"); err != nil { + return nil, err } - var enumQueryStringArrayCollectionFormat = "csv" - if localVarTempParam, localVarOk := localVarOptionals["enumQueryStringArray"].([]string); localVarOptionals != nil && localVarOk { - localVarQueryParams.Add("enum_query_string_array", a.Configuration.APIClient.ParameterToString(localVarTempParam, enumQueryStringArrayCollectionFormat)) + if err := typeCheckParameter(localVarOptionals["enumHeaderString"], "string", "enumHeaderString"); err != nil { + return nil, err } - if localVarTempParam, localVarOk := localVarOptionals["enumQueryString"].(string); localVarOptionals != nil && localVarOk { - localVarQueryParams.Add("enum_query_string", a.Configuration.APIClient.ParameterToString(localVarTempParam, "")) + if err := typeCheckParameter(localVarOptionals["enumQueryString"], "string", "enumQueryString"); err != nil { + return nil, err + } + if err := typeCheckParameter(localVarOptionals["enumQueryInteger"], "int32", "enumQueryInteger"); err != nil { + return nil, err } - if localVarTempParam, localVarOk := localVarOptionals["enumQueryInteger"].(int32); localVarOptionals != nil && localVarOk { - localVarQueryParams.Add("enum_query_integer", a.Configuration.APIClient.ParameterToString(localVarTempParam, "")) + if err := typeCheckParameter(localVarOptionals["enumQueryDouble"], "float64", "enumQueryDouble"); err != nil { + return nil, err } + if localVarTempParam, localVarOk := localVarOptionals["enumQueryStringArray"].([]string); localVarOk { + localVarQueryParams.Add("enum_query_string_array", parameterToString(localVarTempParam, "csv")) + } + if localVarTempParam, localVarOk := localVarOptionals["enumQueryString"].(string); localVarOk { + localVarQueryParams.Add("enum_query_string", parameterToString(localVarTempParam, "")) + } + if localVarTempParam, localVarOk := localVarOptionals["enumQueryInteger"].(int32); localVarOk { + localVarQueryParams.Add("enum_query_integer", parameterToString(localVarTempParam, "")) + } // to determine the Content-Type header localVarHttpContentTypes := []string{ "*/*", } // set Content-Type header - localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) + localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } + // to determine the Accept header localVarHttpHeaderAccepts := []string{ "*/*", } // set Accept header - localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) + localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } - if localVarTempParam, localVarOk := localVarOptionals["enumHeaderStringArray"].([]string); localVarOptionals != nil && localVarOk { - localVarHeaderParams["enum_header_string_array"] = a.Configuration.APIClient.ParameterToString(localVarTempParam, "csv") - } - if localVarTempParam, localVarOk := localVarOptionals["enumHeaderString"].(string); localVarOptionals != nil && localVarOk { - localVarHeaderParams["enum_header_string"] = a.Configuration.APIClient.ParameterToString(localVarTempParam, "") + if localVarTempParam, localVarOk := localVarOptionals["enumHeaderStringArray"].([]string); localVarOk { + localVarHeaderParams["enum_header_string_array"] = parameterToString(localVarTempParam, "csv") } - if localVarTempParam, localVarOk := localVarOptionals["enumFormStringArray"].([]string); localVarOptionals != nil && localVarOk { - localVarFormParams["enum_form_string_array"] = a.Configuration.APIClient.ParameterToString(localVarTempParam, "csv") + if localVarTempParam, localVarOk := localVarOptionals["enumHeaderString"].(string); localVarOk { + localVarHeaderParams["enum_header_string"] = parameterToString(localVarTempParam, "") } - if localVarTempParam, localVarOk := localVarOptionals["enumFormString"].(string); localVarOptionals != nil && localVarOk { - localVarFormParams["enum_form_string"] = a.Configuration.APIClient.ParameterToString(localVarTempParam, "") + if localVarTempParam, localVarOk := localVarOptionals["enumFormStringArray"].([]string); localVarOk { + localVarFormParams.Add("enum_form_string_array", parameterToString(localVarTempParam, "csv")) } - if localVarTempParam, localVarOk := localVarOptionals["enumQueryDouble"].(float64); localVarOptionals != nil && localVarOk { - localVarFormParams["enum_query_double"] = a.Configuration.APIClient.ParameterToString(localVarTempParam, "") + if localVarTempParam, localVarOk := localVarOptionals["enumFormString"].(string); localVarOk { + localVarFormParams.Add("enum_form_string", parameterToString(localVarTempParam, "")) } - localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - - var localVarURL, _ = url.Parse(localVarPath) - localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "TestEnumParameters", Method: localVarHttpMethod, RequestURL: localVarURL.String()} - if localVarHttpResponse != nil { - localVarAPIResponse.Response = localVarHttpResponse.RawResponse - localVarAPIResponse.Payload = localVarHttpResponse.Body() + if localVarTempParam, localVarOk := localVarOptionals["enumQueryDouble"].(float64); localVarOk { + localVarFormParams.Add("enum_query_double", parameterToString(localVarTempParam, "")) } - + r, err := a.client.prepareRequest(nil, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { - return localVarAPIResponse, err + return nil, err } - return localVarAPIResponse, err + + localVarHttpResponse, err := a.client.callAPI(r) + if err != nil || localVarHttpResponse == nil { + return localVarHttpResponse, err + } + defer localVarHttpResponse.Body.Close() + if localVarHttpResponse.StatusCode >= 300 { + return localVarHttpResponse, reportError(localVarHttpResponse.Status) + } + + return localVarHttpResponse, err } diff --git a/samples/client/petstore/go/go-petstore/fake_classname_tags123_api.go b/samples/client/petstore/go/go-petstore/fake_classname_tags123_api.go index 5cafce5e20a..1154155250c 100644 --- a/samples/client/petstore/go/go-petstore/fake_classname_tags123_api.go +++ b/samples/client/petstore/go/go-petstore/fake_classname_tags123_api.go @@ -12,88 +12,81 @@ package petstore import ( "net/url" + "net/http" "strings" + "golang.org/x/net/context" "encoding/json" ) -type Fake_classname_tags123Api struct { - Configuration *Configuration -} +// Linger please +var ( + _ context.Context +) -func NewFake_classname_tags123Api() *Fake_classname_tags123Api { - configuration := NewConfiguration() - return &Fake_classname_tags123Api{ - Configuration: configuration, - } -} +type Fake_classname_tags123ApiService service -func NewFake_classname_tags123ApiWithBasePath(basePath string) *Fake_classname_tags123Api { - configuration := NewConfiguration() - configuration.BasePath = basePath - return &Fake_classname_tags123Api{ - Configuration: configuration, - } -} +/* Fake_classname_tags123ApiService To test class name in snake case -/** - * To test class name in snake case - * - * @param body client model - * @return *Client - */ -func (a Fake_classname_tags123Api) TestClassname(body Client) (*Client, *APIResponse, error) { + @param body client model + @return Client*/ +func (a *Fake_classname_tags123ApiService) TestClassname(body Client) (Client, *http.Response, error) { + var ( + localVarHttpMethod = strings.ToUpper("Patch") + localVarPostBody interface{} + localVarFileName string + localVarFileBytes []byte + successPayload Client + ) - var localVarHttpMethod = strings.ToUpper("Patch") // create path and map variables - localVarPath := a.Configuration.BasePath + "/fake_classname_test" + localVarPath := a.client.cfg.BasePath + "/fake_classname_test" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} - localVarFormParams := make(map[string]string) - var localVarPostBody interface{} - var localVarFileName string - var localVarFileBytes []byte - // add default headers if any - for key := range a.Configuration.DefaultHeader { - localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] - } + localVarFormParams := url.Values{} + // to determine the Content-Type header localVarHttpContentTypes := []string{ "application/json", } // set Content-Type header - localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) + localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } + // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/json", } // set Accept header - localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) + localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // body params localVarPostBody = &body - var successPayload = new(Client) - localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - - var localVarURL, _ = url.Parse(localVarPath) - localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "TestClassname", Method: localVarHttpMethod, RequestURL: localVarURL.String()} - if localVarHttpResponse != nil { - localVarAPIResponse.Response = localVarHttpResponse.RawResponse - localVarAPIResponse.Payload = localVarHttpResponse.Body() + r, err := a.client.prepareRequest(nil, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + if err != nil { + return successPayload, nil, err } - if err != nil { - return successPayload, localVarAPIResponse, err + localVarHttpResponse, err := a.client.callAPI(r) + if err != nil || localVarHttpResponse == nil { + return successPayload, localVarHttpResponse, err + } + defer localVarHttpResponse.Body.Close() + if localVarHttpResponse.StatusCode >= 300 { + return successPayload, localVarHttpResponse, reportError(localVarHttpResponse.Status) + } + + if err = json.NewDecoder(localVarHttpResponse.Body).Decode(&successPayload); err != nil { + return successPayload, localVarHttpResponse, err } - err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) - return successPayload, localVarAPIResponse, err + + + return successPayload, localVarHttpResponse, err } diff --git a/samples/client/petstore/go/go-petstore/format_test.go b/samples/client/petstore/go/go-petstore/format_test.go index 43125b9df34..bf9c945781c 100644 --- a/samples/client/petstore/go/go-petstore/format_test.go +++ b/samples/client/petstore/go/go-petstore/format_test.go @@ -34,7 +34,7 @@ type FormatTest struct { Binary string `json:"binary,omitempty"` - Date time.Time `json:"date"` + Date string `json:"date,omitempty"` DateTime time.Time `json:"dateTime,omitempty"` diff --git a/samples/client/petstore/go/go-petstore/pet_api.go b/samples/client/petstore/go/go-petstore/pet_api.go index 84984745dd5..f9a1ec37193 100644 --- a/samples/client/petstore/go/go-petstore/pet_api.go +++ b/samples/client/petstore/go/go-petstore/pet_api.go @@ -12,70 +12,53 @@ package petstore import ( "net/url" + "net/http" "strings" + "golang.org/x/net/context" "os" "io/ioutil" "encoding/json" "fmt" ) -type PetApi struct { - Configuration *Configuration -} +// Linger please +var ( + _ context.Context +) -func NewPetApi() *PetApi { - configuration := NewConfiguration() - return &PetApi{ - Configuration: configuration, - } -} +type PetApiService service -func NewPetApiWithBasePath(basePath string) *PetApi { - configuration := NewConfiguration() - configuration.BasePath = basePath - return &PetApi{ - Configuration: configuration, - } -} +/* PetApiService Add a new pet to the store + + * @param ctx context.Context Authentication Context + @param body Pet object that needs to be added to the store + @return */ +func (a *PetApiService) AddPet(ctx context.Context, body Pet) ( *http.Response, error) { + var ( + localVarHttpMethod = strings.ToUpper("Post") + localVarPostBody interface{} + localVarFileName string + localVarFileBytes []byte + ) -/** - * Add a new pet to the store - * - * - * @param body Pet object that needs to be added to the store - * @return - */ -func (a PetApi) AddPet(body Pet) (*APIResponse, error) { - - var localVarHttpMethod = strings.ToUpper("Post") // create path and map variables - localVarPath := a.Configuration.BasePath + "/pet" + localVarPath := a.client.cfg.BasePath + "/pet" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} - localVarFormParams := make(map[string]string) - var localVarPostBody interface{} - var localVarFileName string - var localVarFileBytes []byte - // authentication '(petstore_auth)' required - // oauth required - if a.Configuration.AccessToken != ""{ - localVarHeaderParams["Authorization"] = "Bearer " + a.Configuration.AccessToken - } - // add default headers if any - for key := range a.Configuration.DefaultHeader { - localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] - } + localVarFormParams := url.Values{} + // to determine the Content-Type header localVarHttpContentTypes := []string{ "application/json", "application/xml", } // set Content-Type header - localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) + localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } + // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/xml", @@ -83,68 +66,65 @@ func (a PetApi) AddPet(body Pet) (*APIResponse, error) { } // set Accept header - localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) + localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // body params localVarPostBody = &body - localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - - var localVarURL, _ = url.Parse(localVarPath) - localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "AddPet", Method: localVarHttpMethod, RequestURL: localVarURL.String()} - if localVarHttpResponse != nil { - localVarAPIResponse.Response = localVarHttpResponse.RawResponse - localVarAPIResponse.Payload = localVarHttpResponse.Body() - } - + r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { - return localVarAPIResponse, err + return nil, err } - return localVarAPIResponse, err + + localVarHttpResponse, err := a.client.callAPI(r) + if err != nil || localVarHttpResponse == nil { + return localVarHttpResponse, err + } + defer localVarHttpResponse.Body.Close() + if localVarHttpResponse.StatusCode >= 300 { + return localVarHttpResponse, reportError(localVarHttpResponse.Status) + } + + return localVarHttpResponse, err } -/** - * Deletes a pet - * - * - * @param petId Pet id to delete - * @param optional (nil or map[string]interface{}) with one or more of: - * @param "apiKey" (string) - * @return - */ -func (a PetApi) DeletePet(petId int64, localVarOptionals map[string]interface{}) (*APIResponse, error) { +/* PetApiService Deletes a pet + + * @param ctx context.Context Authentication Context + @param petId Pet id to delete + @param optional (nil or map[string]interface{}) with one or more of: + @param "apiKey" (string) + @return */ +func (a *PetApiService) DeletePet(ctx context.Context, petId int64, localVarOptionals map[string]interface{}) ( *http.Response, error) { + var ( + localVarHttpMethod = strings.ToUpper("Delete") + localVarPostBody interface{} + localVarFileName string + localVarFileBytes []byte + ) - var localVarHttpMethod = strings.ToUpper("Delete") // create path and map variables - localVarPath := a.Configuration.BasePath + "/pet/{petId}" + localVarPath := a.client.cfg.BasePath + "/pet/{petId}" localVarPath = strings.Replace(localVarPath, "{"+"petId"+"}", fmt.Sprintf("%v", petId), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} - localVarFormParams := make(map[string]string) - var localVarPostBody interface{} - var localVarFileName string - var localVarFileBytes []byte - // authentication '(petstore_auth)' required - // oauth required - if a.Configuration.AccessToken != ""{ - localVarHeaderParams["Authorization"] = "Bearer " + a.Configuration.AccessToken - } - // add default headers if any - for key := range a.Configuration.DefaultHeader { - localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] + localVarFormParams := url.Values{} + + if err := typeCheckParameter(localVarOptionals["apiKey"], "string", "apiKey"); err != nil { + return nil, err } // to determine the Content-Type header localVarHttpContentTypes := []string{ } // set Content-Type header - localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) + localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } + // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/xml", @@ -152,68 +132,61 @@ func (a PetApi) DeletePet(petId int64, localVarOptionals map[string]interface{}) } // set Accept header - localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) + localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } - if localVarTempParam, localVarOk := localVarOptionals["apiKey"].(string); localVarOptionals != nil && localVarOk { - localVarHeaderParams["api_key"] = a.Configuration.APIClient.ParameterToString(localVarTempParam, "") - } - localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - - var localVarURL, _ = url.Parse(localVarPath) - localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "DeletePet", Method: localVarHttpMethod, RequestURL: localVarURL.String()} - if localVarHttpResponse != nil { - localVarAPIResponse.Response = localVarHttpResponse.RawResponse - localVarAPIResponse.Payload = localVarHttpResponse.Body() + if localVarTempParam, localVarOk := localVarOptionals["apiKey"].(string); localVarOk { + localVarHeaderParams["api_key"] = parameterToString(localVarTempParam, "") } - + r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { - return localVarAPIResponse, err + return nil, err } - return localVarAPIResponse, err + + localVarHttpResponse, err := a.client.callAPI(r) + if err != nil || localVarHttpResponse == nil { + return localVarHttpResponse, err + } + defer localVarHttpResponse.Body.Close() + if localVarHttpResponse.StatusCode >= 300 { + return localVarHttpResponse, reportError(localVarHttpResponse.Status) + } + + return localVarHttpResponse, err } -/** - * Finds Pets by status - * Multiple status values can be provided with comma separated strings - * - * @param status Status values that need to be considered for filter - * @return []Pet - */ -func (a PetApi) FindPetsByStatus(status []string) ([]Pet, *APIResponse, error) { +/* PetApiService Finds Pets by status + Multiple status values can be provided with comma separated strings + * @param ctx context.Context Authentication Context + @param status Status values that need to be considered for filter + @return []Pet*/ +func (a *PetApiService) FindPetsByStatus(ctx context.Context, status []string) ([]Pet, *http.Response, error) { + var ( + localVarHttpMethod = strings.ToUpper("Get") + localVarPostBody interface{} + localVarFileName string + localVarFileBytes []byte + successPayload []Pet + ) - var localVarHttpMethod = strings.ToUpper("Get") // create path and map variables - localVarPath := a.Configuration.BasePath + "/pet/findByStatus" + localVarPath := a.client.cfg.BasePath + "/pet/findByStatus" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} - localVarFormParams := make(map[string]string) - var localVarPostBody interface{} - var localVarFileName string - var localVarFileBytes []byte - // authentication '(petstore_auth)' required - // oauth required - if a.Configuration.AccessToken != ""{ - localVarHeaderParams["Authorization"] = "Bearer " + a.Configuration.AccessToken - } - // add default headers if any - for key := range a.Configuration.DefaultHeader { - localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] - } - var statusCollectionFormat = "csv" - localVarQueryParams.Add("status", a.Configuration.APIClient.ParameterToString(status, statusCollectionFormat)) + localVarFormParams := url.Values{} + localVarQueryParams.Add("status", parameterToString(status, "csv")) // to determine the Content-Type header localVarHttpContentTypes := []string{ } // set Content-Type header - localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) + localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } + // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/xml", @@ -221,67 +194,63 @@ func (a PetApi) FindPetsByStatus(status []string) ([]Pet, *APIResponse, error) { } // set Accept header - localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) + localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } - var successPayload = new([]Pet) - localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - - var localVarURL, _ = url.Parse(localVarPath) - localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "FindPetsByStatus", Method: localVarHttpMethod, RequestURL: localVarURL.String()} - if localVarHttpResponse != nil { - localVarAPIResponse.Response = localVarHttpResponse.RawResponse - localVarAPIResponse.Payload = localVarHttpResponse.Body() + r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + if err != nil { + return successPayload, nil, err } - if err != nil { - return *successPayload, localVarAPIResponse, err + localVarHttpResponse, err := a.client.callAPI(r) + if err != nil || localVarHttpResponse == nil { + return successPayload, localVarHttpResponse, err + } + defer localVarHttpResponse.Body.Close() + if localVarHttpResponse.StatusCode >= 300 { + return successPayload, localVarHttpResponse, reportError(localVarHttpResponse.Status) + } + + if err = json.NewDecoder(localVarHttpResponse.Body).Decode(&successPayload); err != nil { + return successPayload, localVarHttpResponse, err } - err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) - return *successPayload, localVarAPIResponse, err + + + return successPayload, localVarHttpResponse, err } -/** - * Finds Pets by tags - * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - * - * @param tags Tags to filter by - * @return []Pet - */ -func (a PetApi) FindPetsByTags(tags []string) ([]Pet, *APIResponse, error) { +/* PetApiService Finds Pets by tags + Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param ctx context.Context Authentication Context + @param tags Tags to filter by + @return []Pet*/ +func (a *PetApiService) FindPetsByTags(ctx context.Context, tags []string) ([]Pet, *http.Response, error) { + var ( + localVarHttpMethod = strings.ToUpper("Get") + localVarPostBody interface{} + localVarFileName string + localVarFileBytes []byte + successPayload []Pet + ) - var localVarHttpMethod = strings.ToUpper("Get") // create path and map variables - localVarPath := a.Configuration.BasePath + "/pet/findByTags" + localVarPath := a.client.cfg.BasePath + "/pet/findByTags" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} - localVarFormParams := make(map[string]string) - var localVarPostBody interface{} - var localVarFileName string - var localVarFileBytes []byte - // authentication '(petstore_auth)' required - // oauth required - if a.Configuration.AccessToken != ""{ - localVarHeaderParams["Authorization"] = "Bearer " + a.Configuration.AccessToken - } - // add default headers if any - for key := range a.Configuration.DefaultHeader { - localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] - } - var tagsCollectionFormat = "csv" - localVarQueryParams.Add("tags", a.Configuration.APIClient.ParameterToString(tags, tagsCollectionFormat)) + localVarFormParams := url.Values{} + localVarQueryParams.Add("tags", parameterToString(tags, "csv")) // to determine the Content-Type header localVarHttpContentTypes := []string{ } // set Content-Type header - localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) + localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } + // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/xml", @@ -289,64 +258,64 @@ func (a PetApi) FindPetsByTags(tags []string) ([]Pet, *APIResponse, error) { } // set Accept header - localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) + localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } - var successPayload = new([]Pet) - localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - - var localVarURL, _ = url.Parse(localVarPath) - localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "FindPetsByTags", Method: localVarHttpMethod, RequestURL: localVarURL.String()} - if localVarHttpResponse != nil { - localVarAPIResponse.Response = localVarHttpResponse.RawResponse - localVarAPIResponse.Payload = localVarHttpResponse.Body() + r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + if err != nil { + return successPayload, nil, err } - if err != nil { - return *successPayload, localVarAPIResponse, err + localVarHttpResponse, err := a.client.callAPI(r) + if err != nil || localVarHttpResponse == nil { + return successPayload, localVarHttpResponse, err + } + defer localVarHttpResponse.Body.Close() + if localVarHttpResponse.StatusCode >= 300 { + return successPayload, localVarHttpResponse, reportError(localVarHttpResponse.Status) + } + + if err = json.NewDecoder(localVarHttpResponse.Body).Decode(&successPayload); err != nil { + return successPayload, localVarHttpResponse, err } - err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) - return *successPayload, localVarAPIResponse, err + + + return successPayload, localVarHttpResponse, err } -/** - * Find pet by ID - * Returns a single pet - * - * @param petId ID of pet to return - * @return *Pet - */ -func (a PetApi) GetPetById(petId int64) (*Pet, *APIResponse, error) { +/* PetApiService Find pet by ID + Returns a single pet + * @param ctx context.Context Authentication Context + @param petId ID of pet to return + @return Pet*/ +func (a *PetApiService) GetPetById(ctx context.Context, petId int64) (Pet, *http.Response, error) { + var ( + localVarHttpMethod = strings.ToUpper("Get") + localVarPostBody interface{} + localVarFileName string + localVarFileBytes []byte + successPayload Pet + ) - var localVarHttpMethod = strings.ToUpper("Get") // create path and map variables - localVarPath := a.Configuration.BasePath + "/pet/{petId}" + localVarPath := a.client.cfg.BasePath + "/pet/{petId}" localVarPath = strings.Replace(localVarPath, "{"+"petId"+"}", fmt.Sprintf("%v", petId), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} - localVarFormParams := make(map[string]string) - var localVarPostBody interface{} - var localVarFileName string - var localVarFileBytes []byte - // authentication '(api_key)' required - // set key with prefix in header - localVarHeaderParams["api_key"] = a.Configuration.GetAPIKeyWithPrefix("api_key") - // add default headers if any - for key := range a.Configuration.DefaultHeader { - localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] - } + localVarFormParams := url.Values{} + // to determine the Content-Type header localVarHttpContentTypes := []string{ } // set Content-Type header - localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) + localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } + // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/xml", @@ -354,65 +323,74 @@ func (a PetApi) GetPetById(petId int64) (*Pet, *APIResponse, error) { } // set Accept header - localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) + localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } - var successPayload = new(Pet) - localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - - var localVarURL, _ = url.Parse(localVarPath) - localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "GetPetById", Method: localVarHttpMethod, RequestURL: localVarURL.String()} - if localVarHttpResponse != nil { - localVarAPIResponse.Response = localVarHttpResponse.RawResponse - localVarAPIResponse.Payload = localVarHttpResponse.Body() + if ctx != nil { + // API Key Authentication + if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { + var key string + if auth.Prefix != "" { + key = auth.Prefix + " " + auth.Key + } else { + key = auth.Key + } + localVarHeaderParams["api_key"] = key + } } - + r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { - return successPayload, localVarAPIResponse, err + return successPayload, nil, err + } + + localVarHttpResponse, err := a.client.callAPI(r) + if err != nil || localVarHttpResponse == nil { + return successPayload, localVarHttpResponse, err + } + defer localVarHttpResponse.Body.Close() + if localVarHttpResponse.StatusCode >= 300 { + return successPayload, localVarHttpResponse, reportError(localVarHttpResponse.Status) + } + + if err = json.NewDecoder(localVarHttpResponse.Body).Decode(&successPayload); err != nil { + return successPayload, localVarHttpResponse, err } - err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) - return successPayload, localVarAPIResponse, err + + + return successPayload, localVarHttpResponse, err } -/** - * Update an existing pet - * - * - * @param body Pet object that needs to be added to the store - * @return - */ -func (a PetApi) UpdatePet(body Pet) (*APIResponse, error) { +/* PetApiService Update an existing pet + + * @param ctx context.Context Authentication Context + @param body Pet object that needs to be added to the store + @return */ +func (a *PetApiService) UpdatePet(ctx context.Context, body Pet) ( *http.Response, error) { + var ( + localVarHttpMethod = strings.ToUpper("Put") + localVarPostBody interface{} + localVarFileName string + localVarFileBytes []byte + ) - var localVarHttpMethod = strings.ToUpper("Put") // create path and map variables - localVarPath := a.Configuration.BasePath + "/pet" + localVarPath := a.client.cfg.BasePath + "/pet" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} - localVarFormParams := make(map[string]string) - var localVarPostBody interface{} - var localVarFileName string - var localVarFileBytes []byte - // authentication '(petstore_auth)' required - // oauth required - if a.Configuration.AccessToken != ""{ - localVarHeaderParams["Authorization"] = "Bearer " + a.Configuration.AccessToken - } - // add default headers if any - for key := range a.Configuration.DefaultHeader { - localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] - } + localVarFormParams := url.Values{} + // to determine the Content-Type header localVarHttpContentTypes := []string{ "application/json", "application/xml", } // set Content-Type header - localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) + localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } + // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/xml", @@ -420,69 +398,69 @@ func (a PetApi) UpdatePet(body Pet) (*APIResponse, error) { } // set Accept header - localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) + localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // body params localVarPostBody = &body - localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - - var localVarURL, _ = url.Parse(localVarPath) - localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "UpdatePet", Method: localVarHttpMethod, RequestURL: localVarURL.String()} - if localVarHttpResponse != nil { - localVarAPIResponse.Response = localVarHttpResponse.RawResponse - localVarAPIResponse.Payload = localVarHttpResponse.Body() - } - + r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { - return localVarAPIResponse, err + return nil, err } - return localVarAPIResponse, err + + localVarHttpResponse, err := a.client.callAPI(r) + if err != nil || localVarHttpResponse == nil { + return localVarHttpResponse, err + } + defer localVarHttpResponse.Body.Close() + if localVarHttpResponse.StatusCode >= 300 { + return localVarHttpResponse, reportError(localVarHttpResponse.Status) + } + + return localVarHttpResponse, err } -/** - * Updates a pet in the store with form data - * - * - * @param petId ID of pet that needs to be updated - * @param optional (nil or map[string]interface{}) with one or more of: - * @param "name" (string) Updated name of the pet - * @param "status" (string) Updated status of the pet - * @return - */ -func (a PetApi) UpdatePetWithForm(petId int64, localVarOptionals map[string]interface{}) (*APIResponse, error) { +/* PetApiService Updates a pet in the store with form data + + * @param ctx context.Context Authentication Context + @param petId ID of pet that needs to be updated + @param optional (nil or map[string]interface{}) with one or more of: + @param "name" (string) Updated name of the pet + @param "status" (string) Updated status of the pet + @return */ +func (a *PetApiService) UpdatePetWithForm(ctx context.Context, petId int64, localVarOptionals map[string]interface{}) ( *http.Response, error) { + var ( + localVarHttpMethod = strings.ToUpper("Post") + localVarPostBody interface{} + localVarFileName string + localVarFileBytes []byte + ) - var localVarHttpMethod = strings.ToUpper("Post") // create path and map variables - localVarPath := a.Configuration.BasePath + "/pet/{petId}" + localVarPath := a.client.cfg.BasePath + "/pet/{petId}" localVarPath = strings.Replace(localVarPath, "{"+"petId"+"}", fmt.Sprintf("%v", petId), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} - localVarFormParams := make(map[string]string) - var localVarPostBody interface{} - var localVarFileName string - var localVarFileBytes []byte - // authentication '(petstore_auth)' required - // oauth required - if a.Configuration.AccessToken != ""{ - localVarHeaderParams["Authorization"] = "Bearer " + a.Configuration.AccessToken + localVarFormParams := url.Values{} + + if err := typeCheckParameter(localVarOptionals["name"], "string", "name"); err != nil { + return nil, err } - // add default headers if any - for key := range a.Configuration.DefaultHeader { - localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] + if err := typeCheckParameter(localVarOptionals["status"], "string", "status"); err != nil { + return nil, err } // to determine the Content-Type header localVarHttpContentTypes := []string{ "application/x-www-form-urlencoded", } // set Content-Type header - localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) + localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } + // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/xml", @@ -490,110 +468,113 @@ func (a PetApi) UpdatePetWithForm(petId int64, localVarOptionals map[string]inte } // set Accept header - localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) + localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } - if localVarTempParam, localVarOk := localVarOptionals["name"].(string); localVarOptionals != nil && localVarOk { - localVarFormParams["name"] = a.Configuration.APIClient.ParameterToString(localVarTempParam, "") + if localVarTempParam, localVarOk := localVarOptionals["name"].(string); localVarOk { + localVarFormParams.Add("name", parameterToString(localVarTempParam, "")) } - if localVarTempParam, localVarOk := localVarOptionals["status"].(string); localVarOptionals != nil && localVarOk { - localVarFormParams["status"] = a.Configuration.APIClient.ParameterToString(localVarTempParam, "") + if localVarTempParam, localVarOk := localVarOptionals["status"].(string); localVarOk { + localVarFormParams.Add("status", parameterToString(localVarTempParam, "")) } - localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - - var localVarURL, _ = url.Parse(localVarPath) - localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "UpdatePetWithForm", Method: localVarHttpMethod, RequestURL: localVarURL.String()} - if localVarHttpResponse != nil { - localVarAPIResponse.Response = localVarHttpResponse.RawResponse - localVarAPIResponse.Payload = localVarHttpResponse.Body() - } - + r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { - return localVarAPIResponse, err + return nil, err } - return localVarAPIResponse, err + + localVarHttpResponse, err := a.client.callAPI(r) + if err != nil || localVarHttpResponse == nil { + return localVarHttpResponse, err + } + defer localVarHttpResponse.Body.Close() + if localVarHttpResponse.StatusCode >= 300 { + return localVarHttpResponse, reportError(localVarHttpResponse.Status) + } + + return localVarHttpResponse, err } -/** - * uploads an image - * - * - * @param petId ID of pet to update - * @param optional (nil or map[string]interface{}) with one or more of: - * @param "additionalMetadata" (string) Additional data to pass to server - * @param "file" (*os.File) file to upload - * @return *ModelApiResponse - */ -func (a PetApi) UploadFile(petId int64, localVarOptionals map[string]interface{}) (*ModelApiResponse, *APIResponse, error) { +/* PetApiService uploads an image + + * @param ctx context.Context Authentication Context + @param petId ID of pet to update + @param optional (nil or map[string]interface{}) with one or more of: + @param "additionalMetadata" (string) Additional data to pass to server + @param "file" (*os.File) file to upload + @return ModelApiResponse*/ +func (a *PetApiService) UploadFile(ctx context.Context, petId int64, localVarOptionals map[string]interface{}) (ModelApiResponse, *http.Response, error) { + var ( + localVarHttpMethod = strings.ToUpper("Post") + localVarPostBody interface{} + localVarFileName string + localVarFileBytes []byte + successPayload ModelApiResponse + ) - var localVarHttpMethod = strings.ToUpper("Post") // create path and map variables - localVarPath := a.Configuration.BasePath + "/pet/{petId}/uploadImage" + localVarPath := a.client.cfg.BasePath + "/pet/{petId}/uploadImage" localVarPath = strings.Replace(localVarPath, "{"+"petId"+"}", fmt.Sprintf("%v", petId), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} - localVarFormParams := make(map[string]string) - var localVarPostBody interface{} - var localVarFileName string - var localVarFileBytes []byte - // authentication '(petstore_auth)' required - // oauth required - if a.Configuration.AccessToken != ""{ - localVarHeaderParams["Authorization"] = "Bearer " + a.Configuration.AccessToken - } - // add default headers if any - for key := range a.Configuration.DefaultHeader { - localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] + localVarFormParams := url.Values{} + + if err := typeCheckParameter(localVarOptionals["additionalMetadata"], "string", "additionalMetadata"); err != nil { + return successPayload, nil, err } // to determine the Content-Type header localVarHttpContentTypes := []string{ "multipart/form-data", } // set Content-Type header - localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) + localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } + // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/json", } // set Accept header - localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) + localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } - if localVarTempParam, localVarOk := localVarOptionals["additionalMetadata"].(string); localVarOptionals != nil && localVarOk { - localVarFormParams["additionalMetadata"] = a.Configuration.APIClient.ParameterToString(localVarTempParam, "") + if localVarTempParam, localVarOk := localVarOptionals["additionalMetadata"].(string); localVarOk { + localVarFormParams.Add("additionalMetadata", parameterToString(localVarTempParam, "")) } var file (*os.File) - if localVarTempParam, localVarOk := localVarOptionals["file"].(*os.File); localVarOptionals != nil && localVarOk { + if localVarTempParam, localVarOk := localVarOptionals["file"].(*os.File); localVarOk { file = localVarTempParam } if file != nil { fbs, _ := ioutil.ReadAll(file) localVarFileBytes = fbs localVarFileName = file.Name() + file.Close() } - var successPayload = new(ModelApiResponse) - localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - - var localVarURL, _ = url.Parse(localVarPath) - localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "UploadFile", Method: localVarHttpMethod, RequestURL: localVarURL.String()} - if localVarHttpResponse != nil { - localVarAPIResponse.Response = localVarHttpResponse.RawResponse - localVarAPIResponse.Payload = localVarHttpResponse.Body() + r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + if err != nil { + return successPayload, nil, err } - if err != nil { - return successPayload, localVarAPIResponse, err + localVarHttpResponse, err := a.client.callAPI(r) + if err != nil || localVarHttpResponse == nil { + return successPayload, localVarHttpResponse, err + } + defer localVarHttpResponse.Body.Close() + if localVarHttpResponse.StatusCode >= 300 { + return successPayload, localVarHttpResponse, reportError(localVarHttpResponse.Status) + } + + if err = json.NewDecoder(localVarHttpResponse.Body).Decode(&successPayload); err != nil { + return successPayload, localVarHttpResponse, err } - err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) - return successPayload, localVarAPIResponse, err + + + return successPayload, localVarHttpResponse, err } diff --git a/samples/client/petstore/go/go-petstore/store_api.go b/samples/client/petstore/go/go-petstore/store_api.go index ca90d190d8a..00262be1d88 100644 --- a/samples/client/petstore/go/go-petstore/store_api.go +++ b/samples/client/petstore/go/go-petstore/store_api.go @@ -12,64 +12,56 @@ package petstore import ( "net/url" + "net/http" "strings" + "golang.org/x/net/context" "encoding/json" "fmt" ) -type StoreApi struct { - Configuration *Configuration -} +// Linger please +var ( + _ context.Context +) -func NewStoreApi() *StoreApi { - configuration := NewConfiguration() - return &StoreApi{ - Configuration: configuration, - } -} +type StoreApiService service -func NewStoreApiWithBasePath(basePath string) *StoreApi { - configuration := NewConfiguration() - configuration.BasePath = basePath - return &StoreApi{ - Configuration: configuration, - } -} +/* StoreApiService Delete purchase order by ID + For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors -/** - * Delete purchase order by ID - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * - * @param orderId ID of the order that needs to be deleted - * @return - */ -func (a StoreApi) DeleteOrder(orderId string) (*APIResponse, error) { + @param orderId ID of the order that needs to be deleted + @return */ +func (a *StoreApiService) DeleteOrder(orderId string) ( *http.Response, error) { + var ( + localVarHttpMethod = strings.ToUpper("Delete") + localVarPostBody interface{} + localVarFileName string + localVarFileBytes []byte + ) - var localVarHttpMethod = strings.ToUpper("Delete") // create path and map variables - localVarPath := a.Configuration.BasePath + "/store/order/{order_id}" - localVarPath = strings.Replace(localVarPath, "{"+"order_id"+"}", fmt.Sprintf("%v", orderId), -1) + localVarPath := a.client.cfg.BasePath + "/store/order/{orderId}" + localVarPath = strings.Replace(localVarPath, "{"+"orderId"+"}", fmt.Sprintf("%v", orderId), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} - localVarFormParams := make(map[string]string) - var localVarPostBody interface{} - var localVarFileName string - var localVarFileBytes []byte - // add default headers if any - for key := range a.Configuration.DefaultHeader { - localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] + localVarFormParams := url.Values{} + + orderIdTxt, err := atoi(orderId) + if orderIdTxt < 1 { + return nil, reportError("orderId must be greater than 1") } // to determine the Content-Type header localVarHttpContentTypes := []string{ } // set Content-Type header - localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) + localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } + // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/xml", @@ -77,121 +69,139 @@ func (a StoreApi) DeleteOrder(orderId string) (*APIResponse, error) { } // set Accept header - localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) + localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } - localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - - var localVarURL, _ = url.Parse(localVarPath) - localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "DeleteOrder", Method: localVarHttpMethod, RequestURL: localVarURL.String()} - if localVarHttpResponse != nil { - localVarAPIResponse.Response = localVarHttpResponse.RawResponse - localVarAPIResponse.Payload = localVarHttpResponse.Body() - } - + r, err := a.client.prepareRequest(nil, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { - return localVarAPIResponse, err + return nil, err } - return localVarAPIResponse, err + + localVarHttpResponse, err := a.client.callAPI(r) + if err != nil || localVarHttpResponse == nil { + return localVarHttpResponse, err + } + defer localVarHttpResponse.Body.Close() + if localVarHttpResponse.StatusCode >= 300 { + return localVarHttpResponse, reportError(localVarHttpResponse.Status) + } + + return localVarHttpResponse, err } -/** - * Returns pet inventories by status - * Returns a map of status codes to quantities - * - * @return *map[string]int32 - */ -func (a StoreApi) GetInventory() (*map[string]int32, *APIResponse, error) { +/* StoreApiService Returns pet inventories by status + Returns a map of status codes to quantities + * @param ctx context.Context Authentication Context + @return map[string]int32*/ +func (a *StoreApiService) GetInventory(ctx context.Context, ) (map[string]int32, *http.Response, error) { + var ( + localVarHttpMethod = strings.ToUpper("Get") + localVarPostBody interface{} + localVarFileName string + localVarFileBytes []byte + successPayload map[string]int32 + ) - var localVarHttpMethod = strings.ToUpper("Get") // create path and map variables - localVarPath := a.Configuration.BasePath + "/store/inventory" + localVarPath := a.client.cfg.BasePath + "/store/inventory" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} - localVarFormParams := make(map[string]string) - var localVarPostBody interface{} - var localVarFileName string - var localVarFileBytes []byte - // authentication '(api_key)' required - // set key with prefix in header - localVarHeaderParams["api_key"] = a.Configuration.GetAPIKeyWithPrefix("api_key") - // add default headers if any - for key := range a.Configuration.DefaultHeader { - localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] - } + localVarFormParams := url.Values{} + // to determine the Content-Type header localVarHttpContentTypes := []string{ } // set Content-Type header - localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) + localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } + // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/json", } // set Accept header - localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) + localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } - var successPayload = new(map[string]int32) - localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - - var localVarURL, _ = url.Parse(localVarPath) - localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "GetInventory", Method: localVarHttpMethod, RequestURL: localVarURL.String()} - if localVarHttpResponse != nil { - localVarAPIResponse.Response = localVarHttpResponse.RawResponse - localVarAPIResponse.Payload = localVarHttpResponse.Body() + if ctx != nil { + // API Key Authentication + if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { + var key string + if auth.Prefix != "" { + key = auth.Prefix + " " + auth.Key + } else { + key = auth.Key + } + localVarHeaderParams["api_key"] = key + } } - + r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { - return successPayload, localVarAPIResponse, err + return successPayload, nil, err + } + + localVarHttpResponse, err := a.client.callAPI(r) + if err != nil || localVarHttpResponse == nil { + return successPayload, localVarHttpResponse, err + } + defer localVarHttpResponse.Body.Close() + if localVarHttpResponse.StatusCode >= 300 { + return successPayload, localVarHttpResponse, reportError(localVarHttpResponse.Status) + } + + if err = json.NewDecoder(localVarHttpResponse.Body).Decode(&successPayload); err != nil { + return successPayload, localVarHttpResponse, err } - err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) - return successPayload, localVarAPIResponse, err + + + return successPayload, localVarHttpResponse, err } -/** - * Find purchase order by ID - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * - * @param orderId ID of pet that needs to be fetched - * @return *Order - */ -func (a StoreApi) GetOrderById(orderId int64) (*Order, *APIResponse, error) { +/* StoreApiService Find purchase order by ID + For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + + @param orderId ID of pet that needs to be fetched + @return Order*/ +func (a *StoreApiService) GetOrderById(orderId int64) (Order, *http.Response, error) { + var ( + localVarHttpMethod = strings.ToUpper("Get") + localVarPostBody interface{} + localVarFileName string + localVarFileBytes []byte + successPayload Order + ) - var localVarHttpMethod = strings.ToUpper("Get") // create path and map variables - localVarPath := a.Configuration.BasePath + "/store/order/{order_id}" - localVarPath = strings.Replace(localVarPath, "{"+"order_id"+"}", fmt.Sprintf("%v", orderId), -1) + localVarPath := a.client.cfg.BasePath + "/store/order/{orderId}" + localVarPath = strings.Replace(localVarPath, "{"+"orderId"+"}", fmt.Sprintf("%v", orderId), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} - localVarFormParams := make(map[string]string) - var localVarPostBody interface{} - var localVarFileName string - var localVarFileBytes []byte - // add default headers if any - for key := range a.Configuration.DefaultHeader { - localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] + localVarFormParams := url.Values{} + + if orderId < 1 { + return successPayload, nil, reportError("orderId must be greater than 1") + } + if orderId > 5 { + return successPayload, nil, reportError("orderId must be less than 5") } // to determine the Content-Type header localVarHttpContentTypes := []string{ } // set Content-Type header - localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) + localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } + // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/xml", @@ -199,60 +209,63 @@ func (a StoreApi) GetOrderById(orderId int64) (*Order, *APIResponse, error) { } // set Accept header - localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) + localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } - var successPayload = new(Order) - localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - - var localVarURL, _ = url.Parse(localVarPath) - localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "GetOrderById", Method: localVarHttpMethod, RequestURL: localVarURL.String()} - if localVarHttpResponse != nil { - localVarAPIResponse.Response = localVarHttpResponse.RawResponse - localVarAPIResponse.Payload = localVarHttpResponse.Body() + r, err := a.client.prepareRequest(nil, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + if err != nil { + return successPayload, nil, err } - if err != nil { - return successPayload, localVarAPIResponse, err + localVarHttpResponse, err := a.client.callAPI(r) + if err != nil || localVarHttpResponse == nil { + return successPayload, localVarHttpResponse, err + } + defer localVarHttpResponse.Body.Close() + if localVarHttpResponse.StatusCode >= 300 { + return successPayload, localVarHttpResponse, reportError(localVarHttpResponse.Status) + } + + if err = json.NewDecoder(localVarHttpResponse.Body).Decode(&successPayload); err != nil { + return successPayload, localVarHttpResponse, err } - err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) - return successPayload, localVarAPIResponse, err + + + return successPayload, localVarHttpResponse, err } -/** - * Place an order for a pet - * - * - * @param body order placed for purchasing the pet - * @return *Order - */ -func (a StoreApi) PlaceOrder(body Order) (*Order, *APIResponse, error) { +/* StoreApiService Place an order for a pet + + + @param body order placed for purchasing the pet + @return Order*/ +func (a *StoreApiService) PlaceOrder(body Order) (Order, *http.Response, error) { + var ( + localVarHttpMethod = strings.ToUpper("Post") + localVarPostBody interface{} + localVarFileName string + localVarFileBytes []byte + successPayload Order + ) - var localVarHttpMethod = strings.ToUpper("Post") // create path and map variables - localVarPath := a.Configuration.BasePath + "/store/order" + localVarPath := a.client.cfg.BasePath + "/store/order" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} - localVarFormParams := make(map[string]string) - var localVarPostBody interface{} - var localVarFileName string - var localVarFileBytes []byte - // add default headers if any - for key := range a.Configuration.DefaultHeader { - localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] - } + localVarFormParams := url.Values{} + // to determine the Content-Type header localVarHttpContentTypes := []string{ } // set Content-Type header - localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) + localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } + // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/xml", @@ -260,27 +273,31 @@ func (a StoreApi) PlaceOrder(body Order) (*Order, *APIResponse, error) { } // set Accept header - localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) + localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // body params localVarPostBody = &body - var successPayload = new(Order) - localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - - var localVarURL, _ = url.Parse(localVarPath) - localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "PlaceOrder", Method: localVarHttpMethod, RequestURL: localVarURL.String()} - if localVarHttpResponse != nil { - localVarAPIResponse.Response = localVarHttpResponse.RawResponse - localVarAPIResponse.Payload = localVarHttpResponse.Body() + r, err := a.client.prepareRequest(nil, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + if err != nil { + return successPayload, nil, err } - if err != nil { - return successPayload, localVarAPIResponse, err + localVarHttpResponse, err := a.client.callAPI(r) + if err != nil || localVarHttpResponse == nil { + return successPayload, localVarHttpResponse, err + } + defer localVarHttpResponse.Body.Close() + if localVarHttpResponse.StatusCode >= 300 { + return successPayload, localVarHttpResponse, reportError(localVarHttpResponse.Status) + } + + if err = json.NewDecoder(localVarHttpResponse.Body).Decode(&successPayload); err != nil { + return successPayload, localVarHttpResponse, err } - err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) - return successPayload, localVarAPIResponse, err + + + return successPayload, localVarHttpResponse, err } diff --git a/samples/client/petstore/go/go-petstore/user_api.go b/samples/client/petstore/go/go-petstore/user_api.go index 9f83e69d4dd..d317fa7cf04 100644 --- a/samples/client/petstore/go/go-petstore/user_api.go +++ b/samples/client/petstore/go/go-petstore/user_api.go @@ -12,63 +12,51 @@ package petstore import ( "net/url" + "net/http" "strings" + "golang.org/x/net/context" "encoding/json" "fmt" ) -type UserApi struct { - Configuration *Configuration -} +// Linger please +var ( + _ context.Context +) -func NewUserApi() *UserApi { - configuration := NewConfiguration() - return &UserApi{ - Configuration: configuration, - } -} +type UserApiService service -func NewUserApiWithBasePath(basePath string) *UserApi { - configuration := NewConfiguration() - configuration.BasePath = basePath - return &UserApi{ - Configuration: configuration, - } -} +/* UserApiService Create user + This can only be done by the logged in user. -/** - * Create user - * This can only be done by the logged in user. - * - * @param body Created user object - * @return - */ -func (a UserApi) CreateUser(body User) (*APIResponse, error) { + @param body Created user object + @return */ +func (a *UserApiService) CreateUser(body User) ( *http.Response, error) { + var ( + localVarHttpMethod = strings.ToUpper("Post") + localVarPostBody interface{} + localVarFileName string + localVarFileBytes []byte + ) - var localVarHttpMethod = strings.ToUpper("Post") // create path and map variables - localVarPath := a.Configuration.BasePath + "/user" + localVarPath := a.client.cfg.BasePath + "/user" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} - localVarFormParams := make(map[string]string) - var localVarPostBody interface{} - var localVarFileName string - var localVarFileBytes []byte - // add default headers if any - for key := range a.Configuration.DefaultHeader { - localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] - } + localVarFormParams := url.Values{} + // to determine the Content-Type header localVarHttpContentTypes := []string{ } // set Content-Type header - localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) + localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } + // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/xml", @@ -76,60 +64,59 @@ func (a UserApi) CreateUser(body User) (*APIResponse, error) { } // set Accept header - localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) + localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // body params localVarPostBody = &body - localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - - var localVarURL, _ = url.Parse(localVarPath) - localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "CreateUser", Method: localVarHttpMethod, RequestURL: localVarURL.String()} - if localVarHttpResponse != nil { - localVarAPIResponse.Response = localVarHttpResponse.RawResponse - localVarAPIResponse.Payload = localVarHttpResponse.Body() - } - + r, err := a.client.prepareRequest(nil, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { - return localVarAPIResponse, err + return nil, err } - return localVarAPIResponse, err + + localVarHttpResponse, err := a.client.callAPI(r) + if err != nil || localVarHttpResponse == nil { + return localVarHttpResponse, err + } + defer localVarHttpResponse.Body.Close() + if localVarHttpResponse.StatusCode >= 300 { + return localVarHttpResponse, reportError(localVarHttpResponse.Status) + } + + return localVarHttpResponse, err } -/** - * Creates list of users with given input array - * - * - * @param body List of user object - * @return - */ -func (a UserApi) CreateUsersWithArrayInput(body []User) (*APIResponse, error) { +/* UserApiService Creates list of users with given input array + + + @param body List of user object + @return */ +func (a *UserApiService) CreateUsersWithArrayInput(body []User) ( *http.Response, error) { + var ( + localVarHttpMethod = strings.ToUpper("Post") + localVarPostBody interface{} + localVarFileName string + localVarFileBytes []byte + ) - var localVarHttpMethod = strings.ToUpper("Post") // create path and map variables - localVarPath := a.Configuration.BasePath + "/user/createWithArray" + localVarPath := a.client.cfg.BasePath + "/user/createWithArray" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} - localVarFormParams := make(map[string]string) - var localVarPostBody interface{} - var localVarFileName string - var localVarFileBytes []byte - // add default headers if any - for key := range a.Configuration.DefaultHeader { - localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] - } + localVarFormParams := url.Values{} + // to determine the Content-Type header localVarHttpContentTypes := []string{ } // set Content-Type header - localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) + localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } + // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/xml", @@ -137,60 +124,59 @@ func (a UserApi) CreateUsersWithArrayInput(body []User) (*APIResponse, error) { } // set Accept header - localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) + localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // body params localVarPostBody = &body - localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - - var localVarURL, _ = url.Parse(localVarPath) - localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "CreateUsersWithArrayInput", Method: localVarHttpMethod, RequestURL: localVarURL.String()} - if localVarHttpResponse != nil { - localVarAPIResponse.Response = localVarHttpResponse.RawResponse - localVarAPIResponse.Payload = localVarHttpResponse.Body() - } - + r, err := a.client.prepareRequest(nil, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { - return localVarAPIResponse, err + return nil, err } - return localVarAPIResponse, err + + localVarHttpResponse, err := a.client.callAPI(r) + if err != nil || localVarHttpResponse == nil { + return localVarHttpResponse, err + } + defer localVarHttpResponse.Body.Close() + if localVarHttpResponse.StatusCode >= 300 { + return localVarHttpResponse, reportError(localVarHttpResponse.Status) + } + + return localVarHttpResponse, err } -/** - * Creates list of users with given input array - * - * - * @param body List of user object - * @return - */ -func (a UserApi) CreateUsersWithListInput(body []User) (*APIResponse, error) { +/* UserApiService Creates list of users with given input array + + + @param body List of user object + @return */ +func (a *UserApiService) CreateUsersWithListInput(body []User) ( *http.Response, error) { + var ( + localVarHttpMethod = strings.ToUpper("Post") + localVarPostBody interface{} + localVarFileName string + localVarFileBytes []byte + ) - var localVarHttpMethod = strings.ToUpper("Post") // create path and map variables - localVarPath := a.Configuration.BasePath + "/user/createWithList" + localVarPath := a.client.cfg.BasePath + "/user/createWithList" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} - localVarFormParams := make(map[string]string) - var localVarPostBody interface{} - var localVarFileName string - var localVarFileBytes []byte - // add default headers if any - for key := range a.Configuration.DefaultHeader { - localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] - } + localVarFormParams := url.Values{} + // to determine the Content-Type header localVarHttpContentTypes := []string{ } // set Content-Type header - localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) + localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } + // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/xml", @@ -198,61 +184,60 @@ func (a UserApi) CreateUsersWithListInput(body []User) (*APIResponse, error) { } // set Accept header - localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) + localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // body params localVarPostBody = &body - localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - - var localVarURL, _ = url.Parse(localVarPath) - localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "CreateUsersWithListInput", Method: localVarHttpMethod, RequestURL: localVarURL.String()} - if localVarHttpResponse != nil { - localVarAPIResponse.Response = localVarHttpResponse.RawResponse - localVarAPIResponse.Payload = localVarHttpResponse.Body() - } - + r, err := a.client.prepareRequest(nil, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { - return localVarAPIResponse, err + return nil, err } - return localVarAPIResponse, err + + localVarHttpResponse, err := a.client.callAPI(r) + if err != nil || localVarHttpResponse == nil { + return localVarHttpResponse, err + } + defer localVarHttpResponse.Body.Close() + if localVarHttpResponse.StatusCode >= 300 { + return localVarHttpResponse, reportError(localVarHttpResponse.Status) + } + + return localVarHttpResponse, err } -/** - * Delete user - * This can only be done by the logged in user. - * - * @param username The name that needs to be deleted - * @return - */ -func (a UserApi) DeleteUser(username string) (*APIResponse, error) { +/* UserApiService Delete user + This can only be done by the logged in user. + + @param username The name that needs to be deleted + @return */ +func (a *UserApiService) DeleteUser(username string) ( *http.Response, error) { + var ( + localVarHttpMethod = strings.ToUpper("Delete") + localVarPostBody interface{} + localVarFileName string + localVarFileBytes []byte + ) - var localVarHttpMethod = strings.ToUpper("Delete") // create path and map variables - localVarPath := a.Configuration.BasePath + "/user/{username}" + localVarPath := a.client.cfg.BasePath + "/user/{username}" localVarPath = strings.Replace(localVarPath, "{"+"username"+"}", fmt.Sprintf("%v", username), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} - localVarFormParams := make(map[string]string) - var localVarPostBody interface{} - var localVarFileName string - var localVarFileBytes []byte - // add default headers if any - for key := range a.Configuration.DefaultHeader { - localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] - } + localVarFormParams := url.Values{} + // to determine the Content-Type header localVarHttpContentTypes := []string{ } // set Content-Type header - localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) + localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } + // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/xml", @@ -260,59 +245,59 @@ func (a UserApi) DeleteUser(username string) (*APIResponse, error) { } // set Accept header - localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) + localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } - localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - - var localVarURL, _ = url.Parse(localVarPath) - localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "DeleteUser", Method: localVarHttpMethod, RequestURL: localVarURL.String()} - if localVarHttpResponse != nil { - localVarAPIResponse.Response = localVarHttpResponse.RawResponse - localVarAPIResponse.Payload = localVarHttpResponse.Body() - } - + r, err := a.client.prepareRequest(nil, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { - return localVarAPIResponse, err + return nil, err } - return localVarAPIResponse, err + + localVarHttpResponse, err := a.client.callAPI(r) + if err != nil || localVarHttpResponse == nil { + return localVarHttpResponse, err + } + defer localVarHttpResponse.Body.Close() + if localVarHttpResponse.StatusCode >= 300 { + return localVarHttpResponse, reportError(localVarHttpResponse.Status) + } + + return localVarHttpResponse, err } -/** - * Get user by user name - * - * - * @param username The name that needs to be fetched. Use user1 for testing. - * @return *User - */ -func (a UserApi) GetUserByName(username string) (*User, *APIResponse, error) { +/* UserApiService Get user by user name + + + @param username The name that needs to be fetched. Use user1 for testing. + @return User*/ +func (a *UserApiService) GetUserByName(username string) (User, *http.Response, error) { + var ( + localVarHttpMethod = strings.ToUpper("Get") + localVarPostBody interface{} + localVarFileName string + localVarFileBytes []byte + successPayload User + ) - var localVarHttpMethod = strings.ToUpper("Get") // create path and map variables - localVarPath := a.Configuration.BasePath + "/user/{username}" + localVarPath := a.client.cfg.BasePath + "/user/{username}" localVarPath = strings.Replace(localVarPath, "{"+"username"+"}", fmt.Sprintf("%v", username), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} - localVarFormParams := make(map[string]string) - var localVarPostBody interface{} - var localVarFileName string - var localVarFileBytes []byte - // add default headers if any - for key := range a.Configuration.DefaultHeader { - localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] - } + localVarFormParams := url.Values{} + // to determine the Content-Type header localVarHttpContentTypes := []string{ } // set Content-Type header - localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) + localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } + // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/xml", @@ -320,63 +305,66 @@ func (a UserApi) GetUserByName(username string) (*User, *APIResponse, error) { } // set Accept header - localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) + localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } - var successPayload = new(User) - localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - - var localVarURL, _ = url.Parse(localVarPath) - localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "GetUserByName", Method: localVarHttpMethod, RequestURL: localVarURL.String()} - if localVarHttpResponse != nil { - localVarAPIResponse.Response = localVarHttpResponse.RawResponse - localVarAPIResponse.Payload = localVarHttpResponse.Body() + r, err := a.client.prepareRequest(nil, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + if err != nil { + return successPayload, nil, err } - if err != nil { - return successPayload, localVarAPIResponse, err + localVarHttpResponse, err := a.client.callAPI(r) + if err != nil || localVarHttpResponse == nil { + return successPayload, localVarHttpResponse, err + } + defer localVarHttpResponse.Body.Close() + if localVarHttpResponse.StatusCode >= 300 { + return successPayload, localVarHttpResponse, reportError(localVarHttpResponse.Status) + } + + if err = json.NewDecoder(localVarHttpResponse.Body).Decode(&successPayload); err != nil { + return successPayload, localVarHttpResponse, err } - err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) - return successPayload, localVarAPIResponse, err + + + return successPayload, localVarHttpResponse, err } -/** - * Logs user into the system - * - * - * @param username The user name for login - * @param password The password for login in clear text - * @return *string - */ -func (a UserApi) LoginUser(username string, password string) (*string, *APIResponse, error) { +/* UserApiService Logs user into the system + + + @param username The user name for login + @param password The password for login in clear text + @return string*/ +func (a *UserApiService) LoginUser(username string, password string) (string, *http.Response, error) { + var ( + localVarHttpMethod = strings.ToUpper("Get") + localVarPostBody interface{} + localVarFileName string + localVarFileBytes []byte + successPayload string + ) - var localVarHttpMethod = strings.ToUpper("Get") // create path and map variables - localVarPath := a.Configuration.BasePath + "/user/login" + localVarPath := a.client.cfg.BasePath + "/user/login" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} - localVarFormParams := make(map[string]string) - var localVarPostBody interface{} - var localVarFileName string - var localVarFileBytes []byte - // add default headers if any - for key := range a.Configuration.DefaultHeader { - localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] - } - localVarQueryParams.Add("username", a.Configuration.APIClient.ParameterToString(username, "")) - localVarQueryParams.Add("password", a.Configuration.APIClient.ParameterToString(password, "")) + localVarFormParams := url.Values{} + + localVarQueryParams.Add("username", parameterToString(username, "")) + localVarQueryParams.Add("password", parameterToString(password, "")) // to determine the Content-Type header localVarHttpContentTypes := []string{ } // set Content-Type header - localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) + localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } + // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/xml", @@ -384,59 +372,61 @@ func (a UserApi) LoginUser(username string, password string) (*string, *APIRespo } // set Accept header - localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) + localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } - var successPayload = new(string) - localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - - var localVarURL, _ = url.Parse(localVarPath) - localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "LoginUser", Method: localVarHttpMethod, RequestURL: localVarURL.String()} - if localVarHttpResponse != nil { - localVarAPIResponse.Response = localVarHttpResponse.RawResponse - localVarAPIResponse.Payload = localVarHttpResponse.Body() + r, err := a.client.prepareRequest(nil, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + if err != nil { + return successPayload, nil, err } - if err != nil { - return successPayload, localVarAPIResponse, err + localVarHttpResponse, err := a.client.callAPI(r) + if err != nil || localVarHttpResponse == nil { + return successPayload, localVarHttpResponse, err + } + defer localVarHttpResponse.Body.Close() + if localVarHttpResponse.StatusCode >= 300 { + return successPayload, localVarHttpResponse, reportError(localVarHttpResponse.Status) + } + + if err = json.NewDecoder(localVarHttpResponse.Body).Decode(&successPayload); err != nil { + return successPayload, localVarHttpResponse, err } - err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) - return successPayload, localVarAPIResponse, err + + + return successPayload, localVarHttpResponse, err } -/** - * Logs out current logged in user session - * - * - * @return - */ -func (a UserApi) LogoutUser() (*APIResponse, error) { +/* UserApiService Logs out current logged in user session + + + @return */ +func (a *UserApiService) LogoutUser() ( *http.Response, error) { + var ( + localVarHttpMethod = strings.ToUpper("Get") + localVarPostBody interface{} + localVarFileName string + localVarFileBytes []byte + ) - var localVarHttpMethod = strings.ToUpper("Get") // create path and map variables - localVarPath := a.Configuration.BasePath + "/user/logout" + localVarPath := a.client.cfg.BasePath + "/user/logout" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} - localVarFormParams := make(map[string]string) - var localVarPostBody interface{} - var localVarFileName string - var localVarFileBytes []byte - // add default headers if any - for key := range a.Configuration.DefaultHeader { - localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] - } + localVarFormParams := url.Values{} + // to determine the Content-Type header localVarHttpContentTypes := []string{ } // set Content-Type header - localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) + localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } + // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/xml", @@ -444,60 +434,59 @@ func (a UserApi) LogoutUser() (*APIResponse, error) { } // set Accept header - localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) + localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } - localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - - var localVarURL, _ = url.Parse(localVarPath) - localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "LogoutUser", Method: localVarHttpMethod, RequestURL: localVarURL.String()} - if localVarHttpResponse != nil { - localVarAPIResponse.Response = localVarHttpResponse.RawResponse - localVarAPIResponse.Payload = localVarHttpResponse.Body() - } - + r, err := a.client.prepareRequest(nil, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { - return localVarAPIResponse, err + return nil, err } - return localVarAPIResponse, err + + localVarHttpResponse, err := a.client.callAPI(r) + if err != nil || localVarHttpResponse == nil { + return localVarHttpResponse, err + } + defer localVarHttpResponse.Body.Close() + if localVarHttpResponse.StatusCode >= 300 { + return localVarHttpResponse, reportError(localVarHttpResponse.Status) + } + + return localVarHttpResponse, err } -/** - * Updated user - * This can only be done by the logged in user. - * - * @param username name that need to be deleted - * @param body Updated user object - * @return - */ -func (a UserApi) UpdateUser(username string, body User) (*APIResponse, error) { +/* UserApiService Updated user + This can only be done by the logged in user. + + @param username name that need to be deleted + @param body Updated user object + @return */ +func (a *UserApiService) UpdateUser(username string, body User) ( *http.Response, error) { + var ( + localVarHttpMethod = strings.ToUpper("Put") + localVarPostBody interface{} + localVarFileName string + localVarFileBytes []byte + ) - var localVarHttpMethod = strings.ToUpper("Put") // create path and map variables - localVarPath := a.Configuration.BasePath + "/user/{username}" + localVarPath := a.client.cfg.BasePath + "/user/{username}" localVarPath = strings.Replace(localVarPath, "{"+"username"+"}", fmt.Sprintf("%v", username), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} - localVarFormParams := make(map[string]string) - var localVarPostBody interface{} - var localVarFileName string - var localVarFileBytes []byte - // add default headers if any - for key := range a.Configuration.DefaultHeader { - localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] - } + localVarFormParams := url.Values{} + // to determine the Content-Type header localVarHttpContentTypes := []string{ } // set Content-Type header - localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) + localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } + // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/xml", @@ -505,25 +494,26 @@ func (a UserApi) UpdateUser(username string, body User) (*APIResponse, error) { } // set Accept header - localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) + localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // body params localVarPostBody = &body - localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - - var localVarURL, _ = url.Parse(localVarPath) - localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "UpdateUser", Method: localVarHttpMethod, RequestURL: localVarURL.String()} - if localVarHttpResponse != nil { - localVarAPIResponse.Response = localVarHttpResponse.RawResponse - localVarAPIResponse.Payload = localVarHttpResponse.Body() - } - + r, err := a.client.prepareRequest(nil, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { - return localVarAPIResponse, err + return nil, err } - return localVarAPIResponse, err + + localVarHttpResponse, err := a.client.callAPI(r) + if err != nil || localVarHttpResponse == nil { + return localVarHttpResponse, err + } + defer localVarHttpResponse.Body.Close() + if localVarHttpResponse.StatusCode >= 300 { + return localVarHttpResponse, reportError(localVarHttpResponse.Status) + } + + return localVarHttpResponse, err } diff --git a/samples/client/petstore/go/pet_api_test.go b/samples/client/petstore/go/pet_api_test.go index 13b4dfa056c..474e13c55bd 100644 --- a/samples/client/petstore/go/pet_api_test.go +++ b/samples/client/petstore/go/pet_api_test.go @@ -5,86 +5,114 @@ import ( "os" "testing" - "time" - sw "./go-petstore" "github.com/stretchr/testify/assert" ) +var client *sw.APIClient + +func TestMain(m *testing.M) { + cfg := sw.NewConfiguration() + cfg.AddDefaultHeader("testheader", "testvalue") + client = sw.NewAPIClient(cfg) + retCode := m.Run() + os.Exit(retCode) +} + func TestAddPet(t *testing.T) { - s := sw.NewPetApi() newPet := (sw.Pet{Id: 12830, Name: "gopher", - PhotoUrls: []string{"http://1.com", "http://2.com"}, Status: "pending"}) + PhotoUrls: []string{"http://1.com", "http://2.com"}, Status: "pending", Tags: []sw.Tag{sw.Tag{Id: 1, Name: "tag2"}}}) - apiResponse, err := s.AddPet(newPet) + r, err := client.PetApi.AddPet(nil, newPet) if err != nil { t.Errorf("Error while adding pet") t.Log(err) } - if apiResponse.Response.StatusCode != 200 { - t.Log(apiResponse.Response) + if r.StatusCode != 200 { + t.Log(r) } } func TestFindPetsByStatusWithMissingParam(t *testing.T) { - s := sw.NewPetApi() - - _, apiResponse, err := s.FindPetsByStatus(nil) + _, r, err := client.PetApi.FindPetsByStatus(nil, nil) if err != nil { t.Errorf("Error while testing TestFindPetsByStatusWithMissingParam") t.Log(err) } - if apiResponse.Response.StatusCode != 200 { - t.Log(apiResponse) + if r.StatusCode != 200 { + t.Log(r) } } func TestGetPetById(t *testing.T) { - s := sw.NewPetApi() - isPetCorrect(t, s, 12830, "gopher", "pending") + isPetCorrect(t, 12830, "gopher", "pending") } func TestGetPetByIdWithInvalidID(t *testing.T) { - s := sw.NewPetApi() - resp, apiResponse, err := s.GetPetById(999999999) - if err != nil { + resp, r, err := client.PetApi.GetPetById(nil, 999999999) + if r != nil && r.StatusCode == 404 { + return // This is a pass condition. API will return with a 404 error. + } else if err != nil { t.Errorf("Error while getting pet by invalid id") t.Log(err) - t.Log(apiResponse) + t.Log(r) } else { t.Log(resp) } - if apiResponse.Response.StatusCode != 200 { - t.Log(apiResponse.Response) - } } func TestUpdatePetWithForm(t *testing.T) { - s := sw.NewPetApi() - apiResponse, err := s.UpdatePetWithForm(12830, map[string]interface{}{ - "name": "golang", - "status": "available", - }) + r, err := client.PetApi.UpdatePetWithForm(nil, 12830, map[string]interface{}{"name": "golang", "status": "available"}) if err != nil { t.Errorf("Error while updating pet by id") t.Log(err) - t.Log(apiResponse) + t.Log(r) } - if apiResponse.Response.StatusCode != 200 { - t.Log(apiResponse.Response) + if r.StatusCode != 200 { + t.Log(r) + } +} + +func TestFindPetsByTag(t *testing.T) { + var found bool = false + resp, r, err := client.PetApi.FindPetsByTags(nil, []string{"tag2"}) + if err != nil { + t.Errorf("Error while getting pet by tag") + t.Log(err) + t.Log(r) + } else { + if len(resp) == 0 { + t.Errorf("Error no pets returned") + } else { + + assert := assert.New(t) + for i := 0; i < len(resp); i++ { + if resp[i].Id == 12830 { + assert.Equal(resp[i].Status, "pending", "Pet status should be `pending`") + found = true + } + } + } + + if found == false { + t.Errorf("Error while getting pet by tag could not find 12830") + } + + if r.StatusCode != 200 { + t.Log(r) + } } } func TestFindPetsByStatus(t *testing.T) { - s := sw.NewPetApi() - resp, apiResponse, err := s.FindPetsByStatus([]string{"available"}) + resp, r, err := client.PetApi.FindPetsByStatus(nil, []string{"available"}) if err != nil { t.Errorf("Error while getting pet by id") t.Log(err) - t.Log(apiResponse) + t.Log(r) } else { if len(resp) == 0 { t.Errorf("Error no pets returned") @@ -95,97 +123,134 @@ func TestFindPetsByStatus(t *testing.T) { } } - if apiResponse.Response.StatusCode != 200 { - t.Log(apiResponse.Response) + if r.StatusCode != 200 { + t.Log(r) } } } func TestUploadFile(t *testing.T) { - s := sw.NewPetApi() file, _ := os.Open("../python/testfiles/foo.png") - _, apiResponse, err := s.UploadFile(12830, map[string]interface{}{ - "additionalMetadata": "golang", - "file": file, - }) + _, r, err := client.PetApi.UploadFile(nil, 12830, map[string]interface{}{"name": "golang", "file": file}) if err != nil { t.Errorf("Error while uploading file") t.Log(err) } - if apiResponse.Response.StatusCode != 200 { - t.Log(apiResponse.Response) + if r.StatusCode != 200 { + t.Log(r) } } func TestDeletePet(t *testing.T) { - s := sw.NewPetApi() - deletePet(t, s, 12830) + r, err := client.PetApi.DeletePet(nil, 12830, nil) + + if err != nil { + t.Errorf("Error while deleting pet by id") + t.Log(err) + } + if r.StatusCode != 200 { + t.Log(r) + } } +/* +// Test we can concurrently create, retrieve, update, and delete. func TestConcurrency(t *testing.T) { - s := sw.NewPetApi() errc := make(chan error) - newPets := []sw.Pet{sw.Pet{Id: 12345, Name: "gopherFred", PhotoUrls: []string{"http://1.com", "http://2.com"}, Status: "pending"}, - sw.Pet{Id: 12346, Name: "gopherDan", PhotoUrls: []string{"http://1.com", "http://2.com"}, Status: "active"}, - sw.Pet{Id: 12347, Name: "gopherRick", PhotoUrls: []string{"http://1.com", "http://2.com"}, Status: "mia"}, - sw.Pet{Id: 12348, Name: "gopherJohn", PhotoUrls: []string{"http://1.com", "http://2.com"}, Status: "dead"}} + newPets := []sw.Pet{ + sw.Pet{Id: 912345, Name: "gopherFred", PhotoUrls: []string{"http://1.com", "http://2.com"}, Status: "pending"}, + sw.Pet{Id: 912346, Name: "gopherDan", PhotoUrls: []string{"http://1.com", "http://2.com"}, Status: "active"}, + sw.Pet{Id: 912347, Name: "gopherRick", PhotoUrls: []string{"http://1.com", "http://2.com"}, Status: "mia"}, + sw.Pet{Id: 912348, Name: "gopherJohn", PhotoUrls: []string{"http://1.com", "http://2.com"}, Status: "active"}, + sw.Pet{Id: 912349, Name: "gopherAlf", PhotoUrls: []string{"http://1.com", "http://2.com"}, Status: "pending"}, + sw.Pet{Id: 912350, Name: "gopherRob", PhotoUrls: []string{"http://1.com", "http://2.com"}, Status: "pending"}, + sw.Pet{Id: 912351, Name: "gopherIan", PhotoUrls: []string{"http://1.com", "http://2.com"}, Status: "active"}, + } - // Add the pets at the same time. + // Add the pets. for _, pet := range newPets { go func(newPet sw.Pet) { - apiResponse, err := s.AddPet(newPet) - if apiResponse.Response.StatusCode != 200 { - t.Log(apiResponse.Response) + r, err := client.PetApi.AddPet(nil, newPet) + if r.StatusCode != 200 { + t.Log(r) + } + errc <- err + }(pet) + } + waitOnFunctions(t, errc, len(newPets)) + + // Verify they are correct. + for _, pet := range newPets { + go func(pet sw.Pet) { + isPetCorrect(t, pet.Id, pet.Name, pet.Status) + errc <- nil + }(pet) + } + + waitOnFunctions(t, errc, len(newPets)) + + // Update all to active with the name gopherDan + for _, pet := range newPets { + go func(id int64) { + r, err := client.PetApi.UpdatePet(nil, sw.Pet{Id: (int64)(id), Name: "gopherDan", PhotoUrls: []string{"http://1.com", "http://2.com"}, Status: "active"}) + if r.StatusCode != 200 { + t.Log(r) } errc <- err + }(pet.Id) + } + waitOnFunctions(t, errc, len(newPets)) + + // Verify they are correct. + for _, pet := range newPets { + go func(pet sw.Pet) { + isPetCorrect(t, pet.Id, "gopherDan", "active") + errc <- nil }(pet) } - // Wait for the go routines to finish - for i := 0; i < len(newPets); i++ { + waitOnFunctions(t, errc, len(newPets)) + + // Delete them all. + for _, pet := range newPets { + go func(id int64) { + deletePet(t, (int64)(id)) + errc <- nil + }(pet.Id) + } + waitOnFunctions(t, errc, len(newPets)) +} +*/ + +func waitOnFunctions(t *testing.T, errc chan error, n int) { + for i := 0; i < n; i++ { err := <-errc if err != nil { - t.Errorf("Error while adding pet") + t.Errorf("Error performing concurrent test") t.Log(err) } } - - // Sleep for just a moment to let the backend catch up - // Getting random 404 errors from the backend - time.Sleep(time.Second) - - // Verify they are correct. - isPetCorrect(t, s, 12345, "gopherFred", "pending") - isPetCorrect(t, s, 12346, "gopherDan", "active") - isPetCorrect(t, s, 12347, "gopherRick", "mia") - isPetCorrect(t, s, 12348, "gopherJohn", "dead") - - // Get rid of them. - deletePet(t, s, 12345) - deletePet(t, s, 12346) - deletePet(t, s, 12347) - deletePet(t, s, 12348) } -func deletePet(t *testing.T, s *sw.PetApi, id int64) { - apiResponse, err := s.DeletePet(id, nil) +func deletePet(t *testing.T, id int64) { + r, err := client.PetApi.DeletePet(nil, id, nil) if err != nil { t.Errorf("Error while deleting pet by id") t.Log(err) } - if apiResponse.Response.StatusCode != 200 { - t.Log(apiResponse.Response) + if r.StatusCode != 200 { + t.Log(r) } } -func isPetCorrect(t *testing.T, s *sw.PetApi, id int64, name string, status string) { +func isPetCorrect(t *testing.T, id int64, name string, status string) { assert := assert.New(t) - resp, apiResponse, err := s.GetPetById(id) + resp, r, err := client.PetApi.GetPetById(nil, id) if err != nil { t.Errorf("Error while getting pet by id") t.Log(err) @@ -196,7 +261,7 @@ func isPetCorrect(t *testing.T, s *sw.PetApi, id int64, name string, status stri //t.Log(resp) } - if apiResponse.Response.StatusCode != 200 { - t.Log(apiResponse.Response) + if r.StatusCode != 200 { + t.Log(r) } } diff --git a/samples/client/petstore/go/pom.xml b/samples/client/petstore/go/pom.xml index 028ef60a6f4..2e72ae80068 100644 --- a/samples/client/petstore/go/pom.xml +++ b/samples/client/petstore/go/pom.xml @@ -40,6 +40,34 @@ + + go-get-oauth2 + pre-integration-test + + exec + + + go + + get + golang.org/x/oauth2 + + + + + go-get-context + pre-integration-test + + exec + + + go + + get + golang.org/x/net/context + + + go-get-resty pre-integration-test diff --git a/samples/client/petstore/go/user_api_test.go b/samples/client/petstore/go/user_api_test.go index 8ea2c29042a..1699b4326dc 100644 --- a/samples/client/petstore/go/user_api_test.go +++ b/samples/client/petstore/go/user_api_test.go @@ -1,162 +1,158 @@ package main import ( - sw "./go-petstore" - "github.com/stretchr/testify/assert" - "testing" + "testing" + + sw "./go-petstore" + "github.com/stretchr/testify/assert" ) func TestCreateUser(t *testing.T) { - s := sw.NewUserApi() - newUser := sw.User{ - Id: 1000, - FirstName: "gopher", - LastName : "lang", - Username : "gopher", - Password : "lang", - Email : "lang@test.com", - Phone : "5101112222", - UserStatus: 1} - - apiResponse, err := s.CreateUser(newUser) - - if err != nil { - t.Errorf("Error while adding user") - t.Log(err) - } - if apiResponse.Response.StatusCode != 200 { - t.Log(apiResponse.Response) - } + newUser := sw.User{ + Id: 1000, + FirstName: "gopher", + LastName: "lang", + Username: "gopher", + Password: "lang", + Email: "lang@test.com", + Phone: "5101112222", + UserStatus: 1} + + apiResponse, err := client.UserApi.CreateUser(newUser) + + if err != nil { + t.Errorf("Error while adding user") + t.Log(err) + } + if apiResponse.StatusCode != 200 { + t.Log(apiResponse) + } } //adding x to skip the test, currently it is failing func TestCreateUsersWithArrayInput(t *testing.T) { - s := sw.NewUserApi() - newUsers := []sw.User{ - sw.User { - Id: int64(1001), - FirstName: "gopher1", - LastName : "lang1", - Username : "gopher1", - Password : "lang1", - Email : "lang1@test.com", - Phone : "5101112222", - UserStatus: int32(1), - }, - sw.User { - Id: int64(1002), - FirstName: "gopher2", - LastName : "lang2", - Username : "gopher2", - Password : "lang2", - Email : "lang2@test.com", - Phone : "5101112222", - UserStatus: int32(1), - }, - } - - apiResponse, err := s.CreateUsersWithArrayInput(newUsers) - - if err != nil { - t.Errorf("Error while adding users") - t.Log(err) - } - if apiResponse.Response.StatusCode != 200 { - t.Log(apiResponse.Response) - } - - //tear down - _, err1 := s.DeleteUser("gopher1") - if(err1 != nil){ - t.Errorf("Error while deleting user") - t.Log(err1) - } - - _, err2 := s.DeleteUser("gopher2") - if(err2 != nil){ - t.Errorf("Error while deleting user") - t.Log(err2) - } + newUsers := []sw.User{ + sw.User{ + Id: int64(1001), + FirstName: "gopher1", + LastName: "lang1", + Username: "gopher1", + Password: "lang1", + Email: "lang1@test.com", + Phone: "5101112222", + UserStatus: int32(1), + }, + sw.User{ + Id: int64(1002), + FirstName: "gopher2", + LastName: "lang2", + Username: "gopher2", + Password: "lang2", + Email: "lang2@test.com", + Phone: "5101112222", + UserStatus: int32(1), + }, + } + + apiResponse, err := client.UserApi.CreateUsersWithArrayInput(newUsers) + if err != nil { + t.Errorf("Error while adding users") + t.Log(err) + } + if apiResponse.StatusCode != 200 { + t.Log(apiResponse) + } + + //tear down + _, err1 := client.UserApi.DeleteUser("gopher1") + if err1 != nil { + t.Errorf("Error while deleting user") + t.Log(err1) + } + + _, err2 := client.UserApi.DeleteUser("gopher2") + if err2 != nil { + t.Errorf("Error while deleting user") + t.Log(err2) + } } func TestGetUserByName(t *testing.T) { - assert := assert.New(t) - - s := sw.NewUserApi() - resp, apiResponse, err := s.GetUserByName("gopher") - if err != nil { - t.Errorf("Error while getting user by id") - t.Log(err) - } else { - assert.Equal(resp.Id, int64(1000), "User id should be equal") - assert.Equal(resp.Username, "gopher", "User name should be gopher") - assert.Equal(resp.LastName, "lang", "Last name should be lang") - //t.Log(resp) - } - if apiResponse.Response.StatusCode != 200 { - t.Log(apiResponse.Response) - } + assert := assert.New(t) + + resp, apiResponse, err := client.UserApi.GetUserByName("gopher") + if err != nil { + t.Errorf("Error while getting user by id") + t.Log(err) + } else { + assert.Equal(resp.Id, int64(1000), "User id should be equal") + assert.Equal(resp.Username, "gopher", "User name should be gopher") + assert.Equal(resp.LastName, "lang", "Last name should be lang") + //t.Log(resp) + } + if apiResponse.StatusCode != 200 { + t.Log(apiResponse) + } } func TestGetUserByNameWithInvalidID(t *testing.T) { - s := sw.NewUserApi() - resp, apiResponse, err := s.GetUserByName("999999999") - if err != nil { - t.Errorf("Error while getting user by invalid id") - t.Log(err) - t.Log(apiResponse) - } else { - t.Log(resp) - } - if apiResponse.Response.StatusCode != 200 { - t.Log(apiResponse.Response) - } + resp, apiResponse, err := client.UserApi.GetUserByName("999999999") + if apiResponse != nil && apiResponse.StatusCode == 404 { + return // This is a pass condition. API will return with a 404 error. + } else if err != nil { + t.Errorf("Error while getting user by invalid id") + t.Log(err) + t.Log(apiResponse) + } else { + t.Log(resp) + } + if apiResponse.StatusCode != 200 { + t.Log(apiResponse) + } } func TestUpdateUser(t *testing.T) { - assert := assert.New(t) - s := sw.NewUserApi() - newUser := sw.User{ - Id: 1000, - FirstName: "gopher20", - LastName : "lang20", - Username : "gopher", - Password : "lang", - Email : "lang@test.com", - Phone : "5101112222", - UserStatus: 1} - - apiResponse, err := s.UpdateUser("gopher", newUser) - - if err != nil { - t.Errorf("Error while deleting user by id") - t.Log(err) - } - if apiResponse.Response.StatusCode != 200 { - t.Log(apiResponse.Response) - } - - //verify changings are correct - resp, apiResponse, err := s.GetUserByName("gopher") - if err != nil { - t.Errorf("Error while getting user by id") - t.Log(err) - } else { - assert.Equal(resp.Id, int64(1000), "User id should be equal") - assert.Equal(resp.FirstName, "gopher20", "User name should be gopher") - assert.Equal(resp.Password, "lang", "User name should be the same") - } + assert := assert.New(t) + + newUser := sw.User{ + Id: 1000, + FirstName: "gopher20", + LastName: "lang20", + Username: "gopher", + Password: "lang", + Email: "lang@test.com", + Phone: "5101112222", + UserStatus: 1} + + apiResponse, err := client.UserApi.UpdateUser("gopher", newUser) + if err != nil { + t.Errorf("Error while deleting user by id") + t.Log(err) + } + if apiResponse.StatusCode != 200 { + t.Log(apiResponse) + } + + //verify changings are correct + resp, apiResponse, err := client.UserApi.GetUserByName("gopher") + if err != nil { + t.Errorf("Error while getting user by id") + t.Log(err) + } else { + assert.Equal(resp.Id, int64(1000), "User id should be equal") + assert.Equal(resp.FirstName, "gopher20", "User name should be gopher") + assert.Equal(resp.Password, "lang", "User name should be the same") + } } func TestDeleteUser(t *testing.T) { - s := sw.NewUserApi() - apiResponse, err := s.DeleteUser("gopher") - - if err != nil { - t.Errorf("Error while deleting user") - t.Log(err) - } - if apiResponse.Response.StatusCode != 200 { - t.Log(apiResponse.Response) - } -} \ No newline at end of file + apiResponse, err := client.UserApi.DeleteUser("gopher") + + if err != nil { + t.Errorf("Error while deleting user") + t.Log(err) + } + if apiResponse.StatusCode != 200 { + t.Log(apiResponse) + } +} diff --git a/samples/server/petstore/go-api-server/go/README.md b/samples/server/petstore/go-api-server/go/README.md index 100f2503789..9ad254ac015 100644 --- a/samples/server/petstore/go-api-server/go/README.md +++ b/samples/server/petstore/go-api-server/go/README.md @@ -13,7 +13,7 @@ To see how to make this your own, look here: [README](https://github.com/swagger-api/swagger-codegen/blob/master/README.md) - API version: 1.0.0 - +- Build date: 2017-03-12T22:24:15.399-05:00 ### Running the server To run the server, follow these simple steps: