[Go] replace go generator with go-experimental generator (#7337)

* replace go with go-experimental

* update samples

* extends with abstract go class

* rearrange

* remove deprecated

* minor fix

* remove go deprecated samples

* update pom, clean up samples

* mark generator as deprecated
This commit is contained in:
William Cheng 2020-09-04 09:56:42 +08:00 committed by GitHub
parent 1f50207bda
commit 14d41310b9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
712 changed files with 37869 additions and 68707 deletions

View File

@ -1,7 +0,0 @@
generatorName: go-experimental
outputDir: samples/client/petstore/go-experimental/go-petstore
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml
templateDir: modules/openapi-generator/src/main/resources/go-experimental
additionalProperties:
packageName: petstore
generateInterfaces: true

View File

@ -1,9 +0,0 @@
generatorName: go-experimental
outputDir: samples/openapi3/client/petstore/go-experimental/go-petstore
inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml
templateDir: modules/openapi-generator/src/main/resources/go-experimental
additionalProperties:
enumClassPrefix: "true"
packageName: petstore
disallowAdditionalPropertiesIfNotPresent: false
generateInterfaces: true

View File

@ -1,6 +1,6 @@
generatorName: go-experimental
generatorName: go
outputDir: samples/openapi3/client/extensions/x-auth-id-alias/go-experimental
inputSpec: modules/openapi-generator/src/test/resources/3_0/extensions/x-auth-id-alias.yaml
templateDir: modules/openapi-generator/src/main/resources/go-experimental
templateDir: modules/openapi-generator/src/main/resources/go
additionalProperties:
packageName: x_auth_id_alias

View File

@ -4,3 +4,4 @@ inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-e
templateDir: modules/openapi-generator/src/main/resources/go
additionalProperties:
packageName: petstore
generateInterfaces: true

View File

@ -1,9 +0,0 @@
generatorName: go
outputDir: samples/client/petstore/go/go-petstore-withXml
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml
templateDir: modules/openapi-generator/src/main/resources/go
additionalProperties:
packageName: petstore
withXml: "true"
withGoCodegenComment: "true"
generateInterfaces: true

View File

@ -1,7 +1,9 @@
generatorName: go
outputDir: samples/openapi3/client/petstore/go/go-petstore
inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml
inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml
templateDir: modules/openapi-generator/src/main/resources/go
additionalProperties:
enumClassPrefix: "true"
packageName: petstore
disallowAdditionalPropertiesIfNotPresent: false
generateInterfaces: true

View File

@ -29,7 +29,7 @@ The following generators are available:
* [erlang-proper](generators/erlang-proper.md)
* [flash-deprecated (deprecated)](generators/flash-deprecated.md)
* [go](generators/go.md)
* [go-experimental (experimental)](generators/go-experimental.md)
* [go-deprecated (deprecated)](generators/go-deprecated.md)
* [groovy](generators/groovy.md)
* [haskell-http-client](generators/haskell-http-client.md)
* [java](generators/java.md)

View File

@ -0,0 +1,211 @@
---
title: Config Options for go-deprecated
sidebar_label: go-deprecated
---
| Option | Description | Values | Default |
| ------ | ----------- | ------ | ------- |
|enumClassPrefix|Prefix enum with class name| |false|
|generateInterfaces|Generate interfaces for api classes| |false|
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |true|
|isGoSubmodule|whether the generated Go module is a submodule| |false|
|packageName|Go package name (convention: lowercase).| |openapi|
|packageVersion|Go package version.| |1.0.0|
|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false|
|structPrefix|whether to prefix struct with the class name. e.g. DeletePetOpts => PetApiDeletePetOpts| |false|
|withAWSV4Signature|whether to include AWS v4 signature support| |false|
|withGoCodegenComment|whether to include Go codegen comment to disable Go Lint and collapse by default in GitHub PRs and diffs| |false|
|withXml|whether to include support for application/xml content type and include XML annotations in the model (works with libraries that provide support for JSON and XML)| |false|
## IMPORT MAPPING
| Type/Alias | Imports |
| ---------- | ------- |
## INSTANTIATION TYPES
| Type/Alias | Instantiated By |
| ---------- | --------------- |
## LANGUAGE PRIMITIVES
<ul class="column-ul">
<li>bool</li>
<li>byte</li>
<li>complex128</li>
<li>complex64</li>
<li>float32</li>
<li>float64</li>
<li>int</li>
<li>int32</li>
<li>int64</li>
<li>interface{}</li>
<li>map[string]interface{}</li>
<li>rune</li>
<li>string</li>
<li>uint</li>
<li>uint32</li>
<li>uint64</li>
</ul>
## RESERVED WORDS
<ul class="column-ul">
<li>bool</li>
<li>break</li>
<li>byte</li>
<li>case</li>
<li>chan</li>
<li>complex128</li>
<li>complex64</li>
<li>const</li>
<li>continue</li>
<li>default</li>
<li>defer</li>
<li>else</li>
<li>error</li>
<li>fallthrough</li>
<li>float32</li>
<li>float64</li>
<li>for</li>
<li>func</li>
<li>go</li>
<li>goto</li>
<li>if</li>
<li>import</li>
<li>int</li>
<li>int16</li>
<li>int32</li>
<li>int64</li>
<li>int8</li>
<li>interface</li>
<li>map</li>
<li>nil</li>
<li>package</li>
<li>range</li>
<li>return</li>
<li>rune</li>
<li>select</li>
<li>string</li>
<li>struct</li>
<li>switch</li>
<li>type</li>
<li>uint</li>
<li>uint16</li>
<li>uint32</li>
<li>uint64</li>
<li>uint8</li>
<li>uintptr</li>
<li>var</li>
</ul>
## FEATURE SET
### Client Modification Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|BasePath|✓|ToolingExtension
|Authorizations|✗|ToolingExtension
|UserAgent|✓|ToolingExtension
|MockServer|✗|ToolingExtension
### Data Type Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|Custom|✗|OAS2,OAS3
|Int32|✓|OAS2,OAS3
|Int64|✓|OAS2,OAS3
|Float|✓|OAS2,OAS3
|Double|✓|OAS2,OAS3
|Decimal|✓|ToolingExtension
|String|✓|OAS2,OAS3
|Byte|✓|OAS2,OAS3
|Binary|✓|OAS2,OAS3
|Boolean|✓|OAS2,OAS3
|Date|✓|OAS2,OAS3
|DateTime|✓|OAS2,OAS3
|Password|✓|OAS2,OAS3
|File|✓|OAS2
|Array|✓|OAS2,OAS3
|Maps|✓|ToolingExtension
|CollectionFormat|✓|OAS2
|CollectionFormatMulti|✓|OAS2
|Enum|✓|OAS2,OAS3
|ArrayOfEnum|✓|ToolingExtension
|ArrayOfModel|✓|ToolingExtension
|ArrayOfCollectionOfPrimitives|✓|ToolingExtension
|ArrayOfCollectionOfModel|✓|ToolingExtension
|ArrayOfCollectionOfEnum|✓|ToolingExtension
|MapOfEnum|✓|ToolingExtension
|MapOfModel|✓|ToolingExtension
|MapOfCollectionOfPrimitives|✓|ToolingExtension
|MapOfCollectionOfModel|✓|ToolingExtension
|MapOfCollectionOfEnum|✓|ToolingExtension
### Documentation Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|Readme|✓|ToolingExtension
|Model|✓|ToolingExtension
|Api|✓|ToolingExtension
### Global Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|Host|✓|OAS2,OAS3
|BasePath|✓|OAS2,OAS3
|Info|✓|OAS2,OAS3
|Schemes|✗|OAS2,OAS3
|PartialSchemes|✓|OAS2,OAS3
|Consumes|✓|OAS2
|Produces|✓|OAS2
|ExternalDocumentation|✓|OAS2,OAS3
|Examples|✓|OAS2,OAS3
|XMLStructureDefinitions|✗|OAS2,OAS3
|MultiServer|✗|OAS3
|ParameterizedServer|✓|OAS3
|ParameterStyling|✗|OAS3
|Callbacks|✗|OAS3
|LinkObjects|✗|OAS3
### Parameter Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|Path|✓|OAS2,OAS3
|Query|✓|OAS2,OAS3
|Header|✓|OAS2,OAS3
|Body|✓|OAS2
|FormUnencoded|✓|OAS2
|FormMultipart|✓|OAS2
|Cookie|✓|OAS3
### Schema Support Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|Simple|✓|OAS2,OAS3
|Composite|✓|OAS2,OAS3
|Polymorphism|✗|OAS2,OAS3
|Union|✗|OAS3
### Security Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|BasicAuth|✓|OAS2,OAS3
|ApiKey|✓|OAS2,OAS3
|OpenIDConnect|✗|OAS3
|BearerToken|✗|OAS3
|OAuth2_Implicit|✓|OAS2,OAS3
|OAuth2_Password|✗|OAS2,OAS3
|OAuth2_ClientCredentials|✗|OAS2,OAS3
|OAuth2_AuthorizationCode|✗|OAS2,OAS3
### Wire Format Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|JSON|✓|OAS2,OAS3
|XML|✓|OAS2,OAS3
|PROTOBUF|✗|ToolingExtension
|Custom|✗|OAS2,OAS3

View File

@ -5,6 +5,7 @@ sidebar_label: go
| Option | Description | Values | Default |
| ------ | ----------- | ------ | ------- |
|disallowAdditionalPropertiesIfNotPresent|Specify the behavior when the 'additionalProperties' keyword is not present in the OAS document. If false: the 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications. If true: when the 'additionalProperties' keyword is not present in a schema, the value of 'additionalProperties' is set to false, i.e. no additional properties are allowed. Note: this mode is not compliant with the JSON schema specification. This is the original openapi-generator behavior.This setting is currently ignored for OAS 2.0 documents: 1) When the 'additionalProperties' keyword is not present in a 2.0 schema, additional properties are NOT allowed. 2) Boolean values of the 'additionalProperties' keyword are ignored. It's as if additional properties are NOT allowed.Note: the root cause are issues #1369 and #1371, which must be resolved in the swagger-parser project.|<dl><dt>**false**</dt><dd>The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.</dd><dt>**true**</dt><dd>when the 'additionalProperties' keyword is not present in a schema, the value of 'additionalProperties' is automatically set to false, i.e. no additional properties are allowed. Note: this mode is not compliant with the JSON schema specification. This is the original openapi-generator behavior.</dd></dl>|true|
|enumClassPrefix|Prefix enum with class name| |false|
|generateInterfaces|Generate interfaces for api classes| |false|
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |true|
@ -13,6 +14,7 @@ sidebar_label: go
|packageVersion|Go package version.| |1.0.0|
|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false|
|structPrefix|whether to prefix struct with the class name. e.g. DeletePetOpts =&gt; PetApiDeletePetOpts| |false|
|useOneOfDiscriminatorLookup|Use the discriminator's mapping in oneOf to speed up the model lookup. IMPORTANT: Validation (e.g. one and onlye one match in oneOf's schemas) will be skipped.| |false|
|withAWSV4Signature|whether to include AWS v4 signature support| |false|
|withGoCodegenComment|whether to include Go codegen comment to disable Go Lint and collapse by default in GitHub PRs and diffs| |false|
|withXml|whether to include support for application/xml content type and include XML annotations in the model (works with libraries that provide support for JSON and XML)| |false|

View File

@ -631,7 +631,7 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege
}
}
if (this instanceof GoClientExperimentalCodegen && model.isEnum) {
if (this instanceof GoClientCodegen && model.isEnum) {
imports.add(createMapping("import", "fmt"));
}

View File

@ -17,30 +17,37 @@
package org.openapitools.codegen.languages;
import org.openapitools.codegen.CliOption;
import org.openapitools.codegen.CodegenConstants;
import org.openapitools.codegen.CodegenType;
import org.openapitools.codegen.SupportingFile;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.*;
import org.openapitools.codegen.meta.GeneratorMetadata;
import org.openapitools.codegen.meta.Stability;
import org.openapitools.codegen.meta.features.*;
import org.openapitools.codegen.utils.ModelUtils;
import org.openapitools.codegen.utils.ProcessUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.EnumSet;
import java.util.*;
import static org.openapitools.codegen.utils.StringUtils.camelize;
public class GoClientCodegen extends AbstractGoCodegen {
private static final Logger LOGGER = LoggerFactory.getLogger(GoClientCodegen.class);
protected String packageVersion = "1.0.0";
protected String apiDocPath = "docs/";
protected String modelDocPath = "docs/";
protected boolean isGoSubmodule = false;
public static final String WITH_GO_CODEGEN_COMMENT = "withGoCodegenComment";
public static final String WITH_XML = "withXml";
public static final String STRUCT_PREFIX = "structPrefix";
public static final String WITH_AWSV4_SIGNATURE = "withAWSV4Signature";
public static final String GENERATE_INTERFACES = "generateInterfaces";
protected String goImportAlias = "openapiclient";
protected boolean isGoSubmodule = false;
protected boolean useOneOfDiscriminatorLookup = false; // use oneOf discriminator's mapping for model lookup
public GoClientCodegen() {
super();
@ -74,15 +81,16 @@ public class GoClientCodegen extends AbstractGoCodegen {
)
);
outputFolder = "generated-code/go";
modelTemplateFiles.put("model.mustache", ".go");
apiTemplateFiles.put("api.mustache", ".go");
generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata).stability(Stability.STABLE).build();
outputFolder = "generated-code/go";
embeddedTemplateDir = templateDir = "go";
usesOptionals = false;
apiTemplateFiles.put("api.mustache", ".go");
modelDocTemplateFiles.put("model_doc.mustache", ".md");
apiDocTemplateFiles.put("api_doc.mustache", ".md");
embeddedTemplateDir = templateDir = "go";
// default HIDE_GENERATION_TIMESTAMP to true
hideGenerationTimestamp = Boolean.TRUE;
@ -99,10 +107,66 @@ public class GoClientCodegen extends AbstractGoCodegen {
CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS,
CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS_DESC)
.defaultValue(Boolean.FALSE.toString()));
cliOptions.add(new CliOption(CodegenConstants.USE_ONEOF_DISCRIMINATOR_LOOKUP, CodegenConstants.USE_ONEOF_DISCRIMINATOR_LOOKUP_DESC).defaultValue("false"));
// option to change how we process + set the data in the 'additionalProperties' keyword.
CliOption disallowAdditionalPropertiesIfNotPresentOpt = CliOption.newBoolean(
CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT,
CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT_DESC).defaultValue(Boolean.TRUE.toString());
Map<String, String> disallowAdditionalPropertiesIfNotPresentOpts = new HashMap<>();
disallowAdditionalPropertiesIfNotPresentOpts.put("false",
"The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.");
disallowAdditionalPropertiesIfNotPresentOpts.put("true",
"when the 'additionalProperties' keyword is not present in a schema, " +
"the value of 'additionalProperties' is automatically set to false, i.e. no additional properties are allowed. " +
"Note: this mode is not compliant with the JSON schema specification. " +
"This is the original openapi-generator behavior.");
disallowAdditionalPropertiesIfNotPresentOpt.setEnum(disallowAdditionalPropertiesIfNotPresentOpts);
cliOptions.add(disallowAdditionalPropertiesIfNotPresentOpt);
this.setDisallowAdditionalPropertiesIfNotPresent(true);
}
/**
* Configures a friendly name for the generator. This will be used by the
* generator to select the library with the -g flag.
*
* @return the friendly name for the generator
*/
@Override
public String getName() {
return "go";
}
/**
* Configures the type of generator.
*
* @return the CodegenType for this generator
* @see org.openapitools.codegen.CodegenType
*/
@Override
public CodegenType getTag() {
return CodegenType.CLIENT;
}
@Override
public String toGetter(String name) {
return "Get" + getterAndSetterCapitalize(name);
}
/**
* Returns human-friendly help for the generator. Provide the consumer with help
* tips, parameters here
*
* @return A string value for the help message
*/
@Override
public String getHelp() {
return "Generates a Go client library.";
}
@Override
public void processOpts() {
this.setLegacyDiscriminatorBehavior(false);
super.processOpts();
if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) {
@ -126,17 +190,6 @@ public class GoClientCodegen extends AbstractGoCodegen {
modelPackage = packageName;
apiPackage = packageName;
supportingFiles.add(new SupportingFile("openapi.mustache", "api", "openapi.yaml"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
supportingFiles.add(new SupportingFile("configuration.mustache", "", "configuration.go"));
supportingFiles.add(new SupportingFile("client.mustache", "", "client.go"));
supportingFiles.add(new SupportingFile("response.mustache", "", "response.go"));
supportingFiles.add(new SupportingFile("go.mod.mustache", "", "go.mod"));
supportingFiles.add(new SupportingFile("go.sum", "", "go.sum"));
supportingFiles.add(new SupportingFile(".travis.yml", "", ".travis.yml"));
if (additionalProperties.containsKey(WITH_GO_CODEGEN_COMMENT)) {
setWithGoCodegenComment(Boolean.parseBoolean(additionalProperties.get(WITH_GO_CODEGEN_COMMENT).toString()));
additionalProperties.put(WITH_GO_CODEGEN_COMMENT, withGoCodegenComment);
@ -171,39 +224,63 @@ public class GoClientCodegen extends AbstractGoCodegen {
setGenerateInterfaces(Boolean.parseBoolean(additionalProperties.get(GENERATE_INTERFACES).toString()));
additionalProperties.put(GENERATE_INTERFACES, generateInterfaces);
}
// Generate the 'signing.py' module, but only if the 'HTTP signature' security scheme is specified in the OAS.
Map<String, SecurityScheme> securitySchemeMap = openAPI != null ?
(openAPI.getComponents() != null ? openAPI.getComponents().getSecuritySchemes() : null) : null;
List<CodegenSecurity> authMethods = fromSecurity(securitySchemeMap);
if (ProcessUtils.hasHttpSignatureMethods(authMethods)) {
supportingFiles.add(new SupportingFile("signing.mustache", "", "signing.go"));
}
if (additionalProperties.containsKey("goImportAlias")) {
setGoImportAlias(additionalProperties.get("goImportAlias").toString());
} else {
additionalProperties.put("goImportAlias", goImportAlias);
}
if (additionalProperties.containsKey(CodegenConstants.USE_ONEOF_DISCRIMINATOR_LOOKUP)) {
setUseOneOfDiscriminatorLookup(convertPropertyToBooleanAndWriteBack(CodegenConstants.USE_ONEOF_DISCRIMINATOR_LOOKUP));
} else {
additionalProperties.put(CodegenConstants.USE_ONEOF_DISCRIMINATOR_LOOKUP, getUseOneOfDiscriminatorLookup());
}
if (additionalProperties.containsKey(CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT)) {
this.setDisallowAdditionalPropertiesIfNotPresent(Boolean.valueOf(additionalProperties
.get(CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT).toString()));
}
supportingFiles.add(new SupportingFile("openapi.mustache", "api", "openapi.yaml"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
supportingFiles.add(new SupportingFile("configuration.mustache", "", "configuration.go"));
supportingFiles.add(new SupportingFile("client.mustache", "", "client.go"));
supportingFiles.add(new SupportingFile("response.mustache", "", "response.go"));
supportingFiles.add(new SupportingFile("go.mod.mustache", "", "go.mod"));
supportingFiles.add(new SupportingFile("go.sum", "", "go.sum"));
supportingFiles.add(new SupportingFile(".travis.yml", "", ".travis.yml"));
supportingFiles.add(new SupportingFile("utils.mustache", "", "utils.go"));
}
/**
* Configures the type of generator.
*
* @return the CodegenType for this generator
* @see org.openapitools.codegen.CodegenType
*/
@Override
public CodegenType getTag() {
return CodegenType.CLIENT;
public void setUseOneOfDiscriminatorLookup(boolean useOneOfDiscriminatorLookup) {
this.useOneOfDiscriminatorLookup = useOneOfDiscriminatorLookup;
}
/**
* Configures a friendly name for the generator. This will be used by the generator
* to select the library with the -g flag.
*
* @return the friendly name for the generator
*/
@Override
public String getName() {
return "go";
public boolean getUseOneOfDiscriminatorLookup() {
return this.useOneOfDiscriminatorLookup;
}
/**
* Returns human-friendly help for the generator. Provide the consumer with help
* tips, parameters here
*
* @return A string value for the help message
*/
@Override
public String getHelp() {
return "Generates a Go client library (beta).";
public void setGoImportAlias(String goImportAlias) {
this.goImportAlias = goImportAlias;
}
public void setPackageVersion(String packageVersion) {
this.packageVersion = packageVersion;
}
public void setIsGoSubmodule(boolean isGoSubmodule) {
this.isGoSubmodule = isGoSubmodule;
}
/**
@ -240,12 +317,267 @@ public class GoClientCodegen extends AbstractGoCodegen {
return toApiName(name);
}
public void setPackageVersion(String packageVersion) {
this.packageVersion = packageVersion;
@Override
public String toModelName(String name) {
// underscoring would also lowercase the whole name, thus losing acronyms which are in capitals
return camelize(toModel(name, false));
}
public void setIsGoSubmodule(boolean isGoSubmodule) {
this.isGoSubmodule = isGoSubmodule;
public String escapeReservedWord(String name) {
if (this.reservedWordsMappings().containsKey(name)) {
return this.reservedWordsMappings().get(name);
}
return name + '_';
}
@Override
public String toEnumDefaultValue(String value, String datatype) {
String prefix = "";
if (enumClassPrefix) {
prefix = datatype.toUpperCase(Locale.ROOT) + "_";
}
return prefix + value;
}
@Override
public void updateCodegenPropertyEnum(CodegenProperty var) {
// make sure the inline enums have plain defaults (e.g. string, int, float)
String enumDefault = null;
if (var.isEnum && var.defaultValue != null) {
enumDefault = var.defaultValue;
}
super.updateCodegenPropertyEnum(var);
if (var.isEnum && enumDefault != null) {
var.defaultValue = enumDefault;
}
}
@Override
public String toDefaultValue(Schema p) {
p = ModelUtils.getReferencedSchema(this.openAPI, p);
if (ModelUtils.isStringSchema(p)) {
if (p.getDefault() != null) {
return "\"" + escapeText((String) p.getDefault()) + "\"";
}
return null;
}
return super.toDefaultValue(p);
}
@Override
public CodegenProperty fromProperty(String name, Schema p) {
CodegenProperty prop = super.fromProperty(name, p);
String cc = camelize(prop.name, true);
if (isReservedWord(cc)) {
cc = escapeReservedWord(cc);
}
prop.nameInCamelCase = cc;
return prop;
}
@Override
public Map<String, Object> postProcessModels(Map<String, Object> objs) {
// The superclass determines the list of required golang imports. The actual list of imports
// depends on which types are used, some of which are changed in the code below (but then preserved
// and used through x-go-base-type in templates). So super.postProcessModels
// must be invoked at the beginning of this method.
objs = super.postProcessModels(objs);
List<Map<String, String>> imports = (List<Map<String, String>>) objs.get("imports");
List<Map<String, Object>> models = (List<Map<String, Object>>) objs.get("models");
for (Map<String, Object> m : models) {
Object v = m.get("model");
if (v instanceof CodegenModel) {
CodegenModel model = (CodegenModel) v;
if (model.isEnum) {
continue;
}
for (CodegenProperty param : model.vars) {
param.vendorExtensions.put("x-go-base-type", param.dataType);
if (!param.isNullable || param.isMapContainer || param.isListContainer ||
param.isFreeFormObject || param.isAnyType) {
continue;
}
if (param.isDateTime) {
// Note this could have been done by adding the following line in processOpts(),
// however, we only want to represent the DateTime object as NullableTime if
// it's marked as nullable in the spec.
// typeMapping.put("DateTime", "NullableTime");
param.dataType = "NullableTime";
} else {
param.dataType = "Nullable" + Character.toUpperCase(param.dataType.charAt(0))
+ param.dataType.substring(1);
}
}
// additional import for different cases
// oneOf
if (model.oneOf != null && !model.oneOf.isEmpty()) {
imports.add(createMapping("import", "fmt"));
}
// anyOf
if (model.anyOf != null && !model.anyOf.isEmpty()) {
imports.add(createMapping("import", "fmt"));
}
// additionalProperties: true and parent
if (model.isAdditionalPropertiesTrue && model.parent != null && Boolean.FALSE.equals(model.isMapModel)) {
imports.add(createMapping("import", "reflect"));
imports.add(createMapping("import", "strings"));
}
}
}
return objs;
}
@Override
public Map<String, Object> postProcessOperationsWithModels(Map<String, Object> objs, List<Object> allModels) {
objs = super.postProcessOperationsWithModels(objs, allModels);
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
HashMap<String, CodegenModel> modelMaps = new HashMap<String, CodegenModel>();
HashMap<String, Integer> processedModelMaps = new HashMap<String, Integer>();
for (Object o : allModels) {
HashMap<String, Object> h = (HashMap<String, Object>) o;
CodegenModel m = (CodegenModel) h.get("model");
modelMaps.put(m.classname, m);
}
List<CodegenOperation> operationList = (List<CodegenOperation>) operations.get("operation");
for (CodegenOperation op : operationList) {
for (CodegenParameter p : op.allParams) {
p.vendorExtensions.put("x-go-example", constructExampleCode(p, modelMaps, processedModelMaps));
}
}
processedModelMaps.clear();
for (CodegenOperation operation : operationList) {
for (CodegenParameter cp : operation.allParams) {
cp.vendorExtensions.put("x-go-example", constructExampleCode(cp, modelMaps, processedModelMaps));
}
}
return objs;
}
private String constructExampleCode(CodegenParameter codegenParameter, HashMap<String, CodegenModel> modelMaps, HashMap<String, Integer> processedModelMap) {
if (codegenParameter.isListContainer) { // array
return codegenParameter.dataType + "{" + constructExampleCode(codegenParameter.items, modelMaps, processedModelMap) + "}";
} else if (codegenParameter.isMapContainer) {
return "map[string]string{ \"Key\" = \"Value\" }";
} else if (codegenParameter.isPrimitiveType) { // primitive type
if (codegenParameter.isString) {
if (StringUtils.isEmpty(codegenParameter.example)) {
return "\"" + codegenParameter.example + "\"";
} else {
return "\"" + codegenParameter.paramName + "_example\"";
}
} else if (codegenParameter.isBoolean) { // boolean
if (Boolean.parseBoolean(codegenParameter.example)) {
return "true";
} else {
return "false";
}
} else if (codegenParameter.isUri) { // URL
return "URL(string: \"https://example.com\")!";
} else if (codegenParameter.isDateTime || codegenParameter.isDate) { // datetime or date
return "Get-Date";
} else { // numeric
if (StringUtils.isEmpty(codegenParameter.example)) {
return codegenParameter.example;
} else {
return "987";
}
}
} else { // model
// look up the model
if (modelMaps.containsKey(codegenParameter.dataType)) {
return constructExampleCode(modelMaps.get(codegenParameter.dataType), modelMaps, processedModelMap);
} else {
//LOGGER.error("Error in constructing examples. Failed to look up the model " + codegenParameter.dataType);
return "TODO";
}
}
}
private String constructExampleCode(CodegenProperty codegenProperty, HashMap<String, CodegenModel> modelMaps, HashMap<String, Integer> processedModelMap) {
if (codegenProperty.isListContainer) { // array
return codegenProperty.dataType + "{" + constructExampleCode(codegenProperty.items, modelMaps, processedModelMap) + ")";
} else if (codegenProperty.isMapContainer) { // map
return "map[string]string{ \"Key\" = \"Value\" }";
} else if (codegenProperty.isPrimitiveType) { // primitive type
if (codegenProperty.isString) {
if (StringUtils.isEmpty(codegenProperty.example)) {
return "\"" + codegenProperty.example + "\"";
} else {
return "\"" + codegenProperty.name + "_example\"";
}
} else if (codegenProperty.isBoolean) { // boolean
if (Boolean.parseBoolean(codegenProperty.example)) {
return "true";
} else {
return "false";
}
} else if (codegenProperty.isUri) { // URL
return "\"https://example.com\")!";
} else if (codegenProperty.isDateTime || codegenProperty.isDate) { // datetime or date
return "time.Now()";
} else { // numeric
String example;
if (StringUtils.isEmpty(codegenProperty.example)) {
example = codegenProperty.example;
} else {
example = "123";
}
if (codegenProperty.isLong) {
return "int64(" + example + ")";
} else {
return example;
}
}
} else {
// look up the model
if (modelMaps.containsKey(codegenProperty.dataType)) {
return constructExampleCode(modelMaps.get(codegenProperty.dataType), modelMaps, processedModelMap);
} else {
//LOGGER.error("Error in constructing examples. Failed to look up the model " + codegenProperty.dataType);
return "\"TODO\"";
}
}
}
private String constructExampleCode(CodegenModel codegenModel, HashMap<String, CodegenModel> modelMaps, HashMap<String, Integer> processedModelMap) {
String example;
// break infinite recursion. Return, in case a model is already processed in the current context.
String model = codegenModel.name;
if (processedModelMap.containsKey(model)) {
int count = processedModelMap.get(model);
if (count == 1) {
processedModelMap.put(model, 2);
} else if (count == 2) {
return "";
} else {
throw new RuntimeException("Invalid count when constructing example: " + count);
}
} else {
processedModelMap.put(model, 1);
}
example = "" + goImportAlias + "." + codegenModel.name + "{";
List<String> propertyExamples = new ArrayList<>();
for (CodegenProperty codegenProperty : codegenModel.allVars) {
propertyExamples.add(codegenProperty.name + ": " + constructExampleCode(codegenProperty, modelMaps, processedModelMap));
}
example += StringUtils.join(propertyExamples, ", ");
example += "}";
return example;
}
}

View File

@ -1,403 +0,0 @@
/*
* Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openapitools.codegen.languages;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.*;
import org.openapitools.codegen.meta.GeneratorMetadata;
import org.openapitools.codegen.meta.Stability;
import org.openapitools.codegen.utils.ModelUtils;
import org.openapitools.codegen.utils.ProcessUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import static org.openapitools.codegen.utils.StringUtils.camelize;
public class GoClientExperimentalCodegen extends GoClientCodegen {
private static final Logger LOGGER = LoggerFactory.getLogger(GoClientExperimentalCodegen.class);
protected String goImportAlias = "openapiclient";
protected boolean useOneOfDiscriminatorLookup = false; // use oneOf discriminator's mapping for model lookup
public GoClientExperimentalCodegen() {
super();
outputFolder = "generated-code/go-experimental";
embeddedTemplateDir = templateDir = "go-experimental";
usesOptionals = false;
generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata).stability(Stability.EXPERIMENTAL).build();
cliOptions.add(new CliOption(CodegenConstants.USE_ONEOF_DISCRIMINATOR_LOOKUP, CodegenConstants.USE_ONEOF_DISCRIMINATOR_LOOKUP_DESC).defaultValue("false"));
// option to change how we process + set the data in the 'additionalProperties' keyword.
CliOption disallowAdditionalPropertiesIfNotPresentOpt = CliOption.newBoolean(
CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT,
CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT_DESC).defaultValue(Boolean.TRUE.toString());
Map<String, String> disallowAdditionalPropertiesIfNotPresentOpts = new HashMap<>();
disallowAdditionalPropertiesIfNotPresentOpts.put("false",
"The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.");
disallowAdditionalPropertiesIfNotPresentOpts.put("true",
"when the 'additionalProperties' keyword is not present in a schema, " +
"the value of 'additionalProperties' is automatically set to false, i.e. no additional properties are allowed. " +
"Note: this mode is not compliant with the JSON schema specification. " +
"This is the original openapi-generator behavior.");
disallowAdditionalPropertiesIfNotPresentOpt.setEnum(disallowAdditionalPropertiesIfNotPresentOpts);
cliOptions.add(disallowAdditionalPropertiesIfNotPresentOpt);
this.setDisallowAdditionalPropertiesIfNotPresent(true);
}
/**
* Configures a friendly name for the generator. This will be used by the
* generator to select the library with the -g flag.
*
* @return the friendly name for the generator
*/
@Override
public String getName() {
return "go-experimental";
}
@Override
public String toGetter(String name) {
return "Get" + getterAndSetterCapitalize(name);
}
/**
* Returns human-friendly help for the generator. Provide the consumer with help
* tips, parameters here
*
* @return A string value for the help message
*/
@Override
public String getHelp() {
return "Generates a Go client library (experimental and may subject to breaking changes without further notice).";
}
@Override
public void processOpts() {
this.setLegacyDiscriminatorBehavior(false);
super.processOpts();
supportingFiles.add(new SupportingFile("utils.mustache", "", "utils.go"));
// Generate the 'signing.py' module, but only if the 'HTTP signature' security scheme is specified in the OAS.
Map<String, SecurityScheme> securitySchemeMap = openAPI != null ?
(openAPI.getComponents() != null ? openAPI.getComponents().getSecuritySchemes() : null) : null;
List<CodegenSecurity> authMethods = fromSecurity(securitySchemeMap);
if (ProcessUtils.hasHttpSignatureMethods(authMethods)) {
supportingFiles.add(new SupportingFile("signing.mustache", "", "signing.go"));
}
if (additionalProperties.containsKey("goImportAlias")) {
setGoImportAlias(additionalProperties.get("goImportAlias").toString());
} else {
additionalProperties.put("goImportAlias", goImportAlias);
}
if (additionalProperties.containsKey(CodegenConstants.USE_ONEOF_DISCRIMINATOR_LOOKUP)) {
setUseOneOfDiscriminatorLookup(convertPropertyToBooleanAndWriteBack(CodegenConstants.USE_ONEOF_DISCRIMINATOR_LOOKUP));
} else {
additionalProperties.put(CodegenConstants.USE_ONEOF_DISCRIMINATOR_LOOKUP, useOneOfDiscriminatorLookup);
}
if (additionalProperties.containsKey(CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT)) {
this.setDisallowAdditionalPropertiesIfNotPresent(Boolean.valueOf(additionalProperties
.get(CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT).toString()));
}
}
public void setUseOneOfDiscriminatorLookup(boolean useOneOfDiscriminatorLookup) {
this.useOneOfDiscriminatorLookup = useOneOfDiscriminatorLookup;
}
public boolean getUseOneOfDiscriminatorLookup() {
return this.useOneOfDiscriminatorLookup;
}
public void setGoImportAlias(String goImportAlias) {
this.goImportAlias = goImportAlias;
}
@Override
public String toModelName(String name) {
// underscoring would also lowercase the whole name, thus losing acronyms which are in capitals
return camelize(toModel(name, false));
}
public String escapeReservedWord(String name) {
if (this.reservedWordsMappings().containsKey(name)) {
return this.reservedWordsMappings().get(name);
}
return name + '_';
}
@Override
public String toEnumDefaultValue(String value, String datatype) {
String prefix = "";
if (enumClassPrefix) {
prefix = datatype.toUpperCase(Locale.ROOT) + "_";
}
return prefix + value;
}
@Override
public void updateCodegenPropertyEnum(CodegenProperty var) {
// make sure the inline enums have plain defaults (e.g. string, int, float)
String enumDefault = null;
if (var.isEnum && var.defaultValue != null) {
enumDefault = var.defaultValue;
}
super.updateCodegenPropertyEnum(var);
if (var.isEnum && enumDefault != null) {
var.defaultValue = enumDefault;
}
}
@Override
public String toDefaultValue(Schema p) {
p = ModelUtils.getReferencedSchema(this.openAPI, p);
if (ModelUtils.isStringSchema(p)) {
if (p.getDefault() != null) {
return "\"" + escapeText((String) p.getDefault()) + "\"";
}
return null;
}
return super.toDefaultValue(p);
}
@Override
public CodegenProperty fromProperty(String name, Schema p) {
CodegenProperty prop = super.fromProperty(name, p);
String cc = camelize(prop.name, true);
if (isReservedWord(cc)) {
cc = escapeReservedWord(cc);
}
prop.nameInCamelCase = cc;
return prop;
}
@Override
public Map<String, Object> postProcessModels(Map<String, Object> objs) {
// The superclass determines the list of required golang imports. The actual list of imports
// depends on which types are used, some of which are changed in the code below (but then preserved
// and used through x-go-base-type in templates). So super.postProcessModels
// must be invoked at the beginning of this method.
objs = super.postProcessModels(objs);
List<Map<String, String>> imports = (List<Map<String, String>>) objs.get("imports");
List<Map<String, Object>> models = (List<Map<String, Object>>) objs.get("models");
for (Map<String, Object> m : models) {
Object v = m.get("model");
if (v instanceof CodegenModel) {
CodegenModel model = (CodegenModel) v;
if (model.isEnum) {
continue;
}
for (CodegenProperty param : model.vars) {
param.vendorExtensions.put("x-go-base-type", param.dataType);
if (!param.isNullable || param.isMapContainer || param.isListContainer ||
param.isFreeFormObject || param.isAnyType) {
continue;
}
if (param.isDateTime) {
// Note this could have been done by adding the following line in processOpts(),
// however, we only want to represent the DateTime object as NullableTime if
// it's marked as nullable in the spec.
// typeMapping.put("DateTime", "NullableTime");
param.dataType = "NullableTime";
} else {
param.dataType = "Nullable" + Character.toUpperCase(param.dataType.charAt(0))
+ param.dataType.substring(1);
}
}
// additional import for different cases
// oneOf
if (model.oneOf != null && !model.oneOf.isEmpty()) {
imports.add(createMapping("import", "fmt"));
}
// anyOf
if (model.anyOf != null && !model.anyOf.isEmpty()) {
imports.add(createMapping("import", "fmt"));
}
// additionalProperties: true and parent
if (model.isAdditionalPropertiesTrue && model.parent != null && Boolean.FALSE.equals(model.isMapModel)) {
imports.add(createMapping("import", "reflect"));
imports.add(createMapping("import", "strings"));
}
}
}
return objs;
}
@Override
public Map<String, Object> postProcessOperationsWithModels(Map<String, Object> objs, List<Object> allModels) {
objs = super.postProcessOperationsWithModels(objs, allModels);
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
HashMap<String, CodegenModel> modelMaps = new HashMap<String, CodegenModel>();
HashMap<String, Integer> processedModelMaps = new HashMap<String, Integer>();
for (Object o : allModels) {
HashMap<String, Object> h = (HashMap<String, Object>) o;
CodegenModel m = (CodegenModel) h.get("model");
modelMaps.put(m.classname, m);
}
List<CodegenOperation> operationList = (List<CodegenOperation>) operations.get("operation");
for (CodegenOperation op : operationList) {
for (CodegenParameter p : op.allParams) {
p.vendorExtensions.put("x-go-example", constructExampleCode(p, modelMaps, processedModelMaps));
}
}
processedModelMaps.clear();
for (CodegenOperation operation : operationList) {
for (CodegenParameter cp : operation.allParams) {
cp.vendorExtensions.put("x-go-example", constructExampleCode(cp, modelMaps, processedModelMaps));
}
}
return objs;
}
private String constructExampleCode(CodegenParameter codegenParameter, HashMap<String, CodegenModel> modelMaps, HashMap<String, Integer> processedModelMap) {
if (codegenParameter.isListContainer) { // array
return codegenParameter.dataType + "{" + constructExampleCode(codegenParameter.items, modelMaps, processedModelMap) + "}";
} else if (codegenParameter.isMapContainer) {
return "map[string]string{ \"Key\" = \"Value\" }";
} else if (codegenParameter.isPrimitiveType) { // primitive type
if (codegenParameter.isString) {
if (StringUtils.isEmpty(codegenParameter.example)) {
return "\"" + codegenParameter.example + "\"";
} else {
return "\"" + codegenParameter.paramName + "_example\"";
}
} else if (codegenParameter.isBoolean) { // boolean
if (Boolean.parseBoolean(codegenParameter.example)) {
return "true";
} else {
return "false";
}
} else if (codegenParameter.isUri) { // URL
return "URL(string: \"https://example.com\")!";
} else if (codegenParameter.isDateTime || codegenParameter.isDate) { // datetime or date
return "Get-Date";
} else { // numeric
if (StringUtils.isEmpty(codegenParameter.example)) {
return codegenParameter.example;
} else {
return "987";
}
}
} else { // model
// look up the model
if (modelMaps.containsKey(codegenParameter.dataType)) {
return constructExampleCode(modelMaps.get(codegenParameter.dataType), modelMaps, processedModelMap);
} else {
//LOGGER.error("Error in constructing examples. Failed to look up the model " + codegenParameter.dataType);
return "TODO";
}
}
}
private String constructExampleCode(CodegenProperty codegenProperty, HashMap<String, CodegenModel> modelMaps, HashMap<String, Integer> processedModelMap) {
if (codegenProperty.isListContainer) { // array
return codegenProperty.dataType + "{" + constructExampleCode(codegenProperty.items, modelMaps, processedModelMap) + ")";
} else if (codegenProperty.isMapContainer) { // map
return "map[string]string{ \"Key\" = \"Value\" }";
} else if (codegenProperty.isPrimitiveType) { // primitive type
if (codegenProperty.isString) {
if (StringUtils.isEmpty(codegenProperty.example)) {
return "\"" + codegenProperty.example + "\"";
} else {
return "\"" + codegenProperty.name + "_example\"";
}
} else if (codegenProperty.isBoolean) { // boolean
if (Boolean.parseBoolean(codegenProperty.example)) {
return "true";
} else {
return "false";
}
} else if (codegenProperty.isUri) { // URL
return "\"https://example.com\")!";
} else if (codegenProperty.isDateTime || codegenProperty.isDate) { // datetime or date
return "time.Now()";
} else { // numeric
String example;
if (StringUtils.isEmpty(codegenProperty.example)) {
example = codegenProperty.example;
} else {
example = "123";
}
if (codegenProperty.isLong) {
return "int64(" + example + ")";
} else {
return example;
}
}
} else {
// look up the model
if (modelMaps.containsKey(codegenProperty.dataType)) {
return constructExampleCode(modelMaps.get(codegenProperty.dataType), modelMaps, processedModelMap);
} else {
//LOGGER.error("Error in constructing examples. Failed to look up the model " + codegenProperty.dataType);
return "\"TODO\"";
}
}
}
private String constructExampleCode(CodegenModel codegenModel, HashMap<String, CodegenModel> modelMaps, HashMap<String, Integer> processedModelMap) {
String example;
// break infinite recursion. Return, in case a model is already processed in the current context.
String model = codegenModel.name;
if (processedModelMap.containsKey(model)) {
int count = processedModelMap.get(model);
if (count == 1) {
processedModelMap.put(model, 2);
} else if (count == 2) {
return "";
} else {
throw new RuntimeException("Invalid count when constructing example: " + count);
}
} else {
processedModelMap.put(model, 1);
}
example = "" + goImportAlias + "." + codegenModel.name + "{";
List<String> propertyExamples = new ArrayList<>();
for (CodegenProperty codegenProperty : codegenModel.allVars) {
propertyExamples.add(codegenProperty.name + ": " + constructExampleCode(codegenProperty, modelMaps, processedModelMap));
}
example += StringUtils.join(propertyExamples, ", ");
example += "}";
return example;
}
}

View File

@ -0,0 +1,255 @@
/*
* Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
* Copyright 2018 SmartBear Software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openapitools.codegen.languages;
import org.openapitools.codegen.CliOption;
import org.openapitools.codegen.CodegenConstants;
import org.openapitools.codegen.CodegenType;
import org.openapitools.codegen.SupportingFile;
import org.openapitools.codegen.meta.features.*;
import org.openapitools.codegen.meta.GeneratorMetadata;
import org.openapitools.codegen.meta.Stability;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.EnumSet;
public class GoDeprecatedClientCodegen extends AbstractGoCodegen {
private static final Logger LOGGER = LoggerFactory.getLogger(GoDeprecatedClientCodegen.class);
protected String packageVersion = "1.0.0";
protected String apiDocPath = "docs/";
protected String modelDocPath = "docs/";
protected boolean isGoSubmodule = false;
public static final String WITH_GO_CODEGEN_COMMENT = "withGoCodegenComment";
public static final String WITH_XML = "withXml";
public static final String STRUCT_PREFIX = "structPrefix";
public static final String WITH_AWSV4_SIGNATURE = "withAWSV4Signature";
public static final String GENERATE_INTERFACES = "generateInterfaces";
public GoDeprecatedClientCodegen() {
super();
generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata).stability(Stability.DEPRECATED).build();
modifyFeatureSet(features -> features
.includeDocumentationFeatures(DocumentationFeature.Readme)
.wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML))
.securityFeatures(EnumSet.of(
SecurityFeature.BasicAuth,
SecurityFeature.ApiKey,
SecurityFeature.OAuth2_Implicit
))
.includeGlobalFeatures(
GlobalFeature.ParameterizedServer
)
.excludeGlobalFeatures(
GlobalFeature.XMLStructureDefinitions,
GlobalFeature.Callbacks,
GlobalFeature.LinkObjects,
GlobalFeature.ParameterStyling
)
.excludeSchemaSupportFeatures(
SchemaSupportFeature.Polymorphism
)
.includeParameterFeatures(
ParameterFeature.Cookie
)
.includeClientModificationFeatures(
ClientModificationFeature.BasePath,
ClientModificationFeature.UserAgent
)
);
outputFolder = "generated-code/go-deprecated";
modelTemplateFiles.put("model.mustache", ".go");
apiTemplateFiles.put("api.mustache", ".go");
modelDocTemplateFiles.put("model_doc.mustache", ".md");
apiDocTemplateFiles.put("api_doc.mustache", ".md");
embeddedTemplateDir = templateDir = "go-deprecated";
// default HIDE_GENERATION_TIMESTAMP to true
hideGenerationTimestamp = Boolean.TRUE;
cliOptions.add(CliOption.newBoolean(CodegenConstants.IS_GO_SUBMODULE, CodegenConstants.IS_GO_SUBMODULE_DESC));
cliOptions.add(CliOption.newBoolean(WITH_GO_CODEGEN_COMMENT, "whether to include Go codegen comment to disable Go Lint and collapse by default in GitHub PRs and diffs"));
cliOptions.add(CliOption.newBoolean(WITH_XML, "whether to include support for application/xml content type and include XML annotations in the model (works with libraries that provide support for JSON and XML)"));
cliOptions.add(CliOption.newBoolean(CodegenConstants.ENUM_CLASS_PREFIX, CodegenConstants.ENUM_CLASS_PREFIX_DESC));
cliOptions.add(CliOption.newBoolean(STRUCT_PREFIX, "whether to prefix struct with the class name. e.g. DeletePetOpts => PetApiDeletePetOpts"));
cliOptions.add(CliOption.newBoolean(WITH_AWSV4_SIGNATURE, "whether to include AWS v4 signature support"));
cliOptions.add(CliOption.newBoolean(GENERATE_INTERFACES, "Generate interfaces for api classes"));
// option to change the order of form/body parameter
cliOptions.add(CliOption.newBoolean(
CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS,
CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS_DESC)
.defaultValue(Boolean.FALSE.toString()));
}
@Override
public void processOpts() {
super.processOpts();
if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) {
setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME));
} else {
setPackageName("openapi");
}
if (additionalProperties.containsKey(CodegenConstants.PACKAGE_VERSION)) {
setPackageVersion((String) additionalProperties.get(CodegenConstants.PACKAGE_VERSION));
} else {
setPackageVersion("1.0.0");
}
additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName);
additionalProperties.put(CodegenConstants.PACKAGE_VERSION, packageVersion);
additionalProperties.put("apiDocPath", apiDocPath);
additionalProperties.put("modelDocPath", modelDocPath);
modelPackage = packageName;
apiPackage = packageName;
supportingFiles.add(new SupportingFile("openapi.mustache", "api", "openapi.yaml"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
supportingFiles.add(new SupportingFile("configuration.mustache", "", "configuration.go"));
supportingFiles.add(new SupportingFile("client.mustache", "", "client.go"));
supportingFiles.add(new SupportingFile("response.mustache", "", "response.go"));
supportingFiles.add(new SupportingFile("go.mod.mustache", "", "go.mod"));
supportingFiles.add(new SupportingFile("go.sum", "", "go.sum"));
supportingFiles.add(new SupportingFile(".travis.yml", "", ".travis.yml"));
if (additionalProperties.containsKey(WITH_GO_CODEGEN_COMMENT)) {
setWithGoCodegenComment(Boolean.parseBoolean(additionalProperties.get(WITH_GO_CODEGEN_COMMENT).toString()));
additionalProperties.put(WITH_GO_CODEGEN_COMMENT, withGoCodegenComment);
}
if (additionalProperties.containsKey(WITH_AWSV4_SIGNATURE)) {
setWithAWSV4Signature(Boolean.parseBoolean(additionalProperties.get(WITH_AWSV4_SIGNATURE).toString()));
additionalProperties.put(WITH_AWSV4_SIGNATURE, withAWSV4Signature);
}
if (additionalProperties.containsKey(WITH_XML)) {
setWithXml(Boolean.parseBoolean(additionalProperties.get(WITH_XML).toString()));
additionalProperties.put(WITH_XML, withXml);
}
if (additionalProperties.containsKey(CodegenConstants.ENUM_CLASS_PREFIX)) {
setEnumClassPrefix(Boolean.parseBoolean(additionalProperties.get(CodegenConstants.ENUM_CLASS_PREFIX).toString()));
additionalProperties.put(CodegenConstants.ENUM_CLASS_PREFIX, enumClassPrefix);
}
if (additionalProperties.containsKey(CodegenConstants.IS_GO_SUBMODULE)) {
setIsGoSubmodule(Boolean.parseBoolean(additionalProperties.get(CodegenConstants.IS_GO_SUBMODULE).toString()));
additionalProperties.put(CodegenConstants.IS_GO_SUBMODULE, isGoSubmodule);
}
if (additionalProperties.containsKey(STRUCT_PREFIX)) {
setStructPrefix(Boolean.parseBoolean(additionalProperties.get(STRUCT_PREFIX).toString()));
additionalProperties.put(STRUCT_PREFIX, structPrefix);
}
if (additionalProperties.containsKey(GENERATE_INTERFACES)) {
setGenerateInterfaces(Boolean.parseBoolean(additionalProperties.get(GENERATE_INTERFACES).toString()));
additionalProperties.put(GENERATE_INTERFACES, generateInterfaces);
}
}
/**
* Configures the type of generator.
*
* @return the CodegenType for this generator
* @see org.openapitools.codegen.CodegenType
*/
@Override
public CodegenType getTag() {
return CodegenType.CLIENT;
}
/**
* Configures a friendly name for the generator. This will be used by the generator
* to select the library with the -g flag.
*
* @return the friendly name for the generator
*/
@Override
public String getName() {
return "go-deprecated";
}
/**
* Returns human-friendly help for the generator. Provide the consumer with help
* tips, parameters here
*
* @return A string value for the help message
*/
@Override
public String getHelp() {
return "Generates a Go client library (beta). NOTE: this generator has been deprecated. Please use `go` client generator instead.";
}
/**
* Location to write api files. You can use the apiPackage() as defined when the class is
* instantiated
*/
@Override
public String apiFileFolder() {
return outputFolder + File.separator;
}
@Override
public String modelFileFolder() {
return outputFolder + File.separator;
}
@Override
public String apiDocFileFolder() {
return (outputFolder + "/" + apiDocPath).replace('/', File.separatorChar);
}
@Override
public String modelDocFileFolder() {
return (outputFolder + "/" + modelDocPath).replace('/', File.separatorChar);
}
@Override
public String toModelDocFilename(String name) {
return toModelName(name);
}
@Override
public String toApiDocFilename(String name) {
return toApiName(name);
}
public void setPackageVersion(String packageVersion) {
this.packageVersion = packageVersion;
}
public void setIsGoSubmodule(boolean isGoSubmodule) {
this.isGoSubmodule = isGoSubmodule;
}
}

View File

@ -34,7 +34,7 @@ org.openapitools.codegen.languages.FlashClientCodegen
org.openapitools.codegen.languages.FsharpFunctionsServerCodegen
org.openapitools.codegen.languages.FsharpGiraffeServerCodegen
org.openapitools.codegen.languages.GoClientCodegen
org.openapitools.codegen.languages.GoClientExperimentalCodegen
org.openapitools.codegen.languages.GoDeprecatedClientCodegen
org.openapitools.codegen.languages.GoServerCodegen
org.openapitools.codegen.languages.GoGinServerCodegen
org.openapitools.codegen.languages.GraphQLSchemaCodegen

View File

@ -0,0 +1,148 @@
# Go API client for {{packageName}}
{{#appDescriptionWithNewLines}}
{{{appDescriptionWithNewLines}}}
{{/appDescriptionWithNewLines}}
## Overview
This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [OpenAPI-spec](https://www.openapis.org/) from a remote server, you can easily generate an API client.
- API version: {{appVersion}}
- Package version: {{packageVersion}}
{{^hideGenerationTimestamp}}
- Build date: {{generatedDate}}
{{/hideGenerationTimestamp}}
- Build package: {{generatorClass}}
{{#infoUrl}}
For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}})
{{/infoUrl}}
## Installation
Install the following dependencies:
```shell
go get github.com/stretchr/testify/assert
go get golang.org/x/oauth2
{{#withAWSV4Signature}}
go get github.com/aws/aws-sdk-go/aws
{{/withAWSV4Signature}}
go get golang.org/x/net/context
go get github.com/antihax/optional
```
Put the package under your project folder and add the following in import:
```golang
import "./{{packageName}}"
```
## Documentation for API Endpoints
All URIs are relative to *{{basePath}}*
Class | Method | HTTP request | Description
------------ | ------------- | ------------- | -------------
{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}}
{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}
## Documentation For Models
{{#models}}{{#model}} - [{{{classname}}}]({{modelDocPath}}{{{classname}}}.md)
{{/model}}{{/models}}
## Documentation For Authorization
{{^authMethods}} Endpoints do not require authorization.
{{/authMethods}}{{#authMethods}}{{#last}} Authentication schemes defined for the API:{{/last}}{{/authMethods}}
{{#authMethods}}
## {{{name}}}
{{#isApiKey}}- **Type**: API key
Example
```golang
auth := context.WithValue(context.Background(), {{packageName}}.ContextAPIKey, {{packageName}}.APIKey{
Key: "APIKEY",
Prefix: "Bearer", // Omit if not necessary.
})
r, err := client.Service.Operation(auth, args)
```
{{/isApiKey}}
{{#isHttpSignature}}
Not supported.
{{/isHttpSignature}}
{{#isBasicBasic}}- **Type**: HTTP basic authentication
Example
```golang
auth := context.WithValue(context.Background(), {{packageName}}.ContextBasicAuth, {{packageName}}.BasicAuth{
UserName: "username",
Password: "password",
})
r, err := client.Service.Operation(auth, args)
```
{{/isBasicBasic}}
{{#isBasicBearer}}- **Type**: HTTP Bearer token authentication
Example
```golang
auth := context.WithValue(context.Background(), {{packageName}}.ContextAccessToken, "BEARERTOKENSTRING")
r, err := client.Service.Operation(auth, args)
```
{{/isBasicBearer}}
{{#isOAuth}}
- **Type**: OAuth
- **Flow**: {{{flow}}}
- **Authorization URL**: {{{authorizationUrl}}}
- **Scopes**: {{^scopes}}N/A{{/scopes}}
{{#scopes}} - **{{{scope}}}**: {{{description}}}
{{/scopes}}
Example
```golang
auth := context.WithValue(context.Background(), {{packageName}}.ContextAccessToken, "ACCESSTOKENSTRING")
r, err := client.Service.Operation(auth, args)
```
Or via OAuth2 module to automatically refresh tokens and perform user authentication.
```golang
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, {{packageName}}.ContextOAuth2, tokenSource)
r, err := client.Service.Operation(auth, args)
```
{{/isOAuth}}
{{/authMethods}}
{{#withAWSV4Signature}}
Example
```golang
auth := context.WithValue(context.Background(), {{packageName}}.ContextAWSv4, {{packageName}}.AWSv4{
AccessKey: "ACCESSKEYSTRING",
SecretKey: "SECRETKEYSTRING",
})
r, err := client.Service.Operation(auth, args)
```
{{/withAWSV4Signature}}
## Author
{{#apiInfo}}{{#apis}}{{^hasMore}}{{infoEmail}}
{{/hasMore}}{{/apis}}{{/apiInfo}}

View File

@ -0,0 +1,400 @@
{{>partial_header}}
package {{packageName}}
{{#operations}}
import (
_context "context"
_ioutil "io/ioutil"
_nethttp "net/http"
_neturl "net/url"
_bytes "bytes"
{{#imports}} "{{import}}"
{{/imports}}
)
// Linger please
var (
_ _context.Context
)
{{#generateInterfaces}}
type {{classname}} interface {
{{#operation}}
/*
* {{operationId}}{{#summary}} {{{.}}}{{/summary}}{{^summary}} Method for {{operationId}}{{/summary}}
*
{{#notes}}
* {{notes}}
*
{{/notes}}
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
{{#allParams}}
{{#required}}
* @param {{paramName}}{{#description}} {{{.}}}{{/description}}
{{/required}}
{{/allParams}}
{{#hasOptionalParams}}
* @param optional nil or *{{#structPrefix}}{{&classname}}{{/structPrefix}}{{{nickname}}}Opts - Optional Parameters:
{{#allParams}}
{{^required}}
* @param "{{vendorExtensions.x-export-param-name}}" ({{#isPrimitiveType}}{{^isBinary}}optional.{{vendorExtensions.x-optional-data-type}}{{/isBinary}}{{#isBinary}}optional.Interface of {{dataType}}{{/isBinary}}{{/isPrimitiveType}}{{^isPrimitiveType}}optional.Interface of {{dataType}}{{/isPrimitiveType}}) - {{#description}} {{{.}}}{{/description}}
{{/required}}
{{/allParams}}
{{/hasOptionalParams}}
{{#returnType}}
* @return {{{returnType}}}
{{/returnType}}
*/
{{{nickname}}}(ctx _context.Context{{#hasParams}}, {{/hasParams}}{{#allParams}}{{#required}}{{paramName}} {{{dataType}}}{{#hasMore}}, {{/hasMore}}{{/required}}{{/allParams}}{{#hasOptionalParams}}localVarOptionals *{{#structPrefix}}{{&classname}}{{/structPrefix}}{{{nickname}}}Opts{{/hasOptionalParams}}) ({{#returnType}}{{{returnType}}}, {{/returnType}}*_nethttp.Response, error)
{{/operation}}
}
{{/generateInterfaces}}
// {{classname}}Service {{classname}} service
type {{classname}}Service service
{{#operation}}
{{#hasOptionalParams}}
// {{#structPrefix}}{{&classname}}{{/structPrefix}}{{{nickname}}}Opts Optional parameters for the method '{{{nickname}}}'
type {{#structPrefix}}{{&classname}}{{/structPrefix}}{{{nickname}}}Opts struct {
{{#allParams}}
{{^required}}
{{#isPrimitiveType}}
{{^isBinary}}
{{vendorExtensions.x-export-param-name}} optional.{{vendorExtensions.x-optional-data-type}}
{{/isBinary}}
{{#isBinary}}
{{vendorExtensions.x-export-param-name}} optional.Interface
{{/isBinary}}
{{/isPrimitiveType}}
{{^isPrimitiveType}}
{{vendorExtensions.x-export-param-name}} optional.Interface
{{/isPrimitiveType}}
{{/required}}
{{/allParams}}
}
{{/hasOptionalParams}}
/*
* {{operationId}}{{#summary}} {{{.}}}{{/summary}}{{^summary}} Method for {{operationId}}{{/summary}}
*
{{#notes}}
* {{notes}}
*
{{/notes}}
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
{{#allParams}}
{{#required}}
* @param {{paramName}}{{#description}} {{{.}}}{{/description}}
{{/required}}
{{/allParams}}
{{#hasOptionalParams}}
* @param optional nil or *{{#structPrefix}}{{&classname}}{{/structPrefix}}{{{nickname}}}Opts - Optional Parameters:
{{#allParams}}
{{^required}}
* @param "{{vendorExtensions.x-export-param-name}}" ({{#isPrimitiveType}}{{^isBinary}}optional.{{vendorExtensions.x-optional-data-type}}{{/isBinary}}{{#isBinary}}optional.Interface of {{dataType}}{{/isBinary}}{{/isPrimitiveType}}{{^isPrimitiveType}}optional.Interface of {{dataType}}{{/isPrimitiveType}}) - {{#description}} {{{.}}}{{/description}}
{{/required}}
{{/allParams}}
{{/hasOptionalParams}}
{{#returnType}}
* @return {{{returnType}}}
{{/returnType}}
*/
func (a *{{{classname}}}Service) {{{nickname}}}(ctx _context.Context{{#hasParams}}, {{/hasParams}}{{#allParams}}{{#required}}{{paramName}} {{{dataType}}}{{#hasMore}}, {{/hasMore}}{{/required}}{{/allParams}}{{#hasOptionalParams}}localVarOptionals *{{#structPrefix}}{{&classname}}{{/structPrefix}}{{{nickname}}}Opts{{/hasOptionalParams}}) ({{#returnType}}{{{returnType}}}, {{/returnType}}*_nethttp.Response, error) {
var (
localVarHTTPMethod = _nethttp.Method{{httpMethod}}
localVarPostBody interface{}
localVarFormFileName string
localVarFileName string
localVarFileBytes []byte
{{#returnType}}
localVarReturnValue {{{returnType}}}
{{/returnType}}
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "{{{path}}}"{{#pathParams}}
localVarPath = strings.Replace(localVarPath, "{"+"{{baseName}}"+"}", _neturl.PathEscape(parameterToString({{paramName}}, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}")) , -1)
{{/pathParams}}
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
{{#allParams}}
{{#required}}
{{#minItems}}
if len({{paramName}}) < {{minItems}} {
return {{#returnType}}localVarReturnValue, {{/returnType}}nil, reportError("{{paramName}} must have at least {{minItems}} elements")
}
{{/minItems}}
{{#maxItems}}
if len({{paramName}}) > {{maxItems}} {
return {{#returnType}}localVarReturnValue, {{/returnType}}nil, reportError("{{paramName}} must have less than {{maxItems}} elements")
}
{{/maxItems}}
{{#minLength}}
if strlen({{paramName}}) < {{minLength}} {
return {{#returnType}}localVarReturnValue, {{/returnType}}nil, reportError("{{paramName}} must have at least {{minLength}} elements")
}
{{/minLength}}
{{#maxLength}}
if strlen({{paramName}}) > {{maxLength}} {
return {{#returnType}}localVarReturnValue, {{/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}}localVarReturnValue, {{/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}}localVarReturnValue, {{/returnType}}nil, reportError("{{paramName}} must be less than {{maximum}}")
}
{{/maximum}}
{{/required}}
{{/allParams}}
{{#hasQueryParams}}
{{#queryParams}}
{{#required}}
{{#isCollectionFormatMulti}}
{
t:={{paramName}}
if reflect.TypeOf(t).Kind() == reflect.Slice {
s := reflect.ValueOf(t)
for i := 0; i < s.Len(); i++ {
localVarQueryParams.Add("{{baseName}}", parameterToString(s.Index(i), "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}"))
}
} else {
localVarQueryParams.Add("{{baseName}}", parameterToString(t, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}"))
}
}
{{/isCollectionFormatMulti}}
{{^isCollectionFormatMulti}}
localVarQueryParams.Add("{{baseName}}", parameterToString({{paramName}}, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}"))
{{/isCollectionFormatMulti}}
{{/required}}
{{^required}}
if localVarOptionals != nil && localVarOptionals.{{vendorExtensions.x-export-param-name}}.IsSet() {
{{#isCollectionFormatMulti}}
t:=localVarOptionals.{{vendorExtensions.x-export-param-name}}.Value()
if reflect.TypeOf(t).Kind() == reflect.Slice {
s := reflect.ValueOf(t)
for i := 0; i < s.Len(); i++ {
localVarQueryParams.Add("{{baseName}}", parameterToString(s.Index(i), "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}"))
}
} else {
localVarQueryParams.Add("{{baseName}}", parameterToString(t, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}"))
}
{{/isCollectionFormatMulti}}
{{^isCollectionFormatMulti}}
localVarQueryParams.Add("{{baseName}}", parameterToString(localVarOptionals.{{vendorExtensions.x-export-param-name}}.Value(), "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}"))
{{/isCollectionFormatMulti}}
}
{{/required}}
{{/queryParams}}
{{/hasQueryParams}}
// to determine the Content-Type header
{{=<% %>=}}
localVarHTTPContentTypes := []string{<%#consumes%>"<%&mediaType%>"<%^-last%>, <%/-last%><%/consumes%>}
<%={{ }}=%>
// set Content-Type header
localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)
if localVarHTTPContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHTTPContentType
}
// to determine the Accept header
{{=<% %>=}}
localVarHTTPHeaderAccepts := []string{<%#produces%>"<%&mediaType%>"<%^-last%>, <%/-last%><%/produces%>}
<%={{ }}=%>
// set Accept header
localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)
if localVarHTTPHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept
}
{{#hasHeaderParams}}
{{#headerParams}}
{{#required}}
localVarHeaderParams["{{baseName}}"] = parameterToString({{paramName}}, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}")
{{/required}}
{{^required}}
if localVarOptionals != nil && localVarOptionals.{{vendorExtensions.x-export-param-name}}.IsSet() {
localVarHeaderParams["{{baseName}}"] = parameterToString(localVarOptionals.{{vendorExtensions.x-export-param-name}}.Value(), "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}")
}
{{/required}}
{{/headerParams}}
{{/hasHeaderParams}}
{{#hasFormParams}}
{{#formParams}}
{{#isFile}}
localVarFormFileName = "{{baseName}}"
{{#required}}
localVarFile := {{paramName}}
{{/required}}
{{^required}}
var localVarFile {{dataType}}
if localVarOptionals != nil && localVarOptionals.{{vendorExtensions.x-export-param-name}}.IsSet() {
localVarFileOk := false
localVarFile, localVarFileOk = localVarOptionals.{{vendorExtensions.x-export-param-name}}.Value().({{dataType}})
if !localVarFileOk {
return {{#returnType}}localVarReturnValue, {{/returnType}}nil, reportError("{{paramName}} should be {{dataType}}")
}
}
{{/required}}
if localVarFile != nil {
fbs, _ := _ioutil.ReadAll(localVarFile)
localVarFileBytes = fbs
localVarFileName = localVarFile.Name()
localVarFile.Close()
}
{{/isFile}}
{{^isFile}}
{{#required}}
localVarFormParams.Add("{{baseName}}", parameterToString({{paramName}}, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}"))
{{/required}}
{{^required}}
{{#isModel}}
if localVarOptionals != nil && localVarOptionals.{{vendorExtensions.x-export-param-name}}.IsSet() {
paramJson, err := parameterToJson(localVarOptionals.{{vendorExtensions.x-export-param-name}}.Value())
if err != nil {
return {{#returnType}}localVarReturnValue, {{/returnType}}nil, err
}
localVarFormParams.Add("{{baseName}}", paramJson)
}
{{/isModel}}
{{^isModel}}
if localVarOptionals != nil && localVarOptionals.{{vendorExtensions.x-export-param-name}}.IsSet() {
localVarFormParams.Add("{{baseName}}", parameterToString(localVarOptionals.{{vendorExtensions.x-export-param-name}}.Value(), "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}"))
}
{{/isModel}}
{{/required}}
{{/isFile}}
{{/formParams}}
{{/hasFormParams}}
{{#hasBodyParam}}
{{#bodyParams}}
// body params
{{#required}}
localVarPostBody = &{{paramName}}
{{/required}}
{{^required}}
if localVarOptionals != nil && localVarOptionals.{{vendorExtensions.x-export-param-name}}.IsSet() {
{{#isPrimitiveType}}
localVarPostBody = localVarOptionals.{{vendorExtensions.x-export-param-name}}.Value()
{{/isPrimitiveType}}
{{^isPrimitiveType}}
localVarOptional{{vendorExtensions.x-export-param-name}}, localVarOptional{{vendorExtensions.x-export-param-name}}ok := localVarOptionals.{{vendorExtensions.x-export-param-name}}.Value().({{{dataType}}})
if !localVarOptional{{vendorExtensions.x-export-param-name}}ok {
return {{#returnType}}localVarReturnValue, {{/returnType}}nil, reportError("{{paramName}} should be {{dataType}}")
}
localVarPostBody = &localVarOptional{{vendorExtensions.x-export-param-name}}
{{/isPrimitiveType}}
}
{{/required}}
{{/bodyParams}}
{{/hasBodyParam}}
{{#authMethods}}
{{#isApiKey}}
{{^isKeyInCookie}}
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.Add("{{keyParamName}}", key)
{{/isKeyInQuery}}
}
}
{{/isKeyInCookie}}
{{/isApiKey}}
{{/authMethods}}
r, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)
if err != nil {
return {{#returnType}}localVarReturnValue, {{/returnType}}nil, err
}
localVarHTTPResponse, err := a.client.callAPI(r)
if err != nil || localVarHTTPResponse == nil {
return {{#returnType}}localVarReturnValue, {{/returnType}}localVarHTTPResponse, err
}
localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)
localVarHTTPResponse.Body.Close()
localVarHTTPResponse.Body = _ioutil.NopCloser(_bytes.NewBuffer(localVarBody))
if err != nil {
return {{#returnType}}localVarReturnValue, {{/returnType}}localVarHTTPResponse, err
}
if localVarHTTPResponse.StatusCode >= 300 {
newErr := GenericOpenAPIError{
body: localVarBody,
error: localVarHTTPResponse.Status,
}
{{#responses}}
{{#dataType}}
{{^is1xx}}
{{^is2xx}}
{{^wildcard}}
if localVarHTTPResponse.StatusCode == {{{code}}} {
{{/wildcard}}
var v {{{dataType}}}
err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr.error = err.Error()
return {{#returnType}}localVarReturnValue, {{/returnType}}localVarHTTPResponse, newErr
}
newErr.model = v
{{#hasMore}}
return {{#returnType}}localVarReturnValue, {{/returnType}}localVarHTTPResponse, newErr
{{/hasMore}}
{{^wildcard}}
}
{{/wildcard}}
{{/is2xx}}
{{/is1xx}}
{{/dataType}}
{{/responses}}
return {{#returnType}}localVarReturnValue, {{/returnType}}localVarHTTPResponse, newErr
}
{{#returnType}}
err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr := GenericOpenAPIError{
body: localVarBody,
error: err.Error(),
}
return {{#returnType}}localVarReturnValue, {{/returnType}}localVarHTTPResponse, newErr
}
{{/returnType}}
return {{#returnType}}localVarReturnValue, {{/returnType}}localVarHTTPResponse, nil
}
{{/operation}}
{{/operations}}

View File

@ -0,0 +1,59 @@
# {{invokerPackage}}\{{classname}}{{#description}}
{{description}}{{/description}}
All URIs are relative to *{{basePath}}*
Method | HTTP request | Description
------------- | ------------- | -------------
{{#operations}}{{#operation}}[**{{operationId}}**]({{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}}
{{/operation}}{{/operations}}
{{#operations}}
{{#operation}}
## {{{operationId}}}
> {{#returnType}}{{{returnType}}} {{/returnType}}{{{operationId}}}(ctx, {{#allParams}}{{#required}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/required}}{{/allParams}}{{#hasOptionalParams}}optional{{/hasOptionalParams}})
{{{summary}}}{{#notes}}
{{{notes}}}{{/notes}}
### Required Parameters
{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}}
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc.{{/-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** | ***{{{nickname}}}Opts** | optional parameters | nil if no parameters
### Optional Parameters
Optional parameters are passed through a pointer to a {{{nickname}}}Opts struct
{{#allParams}}{{#-last}}
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}}{{#allParams}}
{{^required}} **{{paramName}}** | {{#isFile}}**optional.Interface of {{dataType}}**{{/isFile}}{{#isPrimitiveType}}**optional.{{vendorExtensions.x-optional-data-type}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{^isFile}}[**optional.Interface of {{dataType}}**]({{baseType}}.md){{/isFile}}{{/isPrimitiveType}}| {{description}} | {{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}}{{/required}}{{/allParams}}{{/hasOptionalParams}}
### Return type
{{#returnType}}{{#returnTypeIsPrimitive}}**{{{returnType}}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{{returnType}}}**]({{returnBaseType}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}} (empty response body){{/returnType}}
### Authorization
{{^authMethods}}No authorization required{{/authMethods}}{{#authMethods}}[{{{name}}}](../README.md#{{{name}}}){{^-last}}, {{/-last}}{{/authMethods}}
### HTTP request headers
- **Content-Type**: {{#consumes}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}}
- **Accept**: {{#produces}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}}
[[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)
{{/operation}}
{{/operations}}

View File

@ -9,6 +9,7 @@ import (
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"mime/multipart"
"net/http"
@ -31,7 +32,7 @@ import (
)
var (
jsonCheck = regexp.MustCompile(`(?i:(?:application|text)/(?:vnd\.[^;]+\+)?json)`)
jsonCheck = regexp.MustCompile(`(?i:(?:application|text)/(?:vnd\.[^;]+\+)?(?:problem\+)?json)`)
xmlCheck = regexp.MustCompile(`(?i:(?:application|text)/xml)`)
)
@ -46,12 +47,12 @@ type APIClient struct {
{{#apis}}
{{#operations}}
{{#generateInterfaces}}
{{#generateInterfaces}}
{{classname}} {{classname}}
{{/generateInterfaces}}
{{^generateInterfaces}}
{{/generateInterfaces}}
{{^generateInterfaces}}
{{classname}} *{{classname}}Service
{{/generateInterfaces}}
{{/generateInterfaces}}
{{/operations}}
{{/apis}}
{{/apiInfo}}
@ -173,9 +174,9 @@ func parameterToJson(obj interface{}) (string, error) {
// callAPI do the request.
func (c *APIClient) callAPI(request *http.Request) (*http.Response, error) {
if c.cfg.Debug {
dump, err := httputil.DumpRequestOut(request, true)
dump, err := httputil.DumpRequestOut(request, true)
if err != nil {
return nil, err
return nil, err
}
log.Printf("\n%s\n", string(dump))
}
@ -192,9 +193,15 @@ func (c *APIClient) callAPI(request *http.Request) (*http.Response, error) {
}
log.Printf("\n%s\n", string(dump))
}
return resp, err
}
// ChangeBasePath changes base path to allow switching to mocks
func (c *APIClient) ChangeBasePath(path string) {
c.cfg.BasePath = path
}
// Allow modification of underlying config for alternate implementations and testing
// Caution: modifying the configuration while live can cause data races and potentially unwanted behavior
func (c *APIClient) GetConfig() *Configuration {
@ -379,18 +386,7 @@ func (c *APIClient) prepareRequest(
for header, value := range c.cfg.DefaultHeader {
localVarRequest.Header.Add(header, value)
}
{{#hasHttpSignatureMethods}}
if ctx != nil {
// HTTP Signature Authentication. All request headers must be set (including default headers)
// because the headers may be included in the signature.
if auth, ok := ctx.Value(ContextHttpSignatureAuth).(HttpSignatureAuth); ok {
err = SignRequest(ctx, localVarRequest, auth)
if err != nil {
return nil, err
}
}
}
{{/hasHttpSignatureMethods}}
return localVarRequest, nil
}
@ -402,6 +398,15 @@ func (c *APIClient) decode(v interface{}, b []byte, contentType string) (err err
*s = string(b)
return nil
}
if f, ok := v.(**os.File); ok {
*f, err = ioutil.TempFile("", "HttpClientFile")
if err != nil {
return
}
_, err = (*f).Write(b)
_, err = (*f).Seek(0, io.SeekStart)
return
}
if xmlCheck.MatchString(contentType) {
if err = xml.Unmarshal(b, v); err != nil {
return err
@ -409,15 +414,7 @@ func (c *APIClient) decode(v interface{}, b []byte, contentType string) (err err
return nil
}
if jsonCheck.MatchString(contentType) {
if actualObj, ok := v.(interface{GetActualInstance() interface{}}); ok { // oneOf, anyOf schemas
if unmarshalObj, ok := actualObj.(interface{UnmarshalJSON([]byte) error}); ok { // make sure it has UnmarshalJSON defined
if err = unmarshalObj.UnmarshalJSON(b); err!= nil {
return err
}
} else {
errors.New("Unknown type with GetActualInstance but no unmarshalObj.UnmarshalJSON defined")
}
} else if err = json.Unmarshal(b, v); err != nil { // simple model
if err = json.Unmarshal(b, v); err != nil {
return err
}
return nil

View File

@ -1,14 +1,5 @@
/*
* OpenAPI Petstore
*
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*
* API version: 1.0.0
*/
// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT.
package petstore
{{>partial_header}}
package {{packageName}}
import (
"fmt"
@ -39,6 +30,10 @@ var (
// ContextAPIKey takes an APIKey as authentication for the request
ContextAPIKey = contextKey("apikey")
{{#withAWSV4Signature}}
// ContextAWSv4 takes an Access Key and a Secret Key for signing AWS Signature v4.
ContextAWSv4 = contextKey("awsv4")
{{/withAWSV4Signature}}
)
// BasicAuth provides basic http authentication to a request passed via context using ContextBasicAuth
@ -53,6 +48,14 @@ type APIKey struct {
Prefix string
}
{{#withAWSV4Signature}}
// AWSv4 provides AWS Signature to a request passed via context using ContextAWSv4
// https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html
type AWSv4 struct {
AccessKey string
SecretKey string
}
{{/withAWSV4Signature}}
// ServerVariable stores the information about a server variable
type ServerVariable struct {
@ -83,16 +86,43 @@ type Configuration struct {
// NewConfiguration returns a new Configuration object
func NewConfiguration() *Configuration {
cfg := &Configuration{
BasePath: "http://petstore.swagger.io:80/v2",
BasePath: "{{{basePath}}}",
DefaultHeader: make(map[string]string),
UserAgent: "OpenAPI-Generator/1.0.0/go",
UserAgent: "{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}OpenAPI-Generator/{{{packageVersion}}}/go{{/httpUserAgent}}",
Debug: false,
{{#servers}}
{{#-first}}
Servers: []ServerConfiguration{
{{/-first}}
{
Url: "http://petstore.swagger.io:80/v2",
Description: "No description provided",
Url: "{{{url}}}",
Description: "{{{description}}}{{^description}}No description provided{{/description}}",
{{#variables}}
{{#-first}}
Variables: map[string]ServerVariable{
{{/-first}}
"{{{name}}}": ServerVariable{
Description: "{{{description}}}{{^description}}No description provided{{/description}}",
DefaultValue: "{{{defaultValue}}}",
{{#enumValues}}
{{#-first}}
EnumValues: []string{
{{/-first}}
"{{{.}}}",
{{#-last}}
},
{{/-last}}
{{/enumValues}}
},
{{#-last}}
},
{{/-last}}
{{/variables}}
},
{{#-last}}
},
{{/-last}}
{{/servers}}
}
return cfg
}

View File

@ -1,8 +1,7 @@
module {{gitHost}}/{{gitUserId}}/{{gitRepoId}}{{#isGoSubmodule}}/{{packageName}}{{/isGoSubmodule}}
go 1.13
require (
github.com/antihax/optional v1.0.0
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45
{{#withAWSV4Signature}}
github.com/aws/aws-sdk-go v1.34.14

View File

@ -0,0 +1,43 @@
{{>partial_header}}
package {{packageName}}
{{#models}}
{{#imports}}
{{#-first}}
import (
{{/-first}}
"{{import}}"
{{#-last}}
)
{{/-last}}
{{/imports}}
{{#model}}
{{#isEnum}}
// {{{classname}}} {{#description}}{{{.}}}{{/description}}{{^description}}the model '{{{classname}}}'{{/description}}
type {{{classname}}} {{^format}}{{dataType}}{{/format}}{{#format}}{{{format}}}{{/format}}
// List of {{{name}}}
const (
{{#allowableValues}}
{{#enumVars}}
{{^-first}}
{{/-first}}
{{#enumClassPrefix}}{{{classname.toUpperCase}}}_{{/enumClassPrefix}}{{name}} {{{classname}}} = {{{value}}}
{{/enumVars}}
{{/allowableValues}}
)
{{/isEnum}}
{{^isEnum}}
// {{classname}}{{#description}} {{{description}}}{{/description}}{{^description}} struct for {{{classname}}}{{/description}}
type {{classname}} struct {
{{#allVars}}
{{^-first}}
{{/-first}}
{{#description}}
// {{{description}}}
{{/description}}
{{name}} {{#isNullable}}*{{/isNullable}}{{{dataType}}} `json:"{{baseName}}{{^required}},omitempty{{/required}}"{{#withXml}} xml:"{{baseName}}{{#isXmlAttribute}},attr{{/isXmlAttribute}}"{{/withXml}}{{#vendorExtensions.x-go-custom-tag}} {{{.}}}{{/vendorExtensions.x-go-custom-tag}}`
{{/allVars}}
}
{{/isEnum}}
{{/model}}
{{/models}}

View File

@ -0,0 +1,12 @@
{{#models}}{{#model}}# {{classname}}
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
{{#allVars}}**{{name}}** | {{#isNullable}}Pointer to {{/isNullable}}{{#isPrimitiveType}}**{{{dataType}}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{{dataType}}}**]({{complexType}}.md){{/isPrimitiveType}} | {{description}} | {{^required}}[optional] {{/required}}{{#isReadOnly}}[readonly] {{/isReadOnly}}{{#defaultValue}}[default to {{{.}}}]{{/defaultValue}}
{{/allVars}}
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
{{/model}}{{/models}}

View File

@ -1,215 +0,0 @@
# Go API client for {{packageName}}
{{#appDescriptionWithNewLines}}
{{{appDescriptionWithNewLines}}}
{{/appDescriptionWithNewLines}}
## Overview
This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [OpenAPI-spec](https://www.openapis.org/) from a remote server, you can easily generate an API client.
- API version: {{appVersion}}
- Package version: {{packageVersion}}
{{^hideGenerationTimestamp}}
- Build date: {{generatedDate}}
{{/hideGenerationTimestamp}}
- Build package: {{generatorClass}}
{{#infoUrl}}
For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}})
{{/infoUrl}}
## Installation
Install the following dependencies:
```shell
go get github.com/stretchr/testify/assert
go get golang.org/x/oauth2
go get golang.org/x/net/context
```
Put the package under your project folder and add the following in import:
```golang
import sw "./{{packageName}}"
```
## Configuration of Server URL
Default configuration comes with `Servers` field that contains server objects as defined in the OpenAPI specification.
### Select Server Configuration
For using other server than the one defined on index 0 set context value `sw.ContextServerIndex` of type `int`.
```golang
ctx := context.WithValue(context.Background(), sw.ContextServerIndex, 1)
```
### Templated Server URL
Templated server URL is formatted using default variables from configuration or from context value `sw.ContextServerVariables` of type `map[string]string`.
```golang
ctx := context.WithValue(context.Background(), sw.ContextServerVariables, map[string]string{
"basePath": "v2",
})
```
Note, enum values are always validated and all unused variables are silently ignored.
### URLs Configuration per Operation
Each operation can use different server URL defined using `OperationServers` map in the `Configuration`.
An operation is uniquely identifield by `"{classname}Service.{nickname}"` string.
Similar rules for overriding default operation server index and variables applies by using `sw.ContextOperationServerIndices` and `sw.ContextOperationServerVariables` context maps.
```
ctx := context.WithValue(context.Background(), sw.ContextOperationServerIndices, map[string]int{
"{classname}Service.{nickname}": 2,
})
ctx = context.WithValue(context.Background(), sw.ContextOperationServerVariables, map[string]map[string]string{
"{classname}Service.{nickname}": {
"port": "8443",
},
})
```
## Documentation for API Endpoints
All URIs are relative to *{{basePath}}*
Class | Method | HTTP request | Description
------------ | ------------- | ------------- | -------------
{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}}
{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}
## Documentation For Models
{{#models}}{{#model}} - [{{{classname}}}]({{modelDocPath}}{{{classname}}}.md)
{{/model}}{{/models}}
## Documentation For Authorization
{{^authMethods}} Endpoints do not require authorization.
{{/authMethods}}{{#authMethods}}{{#last}} Authentication schemes defined for the API:{{/last}}{{/authMethods}}
{{#authMethods}}
### {{{name}}}
{{#isApiKey}}
- **Type**: API key
- **API key parameter name**: {{{keyParamName}}}
- **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}}
Note, each API key must be added to a map of `map[string]APIKey` where the key is: {{keyParamName}} and passed in as the auth context for each request.
{{/isApiKey}}
{{#isBasic}}
{{#isBasicBearer}}
- **Type**: HTTP Bearer token authentication
Example
```golang
auth := context.WithValue(context.Background(), sw.ContextAccessToken, "BEARERTOKENSTRING")
r, err := client.Service.Operation(auth, args)
```
{{/isBasicBearer}}
{{#isBasicBasic}}
- **Type**: HTTP basic authentication
Example
```golang
auth := context.WithValue(context.Background(), sw.ContextBasicAuth, sw.BasicAuth{
UserName: "username",
Password: "password",
})
r, err := client.Service.Operation(auth, args)
```
{{/isBasicBasic}}
{{#isHttpSignature}}
- **Type**: HTTP signature authentication
Example
```golang
authConfig := sw.HttpSignatureAuth{
KeyId: "my-key-id",
PrivateKeyPath: "rsa.pem",
Passphrase: "my-passphrase",
SigningScheme: sw.HttpSigningSchemeHs2019,
SignedHeaders: []string{
sw.HttpSignatureParameterRequestTarget, // The special (request-target) parameter expresses the HTTP request target.
sw.HttpSignatureParameterCreated, // Time when request was signed, formatted as a Unix timestamp integer value.
"Host", // The Host request header specifies the domain name of the server, and optionally the TCP port number.
"Date", // The date and time at which the message was originated.
"Content-Type", // The Media type of the body of the request.
"Digest", // A cryptographic digest of the request body.
},
SigningAlgorithm: sw.HttpSigningAlgorithmRsaPSS,
SignatureMaxValidity: 5 * time.Minute,
}
var authCtx context.Context
var err error
if authCtx, err = authConfig.ContextWithValue(context.Background()); err != nil {
// Process error
}
r, err = client.Service.Operation(auth, args)
```
{{/isHttpSignature}}
{{/isBasic}}
{{#isOAuth}}
- **Type**: OAuth
- **Flow**: {{{flow}}}
- **Authorization URL**: {{{authorizationUrl}}}
- **Scopes**: {{^scopes}}N/A{{/scopes}}
{{#scopes}} - **{{{scope}}}**: {{{description}}}
{{/scopes}}
Example
```golang
auth := context.WithValue(context.Background(), sw.ContextAccessToken, "ACCESSTOKENSTRING")
r, err := client.Service.Operation(auth, args)
```
Or via OAuth2 module to automatically refresh tokens and perform user authentication.
```golang
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}}
## Documentation for Utility Methods
Due to the fact that model structure members are all pointers, this package contains
a number of utility functions to easily obtain pointers to values of basic types.
Each of these functions takes a value of the given basic type and returns a pointer to it:
* `PtrBool`
* `PtrInt`
* `PtrInt32`
* `PtrInt64`
* `PtrFloat`
* `PtrFloat32`
* `PtrFloat64`
* `PtrString`
* `PtrTime`
## Author
{{#apiInfo}}{{#apis}}{{^hasMore}}{{infoEmail}}
{{/hasMore}}{{/apis}}{{/apiInfo}}

View File

@ -1,375 +0,0 @@
{{>partial_header}}
package {{packageName}}
{{#operations}}
import (
_context "context"
_ioutil "io/ioutil"
_nethttp "net/http"
_neturl "net/url"
{{#imports}} "{{import}}"
{{/imports}}
)
// Linger please
var (
_ _context.Context
)
{{#generateInterfaces}}
type {{classname}} interface {
{{#operation}}
/*
* {{operationId}}{{#summary}} {{{.}}}{{/summary}}{{^summary}} Method for {{operationId}}{{/summary}}
{{#notes}}
* {{{unescapedNotes}}}
{{/notes}}
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().{{#pathParams}}
* @param {{paramName}}{{#description}} {{{.}}}{{/description}}{{/pathParams}}
* @return {{#structPrefix}}{{&classname}}{{/structPrefix}}Api{{operationId}}Request
*/
{{{nickname}}}(ctx _context.Context{{#pathParams}}, {{paramName}} {{{dataType}}}{{/pathParams}}) {{#structPrefix}}{{&classname}}{{/structPrefix}}Api{{operationId}}Request
/*
* {{nickname}}Execute executes the request{{#returnType}}
* @return {{{.}}}{{/returnType}}
*/
{{nickname}}Execute(r {{#structPrefix}}{{&classname}}{{/structPrefix}}Api{{operationId}}Request) ({{#returnType}}{{{.}}}, {{/returnType}}*_nethttp.Response, error)
{{/operation}}
}
{{/generateInterfaces}}
// {{classname}}Service {{classname}} service
type {{classname}}Service service
{{#operation}}
type {{#structPrefix}}{{&classname}}{{/structPrefix}}Api{{operationId}}Request struct {
ctx _context.Context{{#generateInterfaces}}
ApiService {{classname}}
{{/generateInterfaces}}{{^generateInterfaces}}
ApiService *{{classname}}Service
{{/generateInterfaces}}
{{#allParams}}
{{paramName}} {{^isPathParam}}*{{/isPathParam}}{{{dataType}}}
{{/allParams}}
}
{{#allParams}}{{^isPathParam}}
func (r {{#structPrefix}}{{&classname}}{{/structPrefix}}Api{{operationId}}Request) {{vendorExtensions.x-export-param-name}}({{paramName}} {{{dataType}}}) {{#structPrefix}}{{&classname}}{{/structPrefix}}Api{{operationId}}Request {
r.{{paramName}} = &{{paramName}}
return r
}{{/isPathParam}}{{/allParams}}
func (r {{#structPrefix}}{{&classname}}{{/structPrefix}}Api{{operationId}}Request) Execute() ({{#returnType}}{{{.}}}, {{/returnType}}*_nethttp.Response, error) {
return r.ApiService.{{nickname}}Execute(r)
}
/*
* {{operationId}}{{#summary}} {{{.}}}{{/summary}}{{^summary}} Method for {{operationId}}{{/summary}}
{{#notes}}
* {{{unescapedNotes}}}
{{/notes}}
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().{{#pathParams}}
* @param {{paramName}}{{#description}} {{{.}}}{{/description}}{{/pathParams}}
* @return {{#structPrefix}}{{&classname}}{{/structPrefix}}Api{{operationId}}Request
*/
func (a *{{{classname}}}Service) {{{nickname}}}(ctx _context.Context{{#pathParams}}, {{paramName}} {{{dataType}}}{{/pathParams}}) {{#structPrefix}}{{&classname}}{{/structPrefix}}Api{{operationId}}Request {
return {{#structPrefix}}{{&classname}}{{/structPrefix}}Api{{operationId}}Request{
ApiService: a,
ctx: ctx,{{#pathParams}}
{{paramName}}: {{paramName}},{{/pathParams}}
}
}
/*
* Execute executes the request{{#returnType}}
* @return {{{.}}}{{/returnType}}
*/
func (a *{{{classname}}}Service) {{nickname}}Execute(r {{#structPrefix}}{{&classname}}{{/structPrefix}}Api{{operationId}}Request) ({{#returnType}}{{{.}}}, {{/returnType}}*_nethttp.Response, error) {
var (
localVarHTTPMethod = _nethttp.Method{{httpMethod}}
localVarPostBody interface{}
localVarFormFileName string
localVarFileName string
localVarFileBytes []byte
{{#returnType}}
localVarReturnValue {{{.}}}
{{/returnType}}
)
localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "{{{classname}}}Service.{{{nickname}}}")
if err != nil {
return {{#returnType}}localVarReturnValue, {{/returnType}}nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "{{{path}}}"{{#pathParams}}
localVarPath = strings.Replace(localVarPath, "{"+"{{baseName}}"+"}", _neturl.PathEscape(parameterToString(r.{{paramName}}, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}")) , -1){{/pathParams}}
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
{{#allParams}}
{{#required}}
{{^isPathParam}}
if r.{{paramName}} == nil {
return {{#returnType}}localVarReturnValue, {{/returnType}}nil, reportError("{{paramName}} is required and must be specified")
}
{{/isPathParam}}
{{#minItems}}
if len({{^isPathParam}}*{{/isPathParam}}r.{{paramName}}) < {{minItems}} {
return {{#returnType}}localVarReturnValue, {{/returnType}}nil, reportError("{{paramName}} must have at least {{minItems}} elements")
}
{{/minItems}}
{{#maxItems}}
if len({{^isPathParam}}*{{/isPathParam}}r.{{paramName}}) > {{maxItems}} {
return {{#returnType}}localVarReturnValue, {{/returnType}}nil, reportError("{{paramName}} must have less than {{maxItems}} elements")
}
{{/maxItems}}
{{#minLength}}
if strlen({{^isPathParam}}*{{/isPathParam}}r.{{paramName}}) < {{minLength}} {
return {{#returnType}}localVarReturnValue, {{/returnType}}nil, reportError("{{paramName}} must have at least {{minLength}} elements")
}
{{/minLength}}
{{#maxLength}}
if strlen({{^isPathParam}}*{{/isPathParam}}r.{{paramName}}) > {{maxLength}} {
return {{#returnType}}localVarReturnValue, {{/returnType}}nil, reportError("{{paramName}} must have less than {{maxLength}} elements")
}
{{/maxLength}}
{{#minimum}}
{{#isString}}
{{paramName}}Txt, err := atoi({{^isPathParam}}*{{/isPathParam}}r.{{paramName}})
if {{paramName}}Txt < {{minimum}} {
{{/isString}}
{{^isString}}
if {{^isPathParam}}*{{/isPathParam}}r.{{paramName}} < {{minimum}} {
{{/isString}}
return {{#returnType}}localVarReturnValue, {{/returnType}}nil, reportError("{{paramName}} must be greater than {{minimum}}")
}
{{/minimum}}
{{#maximum}}
{{#isString}}
{{paramName}}Txt, err := atoi({{^isPathParam}}*{{/isPathParam}}r.{{paramName}})
if {{paramName}}Txt > {{maximum}} {
{{/isString}}
{{^isString}}
if {{^isPathParam}}*{{/isPathParam}}r.{{paramName}} > {{maximum}} {
{{/isString}}
return {{#returnType}}localVarReturnValue, {{/returnType}}nil, reportError("{{paramName}} must be less than {{maximum}}")
}
{{/maximum}}
{{/required}}
{{/allParams}}
{{#queryParams}}
{{#required}}
{{#isCollectionFormatMulti}}
{
t := *r.{{paramName}}
if reflect.TypeOf(t).Kind() == reflect.Slice {
s := reflect.ValueOf(t)
for i := 0; i < s.Len(); i++ {
localVarQueryParams.Add("{{baseName}}", parameterToString(s.Index(i), "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}"))
}
} else {
localVarQueryParams.Add("{{baseName}}", parameterToString(t, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}"))
}
}
{{/isCollectionFormatMulti}}
{{^isCollectionFormatMulti}}
localVarQueryParams.Add("{{baseName}}", parameterToString(*r.{{paramName}}, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}"))
{{/isCollectionFormatMulti}}
{{/required}}
{{^required}}
if r.{{paramName}} != nil {
{{#isCollectionFormatMulti}}
t := *r.{{paramName}}
if reflect.TypeOf(t).Kind() == reflect.Slice {
s := reflect.ValueOf(t)
for i := 0; i < s.Len(); i++ {
localVarQueryParams.Add("{{baseName}}", parameterToString(s.Index(i), "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}"))
}
} else {
localVarQueryParams.Add("{{baseName}}", parameterToString(t, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}"))
}
{{/isCollectionFormatMulti}}
{{^isCollectionFormatMulti}}
localVarQueryParams.Add("{{baseName}}", parameterToString(*r.{{paramName}}, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}"))
{{/isCollectionFormatMulti}}
}
{{/required}}
{{/queryParams}}
// to determine the Content-Type header
{{=<% %>=}}
localVarHTTPContentTypes := []string{<%#consumes%>"<%&mediaType%>"<%^-last%>, <%/-last%><%/consumes%>}
<%={{ }}=%>
// set Content-Type header
localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)
if localVarHTTPContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHTTPContentType
}
// to determine the Accept header
{{=<% %>=}}
localVarHTTPHeaderAccepts := []string{<%#produces%>"<%&mediaType%>"<%^-last%>, <%/-last%><%/produces%>}
<%={{ }}=%>
// set Accept header
localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)
if localVarHTTPHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept
}
{{#headerParams}}
{{#required}}
localVarHeaderParams["{{baseName}}"] = parameterToString(*r.{{paramName}}, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}")
{{/required}}
{{^required}}
if r.{{paramName}} != nil {
localVarHeaderParams["{{baseName}}"] = parameterToString(*r.{{paramName}}, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}")
}
{{/required}}
{{/headerParams}}
{{#formParams}}
{{#isFile}}
localVarFormFileName = "{{baseName}}"
{{#required}}
localVarFile := *r.{{paramName}}
{{/required}}
{{^required}}
var localVarFile {{dataType}}
if r.{{paramName}} != nil {
localVarFile = *r.{{paramName}}
}
{{/required}}
if localVarFile != nil {
fbs, _ := _ioutil.ReadAll(localVarFile)
localVarFileBytes = fbs
localVarFileName = localVarFile.Name()
localVarFile.Close()
}
{{/isFile}}
{{^isFile}}
{{#required}}
localVarFormParams.Add("{{baseName}}", parameterToString(*r.{{paramName}}, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}"))
{{/required}}
{{^required}}
{{#isModel}}
if r.{{paramName}} != nil {
paramJson, err := parameterToJson(*r.{{paramName}})
if err != nil {
return {{#returnType}}localVarReturnValue, {{/returnType}}nil, err
}
localVarFormParams.Add("{{baseName}}", paramJson)
}
{{/isModel}}
{{^isModel}}
if r.{{paramName}} != nil {
localVarFormParams.Add("{{baseName}}", parameterToString(*r.{{paramName}}, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}"))
}
{{/isModel}}
{{/required}}
{{/isFile}}
{{/formParams}}
{{#bodyParams}}
// body params
localVarPostBody = r.{{paramName}}
{{/bodyParams}}
{{#authMethods}}
{{#isApiKey}}
{{^isKeyInCookie}}
if r.ctx != nil {
// API Key Authentication
if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {
{{#vendorExtensions.x-auth-id-alias}}
if apiKey, ok := auth["{{.}}"]; ok {
var key string
if prefix, ok := auth["{{name}}"]; ok && prefix.Prefix != "" {
key = prefix.Prefix + " " + apiKey.Key
} else {
key = apiKey.Key
}
{{/vendorExtensions.x-auth-id-alias}}
{{^vendorExtensions.x-auth-id-alias}}
if apiKey, ok := auth["{{name}}"]; ok {
var key string
if apiKey.Prefix != "" {
key = apiKey.Prefix + " " + apiKey.Key
} else {
key = apiKey.Key
}
{{/vendorExtensions.x-auth-id-alias}}
{{#isKeyInHeader}}
localVarHeaderParams["{{keyParamName}}"] = key
{{/isKeyInHeader}}
{{#isKeyInQuery}}
localVarQueryParams.Add("{{keyParamName}}", key)
{{/isKeyInQuery}}
}
}
}
{{/isKeyInCookie}}
{{/isApiKey}}
{{/authMethods}}
req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)
if err != nil {
return {{#returnType}}localVarReturnValue, {{/returnType}}nil, err
}
localVarHTTPResponse, err := a.client.callAPI(req)
if err != nil || localVarHTTPResponse == nil {
return {{#returnType}}localVarReturnValue, {{/returnType}}localVarHTTPResponse, err
}
localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)
localVarHTTPResponse.Body.Close()
if err != nil {
return {{#returnType}}localVarReturnValue, {{/returnType}}localVarHTTPResponse, err
}
if localVarHTTPResponse.StatusCode >= 300 {
newErr := GenericOpenAPIError{
body: localVarBody,
error: localVarHTTPResponse.Status,
}
{{#responses}}
{{#dataType}}
{{^is1xx}}
{{^is2xx}}
{{^wildcard}}
if localVarHTTPResponse.StatusCode == {{{code}}} {
{{/wildcard}}
var v {{{dataType}}}
err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr.error = err.Error()
return {{#returnType}}localVarReturnValue, {{/returnType}}localVarHTTPResponse, newErr
}
newErr.model = v
{{#hasMore}}
return {{#returnType}}localVarReturnValue, {{/returnType}}localVarHTTPResponse, newErr
{{/hasMore}}
{{^wildcard}}
}
{{/wildcard}}
{{/is2xx}}
{{/is1xx}}
{{/dataType}}
{{/responses}}
return {{#returnType}}localVarReturnValue, {{/returnType}}localVarHTTPResponse, newErr
}
{{#returnType}}
err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr := GenericOpenAPIError{
body: localVarBody,
error: err.Error(),
}
return {{#returnType}}localVarReturnValue, {{/returnType}}localVarHTTPResponse, newErr
}
{{/returnType}}
return {{#returnType}}localVarReturnValue, {{/returnType}}localVarHTTPResponse, nil
}
{{/operation}}
{{/operations}}

View File

@ -1,89 +0,0 @@
# {{invokerPackage}}\{{classname}}{{#description}}
{{description}}{{/description}}
All URIs are relative to *{{basePath}}*
Method | HTTP request | Description
------------- | ------------- | -------------
{{#operations}}{{#operation}}[**{{operationId}}**]({{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}}
{{/operation}}{{/operations}}
{{#operations}}
{{#operation}}
## {{{operationId}}}
> {{#returnType}}{{{.}}} {{/returnType}}{{{operationId}}}(ctx{{#pathParams}}, {{paramName}}{{/pathParams}}){{#allParams}}{{^isPathParam}}.{{vendorExtensions.x-export-param-name}}({{paramName}}){{/isPathParam}}{{/allParams}}.Execute()
{{{summary}}}{{#notes}}
{{{unespacedNotes}}}{{/notes}}
### Example
```go
package main
import (
"context"
"fmt"
"os"
{{goImportAlias}} "./openapi"
)
func main() {
{{#allParams}}
{{paramName}} := {{{vendorExtensions.x-go-example}}} // {{{dataType}}} | {{{description}}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}}
{{/allParams}}
configuration := {{goImportAlias}}.NewConfiguration()
api_client := {{goImportAlias}}.NewAPIClient(configuration)
resp, r, err := api_client.{{classname}}.{{operationId}}(context.Background(), {{#requiredParams}}{{paramName}}{{^-last}}, {{/-last}}{{/requiredParams}}){{#optionalParams}}.{{{vendorExtensions.x-export-param-name}}}({{{paramName}}}){{/optionalParams}}.Execute()
if err != nil {
fmt.Fprintf(os.Stderr, "Error when calling `{{classname}}.{{operationId}}``: %v\n", err)
fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r)
}
{{#returnType}}
// response from `{{operationId}}`: {{{.}}}
fmt.Fprintf(os.Stdout, "Response from `{{classname}}.{{operationId}}`: %v\n", resp)
{{/returnType}}
}
```
### Path Parameters
{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#pathParams}}{{#-last}}
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc.{{/-last}}{{/pathParams}}{{#pathParams}}
**{{paramName}}** | {{^isPrimitiveType}}{{^isFile}}[{{/isFile}}{{/isPrimitiveType}}**{{dataType}}**{{^isPrimitiveType}}{{^isFile}}]({{baseType}}.md){{/isFile}}{{/isPrimitiveType}} | {{description}} | {{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}}{{/pathParams}}
### Other Parameters
Other parameters are passed through a pointer to a api{{{nickname}}}Request struct via the builder pattern
{{#allParams}}{{#-last}}
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}}{{#allParams}}
{{^isPathParam}} **{{paramName}}** | {{^isPrimitiveType}}{{^isFile}}[{{/isFile}}{{/isPrimitiveType}}**{{dataType}}**{{^isPrimitiveType}}{{^isFile}}]({{baseType}}.md){{/isFile}}{{/isPrimitiveType}} | {{description}} | {{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}}{{/isPathParam}}{{/allParams}}
### Return type
{{#returnType}}{{#returnTypeIsPrimitive}}**{{{returnType}}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{{returnType}}}**]({{returnBaseType}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}} (empty response body){{/returnType}}
### Authorization
{{^authMethods}}No authorization required{{/authMethods}}{{#authMethods}}[{{{name}}}](../README.md#{{{name}}}){{^-last}}, {{/-last}}{{/authMethods}}
### HTTP request headers
- **Content-Type**: {{#consumes}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}}
- **Accept**: {{#produces}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}}
[[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)
{{/operation}}
{{/operations}}

View File

@ -1,303 +0,0 @@
{{>partial_header}}
package {{packageName}}
import (
"context"
"fmt"
"net/http"
"strings"
)
// contextKeys are used to identify the type of value in the context.
// Since these are string, it is possible to get a short description of the
// context key for logging and debugging using key.String().
type contextKey string
func (c contextKey) String() string {
return "auth " + string(c)
}
var (
// ContextOAuth2 takes an oauth2.TokenSource as authentication for the request.
ContextOAuth2 = contextKey("token")
// ContextBasicAuth takes BasicAuth as authentication for the request.
ContextBasicAuth = contextKey("basic")
// ContextAccessToken takes a string oauth2 access token as authentication for the request.
ContextAccessToken = contextKey("accesstoken")
// ContextAPIKeys takes a string apikey as authentication for the request
ContextAPIKeys = contextKey("apiKeys")
{{#withAWSV4Signature}}
// ContextAWSv4 takes an Access Key and a Secret Key for signing AWS Signature v4
ContextAWSv4 = contextKey("awsv4")
{{/withAWSV4Signature}}
// ContextHttpSignatureAuth takes HttpSignatureAuth as authentication for the request.
ContextHttpSignatureAuth = contextKey("httpsignature")
// ContextServerIndex uses a server configuration from the index.
ContextServerIndex = contextKey("serverIndex")
// ContextOperationServerIndices uses a server configuration from the index mapping.
ContextOperationServerIndices = contextKey("serverOperationIndices")
// ContextServerVariables overrides a server configuration variables.
ContextServerVariables = contextKey("serverVariables")
// ContextOperationServerVariables overrides a server configuration variables using operation specific values.
ContextOperationServerVariables = contextKey("serverOperationVariables")
)
// BasicAuth provides basic http authentication to a request passed via context using ContextBasicAuth
type BasicAuth struct {
UserName string `json:"userName,omitempty"`
Password string `json:"password,omitempty"`
}
// APIKey provides API key based authentication to a request passed via context using ContextAPIKey
type APIKey struct {
Key string
Prefix string
}
{{#withAWSV4Signature}}
// AWSv4 provides AWS Signature to a request passed via context using ContextAWSv4
// https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html
type AWSv4 struct {
AccessKey string
SecretKey string
}
{{/withAWSV4Signature}}
// ServerVariable stores the information about a server variable
type ServerVariable struct {
Description string
DefaultValue string
EnumValues []string
}
// ServerConfiguration stores the information about a server
type ServerConfiguration struct {
URL string
Description string
Variables map[string]ServerVariable
}
// ServerConfigurations stores multiple ServerConfiguration items
type ServerConfigurations []ServerConfiguration
// Configuration stores the configuration of the API client
type Configuration struct {
Host string `json:"host,omitempty"`
Scheme string `json:"scheme,omitempty"`
DefaultHeader map[string]string `json:"defaultHeader,omitempty"`
UserAgent string `json:"userAgent,omitempty"`
Debug bool `json:"debug,omitempty"`
Servers ServerConfigurations
OperationServers map[string]ServerConfigurations
HTTPClient *http.Client
}
// NewConfiguration returns a new Configuration object
func NewConfiguration() *Configuration {
cfg := &Configuration{
DefaultHeader: make(map[string]string),
UserAgent: "{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}OpenAPI-Generator/{{{packageVersion}}}/go{{/httpUserAgent}}",
Debug: false,
{{#servers}}
{{#-first}}
Servers: ServerConfigurations{
{{/-first}}
{
URL: "{{{url}}}",
Description: "{{{description}}}{{^description}}No description provided{{/description}}",
{{#variables}}
{{#-first}}
Variables: map[string]ServerVariable{
{{/-first}}
"{{{name}}}": ServerVariable{
Description: "{{{description}}}{{^description}}No description provided{{/description}}",
DefaultValue: "{{{defaultValue}}}",
{{#enumValues}}
{{#-first}}
EnumValues: []string{
{{/-first}}
"{{{.}}}",
{{#-last}}
},
{{/-last}}
{{/enumValues}}
},
{{#-last}}
},
{{/-last}}
{{/variables}}
},
{{#-last}}
},
{{/-last}}
{{/servers}}
{{#apiInfo}}
OperationServers: map[string]ServerConfigurations{
{{#apis}}
{{#operations}}
{{#operation}}
{{#servers}}
{{#-first}}
"{{{classname}}}Service.{{{nickname}}}": {
{{/-first}}
{
URL: "{{{url}}}",
Description: "{{{description}}}{{^description}}No description provided{{/description}}",
{{#variables}}
{{#-first}}
Variables: map[string]ServerVariable{
{{/-first}}
"{{{name}}}": ServerVariable{
Description: "{{{description}}}{{^description}}No description provided{{/description}}",
DefaultValue: "{{{defaultValue}}}",
{{#enumValues}}
{{#-first}}
EnumValues: []string{
{{/-first}}
"{{{.}}}",
{{#-last}}
},
{{/-last}}
{{/enumValues}}
},
{{#-last}}
},
{{/-last}}
{{/variables}}
},
{{#-last}}
},
{{/-last}}
{{/servers}}
{{/operation}}
{{/operations}}
{{/apis}}
},
{{/apiInfo}}
}
return cfg
}
// AddDefaultHeader adds a new HTTP header to the default header in the request
func (c *Configuration) AddDefaultHeader(key string, value string) {
c.DefaultHeader[key] = value
}
// URL formats template on a index using given variables
func (sc ServerConfigurations) URL(index int, variables map[string]string) (string, error) {
if index < 0 || len(sc) <= index {
return "", fmt.Errorf("Index %v out of range %v", index, len(sc)-1)
}
server := sc[index]
url := server.URL
// go through variables and replace placeholders
for name, variable := range server.Variables {
if value, ok := variables[name]; ok {
found := bool(len(variable.EnumValues) == 0)
for _, enumValue := range variable.EnumValues {
if value == enumValue {
found = true
}
}
if !found {
return "", fmt.Errorf("The variable %s in the server URL has invalid value %v. Must be %v", name, value, variable.EnumValues)
}
url = strings.Replace(url, "{"+name+"}", value, -1)
} else {
url = strings.Replace(url, "{"+name+"}", variable.DefaultValue, -1)
}
}
return url, nil
}
// ServerURL returns URL based on server settings
func (c *Configuration) ServerURL(index int, variables map[string]string) (string, error) {
return c.Servers.URL(index, variables)
}
func getServerIndex(ctx context.Context) (int, error) {
si := ctx.Value(ContextServerIndex)
if si != nil {
if index, ok := si.(int); ok {
return index, nil
}
return 0, reportError("Invalid type %T should be int", si)
}
return 0, nil
}
func getServerOperationIndex(ctx context.Context, endpoint string) (int, error) {
osi := ctx.Value(ContextOperationServerIndices)
if osi != nil {
if operationIndices, ok := osi.(map[string]int); !ok {
return 0, reportError("Invalid type %T should be map[string]int", osi)
} else {
index, ok := operationIndices[endpoint]
if ok {
return index, nil
}
}
}
return getServerIndex(ctx)
}
func getServerVariables(ctx context.Context) (map[string]string, error) {
sv := ctx.Value(ContextServerVariables)
if sv != nil {
if variables, ok := sv.(map[string]string); ok {
return variables, nil
}
return nil, reportError("ctx value of ContextServerVariables has invalid type %T should be map[string]string", sv)
}
return nil, nil
}
func getServerOperationVariables(ctx context.Context, endpoint string) (map[string]string, error) {
osv := ctx.Value(ContextOperationServerVariables)
if osv != nil {
if operationVariables, ok := osv.(map[string]map[string]string); !ok {
return nil, reportError("ctx value of ContextOperationServerVariables has invalid type %T should be map[string]map[string]string", osv)
} else {
variables, ok := operationVariables[endpoint]
if ok {
return variables, nil
}
}
}
return getServerVariables(ctx)
}
// ServerURLWithContext returns a new server URL given an endpoint
func (c *Configuration) ServerURLWithContext(ctx context.Context, endpoint string) (string, error) {
sc, ok := c.OperationServers[endpoint]
if !ok {
sc = c.Servers
}
if ctx == nil {
return sc.URL(0, nil)
}
index, err := getServerOperationIndex(ctx, endpoint)
if err != nil {
return "", err
}
variables, err := getServerOperationVariables(ctx, endpoint)
if err != nil {
return "", err
}
return sc.URL(index, variables)
}

View File

@ -1,15 +0,0 @@
cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
github.com/antihax/optional v1.0.0 h1:xK2lYat7ZLaVVcIuj82J8kIro4V6kDe0AUDFboUCwcg=
github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY=
github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e h1:bRhVy7zSSasaqNksaRZiA5EEI+Ei4I1nO5Jh72wfHlg=
golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45 h1:SVwTIAaPC2U/AvvLNZ2a7OVsmBpC8L5BlwK1whH3hm0=
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4 h1:YUO/7uOKsKeq9UokNS62b8FYywz3ker1l1vDZRCRefw=
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
google.golang.org/appengine v1.4.0 h1:/wp5JvzpHIxhs/dumFmF7BXTf3Z+dd4uXta4kVyO508=
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=

View File

@ -1,20 +0,0 @@
{{>partial_header}}
package {{packageName}}
{{#models}}
import (
"encoding/json"
{{#imports}}
"{{import}}"
{{/imports}}
)
{{#model}}
{{#isEnum}}
{{>model_enum}}
{{/isEnum}}
{{^isEnum}}
{{#oneOf}}{{#-first}}{{>model_oneof}}{{/-first}}{{/oneOf}}{{^oneOf}}{{#anyOf}}{{#-first}}{{>model_anyof}}{{/-first}}{{/anyOf}}{{^anyOf}}{{>model_simple}}{{/anyOf}}{{/oneOf}}
{{/isEnum}}
{{/model}}
{{/models}}

View File

@ -1,90 +0,0 @@
{{#models}}{{#model}}# {{classname}}
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
{{#vendorExtensions.x-is-one-of-interface}}
**{{classname}}Interface** | **interface { {{#discriminator}}{{propertyGetter}}() {{propertyType}}{{/discriminator}} }** | An interface that can hold any of the proper implementing types |
{{/vendorExtensions.x-is-one-of-interface}}
{{^vendorExtensions.x-is-one-of-interface}}
{{#vars}}**{{name}}** | {{^required}}Pointer to {{/required}}{{#isPrimitiveType}}**{{{dataType}}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{{dataType}}}**]({{complexType}}.md){{/isPrimitiveType}} | {{description}} | {{^required}}[optional] {{/required}}{{#isReadOnly}}[readonly] {{/isReadOnly}}{{#defaultValue}}[default to {{{.}}}]{{/defaultValue}}
{{/vars}}
{{/vendorExtensions.x-is-one-of-interface}}
{{^isEnum}}
## Methods
{{^vendorExtensions.x-is-one-of-interface}}
### New{{classname}}
`func New{{classname}}({{#vars}}{{#required}}{{nameInCamelCase}} {{dataType}}, {{/required}}{{/vars}}) *{{classname}}`
New{{classname}} instantiates a new {{classname}} object
This constructor will assign default values to properties that have it defined,
and makes sure properties required by API are set, but the set of arguments
will change when the set of required properties is changed
### New{{classname}}WithDefaults
`func New{{classname}}WithDefaults() *{{classname}}`
New{{classname}}WithDefaults instantiates a new {{classname}} object
This constructor will only assign default values to properties that have it defined,
but it doesn't guarantee that properties required by API are set
{{#vars}}
### Get{{name}}
`func (o *{{classname}}) Get{{name}}() {{vendorExtensions.x-go-base-type}}`
Get{{name}} returns the {{name}} field if non-nil, zero value otherwise.
### Get{{name}}Ok
`func (o *{{classname}}) Get{{name}}Ok() (*{{vendorExtensions.x-go-base-type}}, bool)`
Get{{name}}Ok returns a tuple with the {{name}} field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### Set{{name}}
`func (o *{{classname}}) Set{{name}}(v {{vendorExtensions.x-go-base-type}})`
Set{{name}} sets {{name}} field to given value.
{{^required}}
### Has{{name}}
`func (o *{{classname}}) Has{{name}}() bool`
Has{{name}} returns a boolean if a field has been set.
{{/required}}
{{#isNullable}}
### Set{{name}}Nil
`func (o *{{classname}}) Set{{name}}Nil(b bool)`
Set{{name}}Nil sets the value for {{name}} to be an explicit nil
### Unset{{name}}
`func (o *{{classname}}) Unset{{name}}()`
Unset{{name}} ensures that no value is present for {{name}}, not even an explicit nil
{{/isNullable}}
{{/vars}}
{{#vendorExtensions.x-implements}}
### As{{{.}}}
`func (s *{{classname}}) As{{{.}}}() {{{.}}}`
Convenience method to wrap this instance of {{classname}} in {{{.}}}
{{/vendorExtensions.x-implements}}
{{/vendorExtensions.x-is-one-of-interface}}
{{/isEnum}}
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
{{/model}}{{/models}}

View File

@ -24,17 +24,54 @@ Install the following dependencies:
```shell
go get github.com/stretchr/testify/assert
go get golang.org/x/oauth2
{{#withAWSV4Signature}}
go get github.com/aws/aws-sdk-go/aws
{{/withAWSV4Signature}}
go get golang.org/x/net/context
go get github.com/antihax/optional
```
Put the package under your project folder and add the following in import:
```golang
import "./{{packageName}}"
import sw "./{{packageName}}"
```
## Configuration of Server URL
Default configuration comes with `Servers` field that contains server objects as defined in the OpenAPI specification.
### Select Server Configuration
For using other server than the one defined on index 0 set context value `sw.ContextServerIndex` of type `int`.
```golang
ctx := context.WithValue(context.Background(), sw.ContextServerIndex, 1)
```
### Templated Server URL
Templated server URL is formatted using default variables from configuration or from context value `sw.ContextServerVariables` of type `map[string]string`.
```golang
ctx := context.WithValue(context.Background(), sw.ContextServerVariables, map[string]string{
"basePath": "v2",
})
```
Note, enum values are always validated and all unused variables are silently ignored.
### URLs Configuration per Operation
Each operation can use different server URL defined using `OperationServers` map in the `Configuration`.
An operation is uniquely identifield by `"{classname}Service.{nickname}"` string.
Similar rules for overriding default operation server index and variables applies by using `sw.ContextOperationServerIndices` and `sw.ContextOperationServerVariables` context maps.
```
ctx := context.WithValue(context.Background(), sw.ContextOperationServerIndices, map[string]int{
"{classname}Service.{nickname}": 2,
})
ctx = context.WithValue(context.Background(), sw.ContextOperationServerVariables, map[string]map[string]string{
"{classname}Service.{nickname}": {
"port": "8443",
},
})
```
## Documentation for API Endpoints
@ -57,31 +94,35 @@ Class | Method | HTTP request | Description
{{/authMethods}}{{#authMethods}}{{#last}} Authentication schemes defined for the API:{{/last}}{{/authMethods}}
{{#authMethods}}
## {{{name}}}
### {{{name}}}
{{#isApiKey}}- **Type**: API key
{{#isApiKey}}
- **Type**: API key
- **API key parameter name**: {{{keyParamName}}}
- **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}}
Note, each API key must be added to a map of `map[string]APIKey` where the key is: {{keyParamName}} and passed in as the auth context for each request.
{{/isApiKey}}
{{#isBasic}}
{{#isBasicBearer}}
- **Type**: HTTP Bearer token authentication
Example
```golang
auth := context.WithValue(context.Background(), {{packageName}}.ContextAPIKey, {{packageName}}.APIKey{
Key: "APIKEY",
Prefix: "Bearer", // Omit if not necessary.
})
auth := context.WithValue(context.Background(), sw.ContextAccessToken, "BEARERTOKENSTRING")
r, err := client.Service.Operation(auth, args)
```
{{/isApiKey}}
{{#isHttpSignature}}
Not supported.
{{/isHttpSignature}}
{{#isBasicBasic}}- **Type**: HTTP basic authentication
{{/isBasicBearer}}
{{#isBasicBasic}}
- **Type**: HTTP basic authentication
Example
```golang
auth := context.WithValue(context.Background(), {{packageName}}.ContextBasicAuth, {{packageName}}.BasicAuth{
auth := context.WithValue(context.Background(), sw.ContextBasicAuth, sw.BasicAuth{
UserName: "username",
Password: "password",
})
@ -89,16 +130,38 @@ r, err := client.Service.Operation(auth, args)
```
{{/isBasicBasic}}
{{#isBasicBearer}}- **Type**: HTTP Bearer token authentication
{{#isHttpSignature}}
- **Type**: HTTP signature authentication
Example
```golang
auth := context.WithValue(context.Background(), {{packageName}}.ContextAccessToken, "BEARERTOKENSTRING")
r, err := client.Service.Operation(auth, args)
```
authConfig := sw.HttpSignatureAuth{
KeyId: "my-key-id",
PrivateKeyPath: "rsa.pem",
Passphrase: "my-passphrase",
SigningScheme: sw.HttpSigningSchemeHs2019,
SignedHeaders: []string{
sw.HttpSignatureParameterRequestTarget, // The special (request-target) parameter expresses the HTTP request target.
sw.HttpSignatureParameterCreated, // Time when request was signed, formatted as a Unix timestamp integer value.
"Host", // The Host request header specifies the domain name of the server, and optionally the TCP port number.
"Date", // The date and time at which the message was originated.
"Content-Type", // The Media type of the body of the request.
"Digest", // A cryptographic digest of the request body.
},
SigningAlgorithm: sw.HttpSigningAlgorithmRsaPSS,
SignatureMaxValidity: 5 * time.Minute,
}
var authCtx context.Context
var err error
if authCtx, err = authConfig.ContextWithValue(context.Background()); err != nil {
// Process error
}
r, err = client.Service.Operation(auth, args)
{{/isBasicBearer}}
```
{{/isHttpSignature}}
{{/isBasic}}
{{#isOAuth}}
- **Type**: OAuth
@ -111,7 +174,7 @@ r, err := client.Service.Operation(auth, args)
Example
```golang
auth := context.WithValue(context.Background(), {{packageName}}.ContextAccessToken, "ACCESSTOKENSTRING")
auth := context.WithValue(context.Background(), sw.ContextAccessToken, "ACCESSTOKENSTRING")
r, err := client.Service.Operation(auth, args)
```
@ -123,24 +186,28 @@ 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, {{packageName}}.ContextOAuth2, tokenSource)
auth := context.WithValue(oauth2.NoContext, sw.ContextOAuth2, tokenSource)
r, err := client.Service.Operation(auth, args)
```
{{/isOAuth}}
{{/authMethods}}
{{#withAWSV4Signature}}
Example
## Documentation for Utility Methods
```golang
auth := context.WithValue(context.Background(), {{packageName}}.ContextAWSv4, {{packageName}}.AWSv4{
AccessKey: "ACCESSKEYSTRING",
SecretKey: "SECRETKEYSTRING",
})
r, err := client.Service.Operation(auth, args)
```
{{/withAWSV4Signature}}
Due to the fact that model structure members are all pointers, this package contains
a number of utility functions to easily obtain pointers to values of basic types.
Each of these functions takes a value of the given basic type and returns a pointer to it:
* `PtrBool`
* `PtrInt`
* `PtrInt32`
* `PtrInt64`
* `PtrFloat`
* `PtrFloat32`
* `PtrFloat64`
* `PtrString`
* `PtrTime`
## Author

View File

@ -7,7 +7,6 @@ import (
_ioutil "io/ioutil"
_nethttp "net/http"
_neturl "net/url"
_bytes "bytes"
{{#imports}} "{{import}}"
{{/imports}}
)
@ -16,92 +15,77 @@ import (
var (
_ _context.Context
)
{{#generateInterfaces}}
type {{classname}} interface {
{{#operation}}
{{#operation}}
/*
* {{operationId}}{{#summary}} {{{.}}}{{/summary}}{{^summary}} Method for {{operationId}}{{/summary}}
*
{{#notes}}
* {{notes}}
*
{{/notes}}
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
{{#allParams}}
{{#required}}
* @param {{paramName}}{{#description}} {{{.}}}{{/description}}
{{/required}}
{{/allParams}}
{{#hasOptionalParams}}
* @param optional nil or *{{#structPrefix}}{{&classname}}{{/structPrefix}}{{{nickname}}}Opts - Optional Parameters:
{{#allParams}}
{{^required}}
* @param "{{vendorExtensions.x-export-param-name}}" ({{#isPrimitiveType}}{{^isBinary}}optional.{{vendorExtensions.x-optional-data-type}}{{/isBinary}}{{#isBinary}}optional.Interface of {{dataType}}{{/isBinary}}{{/isPrimitiveType}}{{^isPrimitiveType}}optional.Interface of {{dataType}}{{/isPrimitiveType}}) - {{#description}} {{{.}}}{{/description}}
{{/required}}
{{/allParams}}
{{/hasOptionalParams}}
{{#returnType}}
* @return {{{returnType}}}
{{/returnType}}
*/
{{{nickname}}}(ctx _context.Context{{#hasParams}}, {{/hasParams}}{{#allParams}}{{#required}}{{paramName}} {{{dataType}}}{{#hasMore}}, {{/hasMore}}{{/required}}{{/allParams}}{{#hasOptionalParams}}localVarOptionals *{{#structPrefix}}{{&classname}}{{/structPrefix}}{{{nickname}}}Opts{{/hasOptionalParams}}) ({{#returnType}}{{{returnType}}}, {{/returnType}}*_nethttp.Response, error)
{{/operation}}
/*
* {{operationId}}{{#summary}} {{{.}}}{{/summary}}{{^summary}} Method for {{operationId}}{{/summary}}
{{#notes}}
* {{{unescapedNotes}}}
{{/notes}}
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().{{#pathParams}}
* @param {{paramName}}{{#description}} {{{.}}}{{/description}}{{/pathParams}}
* @return {{#structPrefix}}{{&classname}}{{/structPrefix}}Api{{operationId}}Request
*/
{{{nickname}}}(ctx _context.Context{{#pathParams}}, {{paramName}} {{{dataType}}}{{/pathParams}}) {{#structPrefix}}{{&classname}}{{/structPrefix}}Api{{operationId}}Request
/*
* {{nickname}}Execute executes the request{{#returnType}}
* @return {{{.}}}{{/returnType}}
*/
{{nickname}}Execute(r {{#structPrefix}}{{&classname}}{{/structPrefix}}Api{{operationId}}Request) ({{#returnType}}{{{.}}}, {{/returnType}}*_nethttp.Response, error)
{{/operation}}
}
{{/generateInterfaces}}
// {{classname}}Service {{classname}} service
type {{classname}}Service service
{{#operation}}
{{#hasOptionalParams}}
// {{#structPrefix}}{{&classname}}{{/structPrefix}}{{{nickname}}}Opts Optional parameters for the method '{{{nickname}}}'
type {{#structPrefix}}{{&classname}}{{/structPrefix}}{{{nickname}}}Opts struct {
type {{#structPrefix}}{{&classname}}{{/structPrefix}}Api{{operationId}}Request struct {
ctx _context.Context{{#generateInterfaces}}
ApiService {{classname}}
{{/generateInterfaces}}{{^generateInterfaces}}
ApiService *{{classname}}Service
{{/generateInterfaces}}
{{#allParams}}
{{^required}}
{{#isPrimitiveType}}
{{^isBinary}}
{{vendorExtensions.x-export-param-name}} optional.{{vendorExtensions.x-optional-data-type}}
{{/isBinary}}
{{#isBinary}}
{{vendorExtensions.x-export-param-name}} optional.Interface
{{/isBinary}}
{{/isPrimitiveType}}
{{^isPrimitiveType}}
{{vendorExtensions.x-export-param-name}} optional.Interface
{{/isPrimitiveType}}
{{/required}}
{{paramName}} {{^isPathParam}}*{{/isPathParam}}{{{dataType}}}
{{/allParams}}
}
{{#allParams}}{{^isPathParam}}
func (r {{#structPrefix}}{{&classname}}{{/structPrefix}}Api{{operationId}}Request) {{vendorExtensions.x-export-param-name}}({{paramName}} {{{dataType}}}) {{#structPrefix}}{{&classname}}{{/structPrefix}}Api{{operationId}}Request {
r.{{paramName}} = &{{paramName}}
return r
}{{/isPathParam}}{{/allParams}}
func (r {{#structPrefix}}{{&classname}}{{/structPrefix}}Api{{operationId}}Request) Execute() ({{#returnType}}{{{.}}}, {{/returnType}}*_nethttp.Response, error) {
return r.ApiService.{{nickname}}Execute(r)
}
{{/hasOptionalParams}}
/*
* {{operationId}}{{#summary}} {{{.}}}{{/summary}}{{^summary}} Method for {{operationId}}{{/summary}}
*
{{#notes}}
* {{notes}}
*
* {{{unescapedNotes}}}
{{/notes}}
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
{{#allParams}}
{{#required}}
* @param {{paramName}}{{#description}} {{{.}}}{{/description}}
{{/required}}
{{/allParams}}
{{#hasOptionalParams}}
* @param optional nil or *{{#structPrefix}}{{&classname}}{{/structPrefix}}{{{nickname}}}Opts - Optional Parameters:
{{#allParams}}
{{^required}}
* @param "{{vendorExtensions.x-export-param-name}}" ({{#isPrimitiveType}}{{^isBinary}}optional.{{vendorExtensions.x-optional-data-type}}{{/isBinary}}{{#isBinary}}optional.Interface of {{dataType}}{{/isBinary}}{{/isPrimitiveType}}{{^isPrimitiveType}}optional.Interface of {{dataType}}{{/isPrimitiveType}}) - {{#description}} {{{.}}}{{/description}}
{{/required}}
{{/allParams}}
{{/hasOptionalParams}}
{{#returnType}}
* @return {{{returnType}}}
{{/returnType}}
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().{{#pathParams}}
* @param {{paramName}}{{#description}} {{{.}}}{{/description}}{{/pathParams}}
* @return {{#structPrefix}}{{&classname}}{{/structPrefix}}Api{{operationId}}Request
*/
func (a *{{{classname}}}Service) {{{nickname}}}(ctx _context.Context{{#hasParams}}, {{/hasParams}}{{#allParams}}{{#required}}{{paramName}} {{{dataType}}}{{#hasMore}}, {{/hasMore}}{{/required}}{{/allParams}}{{#hasOptionalParams}}localVarOptionals *{{#structPrefix}}{{&classname}}{{/structPrefix}}{{{nickname}}}Opts{{/hasOptionalParams}}) ({{#returnType}}{{{returnType}}}, {{/returnType}}*_nethttp.Response, error) {
func (a *{{{classname}}}Service) {{{nickname}}}(ctx _context.Context{{#pathParams}}, {{paramName}} {{{dataType}}}{{/pathParams}}) {{#structPrefix}}{{&classname}}{{/structPrefix}}Api{{operationId}}Request {
return {{#structPrefix}}{{&classname}}{{/structPrefix}}Api{{operationId}}Request{
ApiService: a,
ctx: ctx,{{#pathParams}}
{{paramName}}: {{paramName}},{{/pathParams}}
}
}
/*
* Execute executes the request{{#returnType}}
* @return {{{.}}}{{/returnType}}
*/
func (a *{{{classname}}}Service) {{nickname}}Execute(r {{#structPrefix}}{{&classname}}{{/structPrefix}}Api{{operationId}}Request) ({{#returnType}}{{{.}}}, {{/returnType}}*_nethttp.Response, error) {
var (
localVarHTTPMethod = _nethttp.Method{{httpMethod}}
localVarPostBody interface{}
@ -109,58 +93,66 @@ func (a *{{{classname}}}Service) {{{nickname}}}(ctx _context.Context{{#hasParams
localVarFileName string
localVarFileBytes []byte
{{#returnType}}
localVarReturnValue {{{returnType}}}
localVarReturnValue {{{.}}}
{{/returnType}}
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "{{{path}}}"{{#pathParams}}
localVarPath = strings.Replace(localVarPath, "{"+"{{baseName}}"+"}", _neturl.PathEscape(parameterToString({{paramName}}, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}")) , -1)
{{/pathParams}}
localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "{{{classname}}}Service.{{{nickname}}}")
if err != nil {
return {{#returnType}}localVarReturnValue, {{/returnType}}nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "{{{path}}}"{{#pathParams}}
localVarPath = strings.Replace(localVarPath, "{"+"{{baseName}}"+"}", _neturl.PathEscape(parameterToString(r.{{paramName}}, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}")) , -1){{/pathParams}}
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
{{#allParams}}
{{#required}}
{{^isPathParam}}
if r.{{paramName}} == nil {
return {{#returnType}}localVarReturnValue, {{/returnType}}nil, reportError("{{paramName}} is required and must be specified")
}
{{/isPathParam}}
{{#minItems}}
if len({{paramName}}) < {{minItems}} {
if len({{^isPathParam}}*{{/isPathParam}}r.{{paramName}}) < {{minItems}} {
return {{#returnType}}localVarReturnValue, {{/returnType}}nil, reportError("{{paramName}} must have at least {{minItems}} elements")
}
{{/minItems}}
{{#maxItems}}
if len({{paramName}}) > {{maxItems}} {
if len({{^isPathParam}}*{{/isPathParam}}r.{{paramName}}) > {{maxItems}} {
return {{#returnType}}localVarReturnValue, {{/returnType}}nil, reportError("{{paramName}} must have less than {{maxItems}} elements")
}
{{/maxItems}}
{{#minLength}}
if strlen({{paramName}}) < {{minLength}} {
if strlen({{^isPathParam}}*{{/isPathParam}}r.{{paramName}}) < {{minLength}} {
return {{#returnType}}localVarReturnValue, {{/returnType}}nil, reportError("{{paramName}} must have at least {{minLength}} elements")
}
{{/minLength}}
{{#maxLength}}
if strlen({{paramName}}) > {{maxLength}} {
if strlen({{^isPathParam}}*{{/isPathParam}}r.{{paramName}}) > {{maxLength}} {
return {{#returnType}}localVarReturnValue, {{/returnType}}nil, reportError("{{paramName}} must have less than {{maxLength}} elements")
}
{{/maxLength}}
{{#minimum}}
{{#isString}}
{{paramName}}Txt, err := atoi({{paramName}})
{{paramName}}Txt, err := atoi({{^isPathParam}}*{{/isPathParam}}r.{{paramName}})
if {{paramName}}Txt < {{minimum}} {
{{/isString}}
{{^isString}}
if {{paramName}} < {{minimum}} {
if {{^isPathParam}}*{{/isPathParam}}r.{{paramName}} < {{minimum}} {
{{/isString}}
return {{#returnType}}localVarReturnValue, {{/returnType}}nil, reportError("{{paramName}} must be greater than {{minimum}}")
}
{{/minimum}}
{{#maximum}}
{{#isString}}
{{paramName}}Txt, err := atoi({{paramName}})
{{paramName}}Txt, err := atoi({{^isPathParam}}*{{/isPathParam}}r.{{paramName}})
if {{paramName}}Txt > {{maximum}} {
{{/isString}}
{{^isString}}
if {{paramName}} > {{maximum}} {
if {{^isPathParam}}*{{/isPathParam}}r.{{paramName}} > {{maximum}} {
{{/isString}}
return {{#returnType}}localVarReturnValue, {{/returnType}}nil, reportError("{{paramName}} must be less than {{maximum}}")
}
@ -168,12 +160,11 @@ func (a *{{{classname}}}Service) {{{nickname}}}(ctx _context.Context{{#hasParams
{{/required}}
{{/allParams}}
{{#hasQueryParams}}
{{#queryParams}}
{{#required}}
{{#isCollectionFormatMulti}}
{
t:={{paramName}}
t := *r.{{paramName}}
if reflect.TypeOf(t).Kind() == reflect.Slice {
s := reflect.ValueOf(t)
for i := 0; i < s.Len(); i++ {
@ -185,13 +176,13 @@ func (a *{{{classname}}}Service) {{{nickname}}}(ctx _context.Context{{#hasParams
}
{{/isCollectionFormatMulti}}
{{^isCollectionFormatMulti}}
localVarQueryParams.Add("{{baseName}}", parameterToString({{paramName}}, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}"))
localVarQueryParams.Add("{{baseName}}", parameterToString(*r.{{paramName}}, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}"))
{{/isCollectionFormatMulti}}
{{/required}}
{{^required}}
if localVarOptionals != nil && localVarOptionals.{{vendorExtensions.x-export-param-name}}.IsSet() {
if r.{{paramName}} != nil {
{{#isCollectionFormatMulti}}
t:=localVarOptionals.{{vendorExtensions.x-export-param-name}}.Value()
t := *r.{{paramName}}
if reflect.TypeOf(t).Kind() == reflect.Slice {
s := reflect.ValueOf(t)
for i := 0; i < s.Len(); i++ {
@ -202,12 +193,11 @@ func (a *{{{classname}}}Service) {{{nickname}}}(ctx _context.Context{{#hasParams
}
{{/isCollectionFormatMulti}}
{{^isCollectionFormatMulti}}
localVarQueryParams.Add("{{baseName}}", parameterToString(localVarOptionals.{{vendorExtensions.x-export-param-name}}.Value(), "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}"))
localVarQueryParams.Add("{{baseName}}", parameterToString(*r.{{paramName}}, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}"))
{{/isCollectionFormatMulti}}
}
{{/required}}
{{/queryParams}}
{{/hasQueryParams}}
// to determine the Content-Type header
{{=<% %>=}}
localVarHTTPContentTypes := []string{<%#consumes%>"<%&mediaType%>"<%^-last%>, <%/-last%><%/consumes%>}
@ -229,33 +219,26 @@ func (a *{{{classname}}}Service) {{{nickname}}}(ctx _context.Context{{#hasParams
if localVarHTTPHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept
}
{{#hasHeaderParams}}
{{#headerParams}}
{{#required}}
localVarHeaderParams["{{baseName}}"] = parameterToString({{paramName}}, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}")
localVarHeaderParams["{{baseName}}"] = parameterToString(*r.{{paramName}}, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}")
{{/required}}
{{^required}}
if localVarOptionals != nil && localVarOptionals.{{vendorExtensions.x-export-param-name}}.IsSet() {
localVarHeaderParams["{{baseName}}"] = parameterToString(localVarOptionals.{{vendorExtensions.x-export-param-name}}.Value(), "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}")
if r.{{paramName}} != nil {
localVarHeaderParams["{{baseName}}"] = parameterToString(*r.{{paramName}}, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}")
}
{{/required}}
{{/headerParams}}
{{/hasHeaderParams}}
{{#hasFormParams}}
{{#formParams}}
{{#isFile}}
localVarFormFileName = "{{baseName}}"
{{#required}}
localVarFile := {{paramName}}
localVarFile := *r.{{paramName}}
{{/required}}
{{^required}}
var localVarFile {{dataType}}
if localVarOptionals != nil && localVarOptionals.{{vendorExtensions.x-export-param-name}}.IsSet() {
localVarFileOk := false
localVarFile, localVarFileOk = localVarOptionals.{{vendorExtensions.x-export-param-name}}.Value().({{dataType}})
if !localVarFileOk {
return {{#returnType}}localVarReturnValue, {{/returnType}}nil, reportError("{{paramName}} should be {{dataType}}")
}
if r.{{paramName}} != nil {
localVarFile = *r.{{paramName}}
}
{{/required}}
if localVarFile != nil {
@ -267,12 +250,12 @@ func (a *{{{classname}}}Service) {{{nickname}}}(ctx _context.Context{{#hasParams
{{/isFile}}
{{^isFile}}
{{#required}}
localVarFormParams.Add("{{baseName}}", parameterToString({{paramName}}, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}"))
localVarFormParams.Add("{{baseName}}", parameterToString(*r.{{paramName}}, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}"))
{{/required}}
{{^required}}
{{#isModel}}
if localVarOptionals != nil && localVarOptionals.{{vendorExtensions.x-export-param-name}}.IsSet() {
paramJson, err := parameterToJson(localVarOptionals.{{vendorExtensions.x-export-param-name}}.Value())
if r.{{paramName}} != nil {
paramJson, err := parameterToJson(*r.{{paramName}})
if err != nil {
return {{#returnType}}localVarReturnValue, {{/returnType}}nil, err
}
@ -280,73 +263,65 @@ func (a *{{{classname}}}Service) {{{nickname}}}(ctx _context.Context{{#hasParams
}
{{/isModel}}
{{^isModel}}
if localVarOptionals != nil && localVarOptionals.{{vendorExtensions.x-export-param-name}}.IsSet() {
localVarFormParams.Add("{{baseName}}", parameterToString(localVarOptionals.{{vendorExtensions.x-export-param-name}}.Value(), "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}"))
if r.{{paramName}} != nil {
localVarFormParams.Add("{{baseName}}", parameterToString(*r.{{paramName}}, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}"))
}
{{/isModel}}
{{/required}}
{{/isFile}}
{{/formParams}}
{{/hasFormParams}}
{{#hasBodyParam}}
{{#bodyParams}}
// body params
{{#required}}
localVarPostBody = &{{paramName}}
{{/required}}
{{^required}}
if localVarOptionals != nil && localVarOptionals.{{vendorExtensions.x-export-param-name}}.IsSet() {
{{#isPrimitiveType}}
localVarPostBody = localVarOptionals.{{vendorExtensions.x-export-param-name}}.Value()
{{/isPrimitiveType}}
{{^isPrimitiveType}}
localVarOptional{{vendorExtensions.x-export-param-name}}, localVarOptional{{vendorExtensions.x-export-param-name}}ok := localVarOptionals.{{vendorExtensions.x-export-param-name}}.Value().({{{dataType}}})
if !localVarOptional{{vendorExtensions.x-export-param-name}}ok {
return {{#returnType}}localVarReturnValue, {{/returnType}}nil, reportError("{{paramName}} should be {{dataType}}")
}
localVarPostBody = &localVarOptional{{vendorExtensions.x-export-param-name}}
{{/isPrimitiveType}}
}
{{/required}}
localVarPostBody = r.{{paramName}}
{{/bodyParams}}
{{/hasBodyParam}}
{{#authMethods}}
{{#isApiKey}}
{{^isKeyInCookie}}
if ctx != nil {
if r.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
if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {
{{#vendorExtensions.x-auth-id-alias}}
if apiKey, ok := auth["{{.}}"]; ok {
var key string
if prefix, ok := auth["{{name}}"]; ok && prefix.Prefix != "" {
key = prefix.Prefix + " " + apiKey.Key
} else {
key = apiKey.Key
}
{{/vendorExtensions.x-auth-id-alias}}
{{^vendorExtensions.x-auth-id-alias}}
if apiKey, ok := auth["{{name}}"]; ok {
var key string
if apiKey.Prefix != "" {
key = apiKey.Prefix + " " + apiKey.Key
} else {
key = apiKey.Key
}
{{/vendorExtensions.x-auth-id-alias}}
{{#isKeyInHeader}}
localVarHeaderParams["{{keyParamName}}"] = key
{{/isKeyInHeader}}
{{#isKeyInQuery}}
localVarQueryParams.Add("{{keyParamName}}", key)
{{/isKeyInQuery}}
}
{{#isKeyInHeader}}
localVarHeaderParams["{{keyParamName}}"] = key
{{/isKeyInHeader}}
{{#isKeyInQuery}}
localVarQueryParams.Add("{{keyParamName}}", key)
{{/isKeyInQuery}}
}
}
{{/isKeyInCookie}}
{{/isApiKey}}
{{/authMethods}}
r, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)
req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)
if err != nil {
return {{#returnType}}localVarReturnValue, {{/returnType}}nil, err
}
localVarHTTPResponse, err := a.client.callAPI(r)
localVarHTTPResponse, err := a.client.callAPI(req)
if err != nil || localVarHTTPResponse == nil {
return {{#returnType}}localVarReturnValue, {{/returnType}}localVarHTTPResponse, err
}
localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)
localVarHTTPResponse.Body.Close()
localVarHTTPResponse.Body = _ioutil.NopCloser(_bytes.NewBuffer(localVarBody))
if err != nil {
return {{#returnType}}localVarReturnValue, {{/returnType}}localVarHTTPResponse, err
}

View File

@ -14,29 +14,59 @@ Method | HTTP request | Description
## {{{operationId}}}
> {{#returnType}}{{{returnType}}} {{/returnType}}{{{operationId}}}(ctx, {{#allParams}}{{#required}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/required}}{{/allParams}}{{#hasOptionalParams}}optional{{/hasOptionalParams}})
> {{#returnType}}{{{.}}} {{/returnType}}{{{operationId}}}(ctx{{#pathParams}}, {{paramName}}{{/pathParams}}){{#allParams}}{{^isPathParam}}.{{vendorExtensions.x-export-param-name}}({{paramName}}){{/isPathParam}}{{/allParams}}.Execute()
{{{summary}}}{{#notes}}
{{{notes}}}{{/notes}}
{{{unespacedNotes}}}{{/notes}}
### Required Parameters
### Example
{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}}
```go
package main
import (
"context"
"fmt"
"os"
{{goImportAlias}} "./openapi"
)
func main() {
{{#allParams}}
{{paramName}} := {{{vendorExtensions.x-go-example}}} // {{{dataType}}} | {{{description}}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}}
{{/allParams}}
configuration := {{goImportAlias}}.NewConfiguration()
api_client := {{goImportAlias}}.NewAPIClient(configuration)
resp, r, err := api_client.{{classname}}.{{operationId}}(context.Background(), {{#requiredParams}}{{paramName}}{{^-last}}, {{/-last}}{{/requiredParams}}){{#optionalParams}}.{{{vendorExtensions.x-export-param-name}}}({{{paramName}}}){{/optionalParams}}.Execute()
if err != nil {
fmt.Fprintf(os.Stderr, "Error when calling `{{classname}}.{{operationId}}``: %v\n", err)
fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r)
}
{{#returnType}}
// response from `{{operationId}}`: {{{.}}}
fmt.Fprintf(os.Stdout, "Response from `{{classname}}.{{operationId}}`: %v\n", resp)
{{/returnType}}
}
```
### Path Parameters
{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#pathParams}}{{#-last}}
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc.{{/-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** | ***{{{nickname}}}Opts** | optional parameters | nil if no parameters
**ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc.{{/-last}}{{/pathParams}}{{#pathParams}}
**{{paramName}}** | {{^isPrimitiveType}}{{^isFile}}[{{/isFile}}{{/isPrimitiveType}}**{{dataType}}**{{^isPrimitiveType}}{{^isFile}}]({{baseType}}.md){{/isFile}}{{/isPrimitiveType}} | {{description}} | {{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}}{{/pathParams}}
### Optional Parameters
### Other Parameters
Optional parameters are passed through a pointer to a {{{nickname}}}Opts struct
Other parameters are passed through a pointer to a api{{{nickname}}}Request struct via the builder pattern
{{#allParams}}{{#-last}}
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}}{{#allParams}}
{{^required}} **{{paramName}}** | {{#isFile}}**optional.Interface of {{dataType}}**{{/isFile}}{{#isPrimitiveType}}**optional.{{vendorExtensions.x-optional-data-type}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{^isFile}}[**optional.Interface of {{dataType}}**]({{baseType}}.md){{/isFile}}{{/isPrimitiveType}}| {{description}} | {{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}}{{/required}}{{/allParams}}{{/hasOptionalParams}}
{{^isPathParam}} **{{paramName}}** | {{^isPrimitiveType}}{{^isFile}}[{{/isFile}}{{/isPrimitiveType}}**{{dataType}}**{{^isPrimitiveType}}{{^isFile}}]({{baseType}}.md){{/isFile}}{{/isPrimitiveType}} | {{description}} | {{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}}{{/isPathParam}}{{/allParams}}
### Return type

View File

@ -9,7 +9,6 @@ import (
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"mime/multipart"
"net/http"
@ -32,7 +31,7 @@ import (
)
var (
jsonCheck = regexp.MustCompile(`(?i:(?:application|text)/(?:vnd\.[^;]+\+)?(?:problem\+)?json)`)
jsonCheck = regexp.MustCompile(`(?i:(?:application|text)/(?:vnd\.[^;]+\+)?json)`)
xmlCheck = regexp.MustCompile(`(?i:(?:application|text)/xml)`)
)
@ -47,12 +46,12 @@ type APIClient struct {
{{#apis}}
{{#operations}}
{{#generateInterfaces}}
{{#generateInterfaces}}
{{classname}} {{classname}}
{{/generateInterfaces}}
{{^generateInterfaces}}
{{/generateInterfaces}}
{{^generateInterfaces}}
{{classname}} *{{classname}}Service
{{/generateInterfaces}}
{{/generateInterfaces}}
{{/operations}}
{{/apis}}
{{/apiInfo}}
@ -174,9 +173,9 @@ func parameterToJson(obj interface{}) (string, error) {
// callAPI do the request.
func (c *APIClient) callAPI(request *http.Request) (*http.Response, error) {
if c.cfg.Debug {
dump, err := httputil.DumpRequestOut(request, true)
dump, err := httputil.DumpRequestOut(request, true)
if err != nil {
return nil, err
return nil, err
}
log.Printf("\n%s\n", string(dump))
}
@ -193,15 +192,9 @@ func (c *APIClient) callAPI(request *http.Request) (*http.Response, error) {
}
log.Printf("\n%s\n", string(dump))
}
return resp, err
}
// ChangeBasePath changes base path to allow switching to mocks
func (c *APIClient) ChangeBasePath(path string) {
c.cfg.BasePath = path
}
// Allow modification of underlying config for alternate implementations and testing
// Caution: modifying the configuration while live can cause data races and potentially unwanted behavior
func (c *APIClient) GetConfig() *Configuration {
@ -386,7 +379,18 @@ func (c *APIClient) prepareRequest(
for header, value := range c.cfg.DefaultHeader {
localVarRequest.Header.Add(header, value)
}
{{#hasHttpSignatureMethods}}
if ctx != nil {
// HTTP Signature Authentication. All request headers must be set (including default headers)
// because the headers may be included in the signature.
if auth, ok := ctx.Value(ContextHttpSignatureAuth).(HttpSignatureAuth); ok {
err = SignRequest(ctx, localVarRequest, auth)
if err != nil {
return nil, err
}
}
}
{{/hasHttpSignatureMethods}}
return localVarRequest, nil
}
@ -398,15 +402,6 @@ func (c *APIClient) decode(v interface{}, b []byte, contentType string) (err err
*s = string(b)
return nil
}
if f, ok := v.(**os.File); ok {
*f, err = ioutil.TempFile("", "HttpClientFile")
if err != nil {
return
}
_, err = (*f).Write(b)
_, err = (*f).Seek(0, io.SeekStart)
return
}
if xmlCheck.MatchString(contentType) {
if err = xml.Unmarshal(b, v); err != nil {
return err
@ -414,7 +409,15 @@ func (c *APIClient) decode(v interface{}, b []byte, contentType string) (err err
return nil
}
if jsonCheck.MatchString(contentType) {
if err = json.Unmarshal(b, v); err != nil {
if actualObj, ok := v.(interface{GetActualInstance() interface{}}); ok { // oneOf, anyOf schemas
if unmarshalObj, ok := actualObj.(interface{UnmarshalJSON([]byte) error}); ok { // make sure it has UnmarshalJSON defined
if err = unmarshalObj.UnmarshalJSON(b); err!= nil {
return err
}
} else {
errors.New("Unknown type with GetActualInstance but no unmarshalObj.UnmarshalJSON defined")
}
} else if err = json.Unmarshal(b, v); err != nil { // simple model
return err
}
return nil

View File

@ -2,6 +2,7 @@
package {{packageName}}
import (
"context"
"fmt"
"net/http"
"strings"
@ -27,13 +28,28 @@ var (
// ContextAccessToken takes a string oauth2 access token as authentication for the request.
ContextAccessToken = contextKey("accesstoken")
// ContextAPIKey takes an APIKey as authentication for the request
ContextAPIKey = contextKey("apikey")
// ContextAPIKeys takes a string apikey as authentication for the request
ContextAPIKeys = contextKey("apiKeys")
{{#withAWSV4Signature}}
// ContextAWSv4 takes an Access Key and a Secret Key for signing AWS Signature v4.
// ContextAWSv4 takes an Access Key and a Secret Key for signing AWS Signature v4
ContextAWSv4 = contextKey("awsv4")
{{/withAWSV4Signature}}
// ContextHttpSignatureAuth takes HttpSignatureAuth as authentication for the request.
ContextHttpSignatureAuth = contextKey("httpsignature")
// ContextServerIndex uses a server configuration from the index.
ContextServerIndex = contextKey("serverIndex")
// ContextOperationServerIndices uses a server configuration from the index mapping.
ContextOperationServerIndices = contextKey("serverOperationIndices")
// ContextServerVariables overrides a server configuration variables.
ContextServerVariables = contextKey("serverVariables")
// ContextOperationServerVariables overrides a server configuration variables using operation specific values.
ContextOperationServerVariables = contextKey("serverOperationVariables")
)
// BasicAuth provides basic http authentication to a request passed via context using ContextBasicAuth
@ -52,11 +68,11 @@ type APIKey struct {
// AWSv4 provides AWS Signature to a request passed via context using ContextAWSv4
// https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html
type AWSv4 struct {
AccessKey string
SecretKey string
AccessKey string
SecretKey string
}
{{/withAWSV4Signature}}
{{/withAWSV4Signature}}
// ServerVariable stores the information about a server variable
type ServerVariable struct {
Description string
@ -66,36 +82,38 @@ type ServerVariable struct {
// ServerConfiguration stores the information about a server
type ServerConfiguration struct {
Url string
URL string
Description string
Variables map[string]ServerVariable
}
// ServerConfigurations stores multiple ServerConfiguration items
type ServerConfigurations []ServerConfiguration
// Configuration stores the configuration of the API client
type Configuration struct {
BasePath string `json:"basePath,omitempty"`
Host string `json:"host,omitempty"`
Scheme string `json:"scheme,omitempty"`
DefaultHeader map[string]string `json:"defaultHeader,omitempty"`
UserAgent string `json:"userAgent,omitempty"`
Debug bool `json:"debug,omitempty"`
Servers []ServerConfiguration
HTTPClient *http.Client
Host string `json:"host,omitempty"`
Scheme string `json:"scheme,omitempty"`
DefaultHeader map[string]string `json:"defaultHeader,omitempty"`
UserAgent string `json:"userAgent,omitempty"`
Debug bool `json:"debug,omitempty"`
Servers ServerConfigurations
OperationServers map[string]ServerConfigurations
HTTPClient *http.Client
}
// NewConfiguration returns a new Configuration object
func NewConfiguration() *Configuration {
cfg := &Configuration{
BasePath: "{{{basePath}}}",
DefaultHeader: make(map[string]string),
UserAgent: "{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}OpenAPI-Generator/{{{packageVersion}}}/go{{/httpUserAgent}}",
Debug: false,
DefaultHeader: make(map[string]string),
UserAgent: "{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}OpenAPI-Generator/{{{packageVersion}}}/go{{/httpUserAgent}}",
Debug: false,
{{#servers}}
{{#-first}}
Servers: []ServerConfiguration{
Servers: ServerConfigurations{
{{/-first}}
{
Url: "{{{url}}}",
URL: "{{{url}}}",
Description: "{{{description}}}{{^description}}No description provided{{/description}}",
{{#variables}}
{{#-first}}
@ -123,6 +141,49 @@ func NewConfiguration() *Configuration {
},
{{/-last}}
{{/servers}}
{{#apiInfo}}
OperationServers: map[string]ServerConfigurations{
{{#apis}}
{{#operations}}
{{#operation}}
{{#servers}}
{{#-first}}
"{{{classname}}}Service.{{{nickname}}}": {
{{/-first}}
{
URL: "{{{url}}}",
Description: "{{{description}}}{{^description}}No description provided{{/description}}",
{{#variables}}
{{#-first}}
Variables: map[string]ServerVariable{
{{/-first}}
"{{{name}}}": ServerVariable{
Description: "{{{description}}}{{^description}}No description provided{{/description}}",
DefaultValue: "{{{defaultValue}}}",
{{#enumValues}}
{{#-first}}
EnumValues: []string{
{{/-first}}
"{{{.}}}",
{{#-last}}
},
{{/-last}}
{{/enumValues}}
},
{{#-last}}
},
{{/-last}}
{{/variables}}
},
{{#-last}}
},
{{/-last}}
{{/servers}}
{{/operation}}
{{/operations}}
{{/apis}}
},
{{/apiInfo}}
}
return cfg
}
@ -132,13 +193,13 @@ func (c *Configuration) AddDefaultHeader(key string, value string) {
c.DefaultHeader[key] = value
}
// ServerUrl returns URL based on server settings
func (c *Configuration) ServerUrl(index int, variables map[string]string) (string, error) {
if index < 0 || len(c.Servers) <= index {
return "", fmt.Errorf("Index %v out of range %v", index, len(c.Servers) - 1)
// URL formats template on a index using given variables
func (sc ServerConfigurations) URL(index int, variables map[string]string) (string, error) {
if index < 0 || len(sc) <= index {
return "", fmt.Errorf("Index %v out of range %v", index, len(sc)-1)
}
server := c.Servers[index]
url := server.Url
server := sc[index]
url := server.URL
// go through variables and replace placeholders
for name, variable := range server.Variables {
@ -159,3 +220,84 @@ func (c *Configuration) ServerUrl(index int, variables map[string]string) (strin
}
return url, nil
}
// ServerURL returns URL based on server settings
func (c *Configuration) ServerURL(index int, variables map[string]string) (string, error) {
return c.Servers.URL(index, variables)
}
func getServerIndex(ctx context.Context) (int, error) {
si := ctx.Value(ContextServerIndex)
if si != nil {
if index, ok := si.(int); ok {
return index, nil
}
return 0, reportError("Invalid type %T should be int", si)
}
return 0, nil
}
func getServerOperationIndex(ctx context.Context, endpoint string) (int, error) {
osi := ctx.Value(ContextOperationServerIndices)
if osi != nil {
if operationIndices, ok := osi.(map[string]int); !ok {
return 0, reportError("Invalid type %T should be map[string]int", osi)
} else {
index, ok := operationIndices[endpoint]
if ok {
return index, nil
}
}
}
return getServerIndex(ctx)
}
func getServerVariables(ctx context.Context) (map[string]string, error) {
sv := ctx.Value(ContextServerVariables)
if sv != nil {
if variables, ok := sv.(map[string]string); ok {
return variables, nil
}
return nil, reportError("ctx value of ContextServerVariables has invalid type %T should be map[string]string", sv)
}
return nil, nil
}
func getServerOperationVariables(ctx context.Context, endpoint string) (map[string]string, error) {
osv := ctx.Value(ContextOperationServerVariables)
if osv != nil {
if operationVariables, ok := osv.(map[string]map[string]string); !ok {
return nil, reportError("ctx value of ContextOperationServerVariables has invalid type %T should be map[string]map[string]string", osv)
} else {
variables, ok := operationVariables[endpoint]
if ok {
return variables, nil
}
}
}
return getServerVariables(ctx)
}
// ServerURLWithContext returns a new server URL given an endpoint
func (c *Configuration) ServerURLWithContext(ctx context.Context, endpoint string) (string, error) {
sc, ok := c.OperationServers[endpoint]
if !ok {
sc = c.Servers
}
if ctx == nil {
return sc.URL(0, nil)
}
index, err := getServerOperationIndex(ctx, endpoint)
if err != nil {
return "", err
}
variables, err := getServerOperationVariables(ctx, endpoint)
if err != nil {
return "", err
}
return sc.URL(index, variables)
}

View File

@ -1,7 +1,8 @@
module {{gitHost}}/{{gitUserId}}/{{gitRepoId}}{{#isGoSubmodule}}/{{packageName}}{{/isGoSubmodule}}
go 1.13
require (
github.com/antihax/optional v1.0.0
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45
{{#withAWSV4Signature}}
github.com/aws/aws-sdk-go v1.34.14

View File

@ -1,8 +1,6 @@
cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
github.com/antihax/optional v1.0.0 h1:xK2lYat7ZLaVVcIuj82J8kIro4V6kDe0AUDFboUCwcg=
github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY=
github.com/aws/aws-sdk-go v1.26.3 h1:szQdfJcUBAhQT0zZEx4sxoDuWb7iScoucxCiVxDmaBk=
github.com/aws/aws-sdk-go v1.26.3/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo=
github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=

View File

@ -1,43 +1,20 @@
{{>partial_header}}
package {{packageName}}
{{#models}}
{{#imports}}
{{#-first}}
import (
{{/-first}}
"encoding/json"
{{#imports}}
"{{import}}"
{{#-last}}
)
{{/-last}}
{{/imports}}
)
{{#model}}
{{#isEnum}}
// {{{classname}}} {{#description}}{{{.}}}{{/description}}{{^description}}the model '{{{classname}}}'{{/description}}
type {{{classname}}} {{^format}}{{dataType}}{{/format}}{{#format}}{{{format}}}{{/format}}
// List of {{{name}}}
const (
{{#allowableValues}}
{{#enumVars}}
{{^-first}}
{{/-first}}
{{#enumClassPrefix}}{{{classname.toUpperCase}}}_{{/enumClassPrefix}}{{name}} {{{classname}}} = {{{value}}}
{{/enumVars}}
{{/allowableValues}}
)
{{>model_enum}}
{{/isEnum}}
{{^isEnum}}
// {{classname}}{{#description}} {{{description}}}{{/description}}{{^description}} struct for {{{classname}}}{{/description}}
type {{classname}} struct {
{{#allVars}}
{{^-first}}
{{/-first}}
{{#description}}
// {{{description}}}
{{/description}}
{{name}} {{#isNullable}}*{{/isNullable}}{{{dataType}}} `json:"{{baseName}}{{^required}},omitempty{{/required}}"{{#withXml}} xml:"{{baseName}}{{#isXmlAttribute}},attr{{/isXmlAttribute}}"{{/withXml}}{{#vendorExtensions.x-go-custom-tag}} {{{.}}}{{/vendorExtensions.x-go-custom-tag}}`
{{/allVars}}
}
{{#oneOf}}{{#-first}}{{>model_oneof}}{{/-first}}{{/oneOf}}{{^oneOf}}{{#anyOf}}{{#-first}}{{>model_anyof}}{{/-first}}{{/anyOf}}{{^anyOf}}{{>model_simple}}{{/anyOf}}{{/oneOf}}
{{/isEnum}}
{{/model}}
{{/models}}

View File

@ -4,8 +4,86 @@
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
{{#allVars}}**{{name}}** | {{#isNullable}}Pointer to {{/isNullable}}{{#isPrimitiveType}}**{{{dataType}}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{{dataType}}}**]({{complexType}}.md){{/isPrimitiveType}} | {{description}} | {{^required}}[optional] {{/required}}{{#isReadOnly}}[readonly] {{/isReadOnly}}{{#defaultValue}}[default to {{{.}}}]{{/defaultValue}}
{{/allVars}}
{{#vendorExtensions.x-is-one-of-interface}}
**{{classname}}Interface** | **interface { {{#discriminator}}{{propertyGetter}}() {{propertyType}}{{/discriminator}} }** | An interface that can hold any of the proper implementing types |
{{/vendorExtensions.x-is-one-of-interface}}
{{^vendorExtensions.x-is-one-of-interface}}
{{#vars}}**{{name}}** | {{^required}}Pointer to {{/required}}{{#isPrimitiveType}}**{{{dataType}}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{{dataType}}}**]({{complexType}}.md){{/isPrimitiveType}} | {{description}} | {{^required}}[optional] {{/required}}{{#isReadOnly}}[readonly] {{/isReadOnly}}{{#defaultValue}}[default to {{{.}}}]{{/defaultValue}}
{{/vars}}
{{/vendorExtensions.x-is-one-of-interface}}
{{^isEnum}}
## Methods
{{^vendorExtensions.x-is-one-of-interface}}
### New{{classname}}
`func New{{classname}}({{#vars}}{{#required}}{{nameInCamelCase}} {{dataType}}, {{/required}}{{/vars}}) *{{classname}}`
New{{classname}} instantiates a new {{classname}} object
This constructor will assign default values to properties that have it defined,
and makes sure properties required by API are set, but the set of arguments
will change when the set of required properties is changed
### New{{classname}}WithDefaults
`func New{{classname}}WithDefaults() *{{classname}}`
New{{classname}}WithDefaults instantiates a new {{classname}} object
This constructor will only assign default values to properties that have it defined,
but it doesn't guarantee that properties required by API are set
{{#vars}}
### Get{{name}}
`func (o *{{classname}}) Get{{name}}() {{vendorExtensions.x-go-base-type}}`
Get{{name}} returns the {{name}} field if non-nil, zero value otherwise.
### Get{{name}}Ok
`func (o *{{classname}}) Get{{name}}Ok() (*{{vendorExtensions.x-go-base-type}}, bool)`
Get{{name}}Ok returns a tuple with the {{name}} field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### Set{{name}}
`func (o *{{classname}}) Set{{name}}(v {{vendorExtensions.x-go-base-type}})`
Set{{name}} sets {{name}} field to given value.
{{^required}}
### Has{{name}}
`func (o *{{classname}}) Has{{name}}() bool`
Has{{name}} returns a boolean if a field has been set.
{{/required}}
{{#isNullable}}
### Set{{name}}Nil
`func (o *{{classname}}) Set{{name}}Nil(b bool)`
Set{{name}}Nil sets the value for {{name}} to be an explicit nil
### Unset{{name}}
`func (o *{{classname}}) Unset{{name}}()`
Unset{{name}} ensures that no value is present for {{name}}, not even an explicit nil
{{/isNullable}}
{{/vars}}
{{#vendorExtensions.x-implements}}
### As{{{.}}}
`func (s *{{classname}}) As{{{.}}}() {{{.}}}`
Convenience method to wrap this instance of {{classname}} in {{{.}}}
{{/vendorExtensions.x-implements}}
{{/vendorExtensions.x-is-one-of-interface}}
{{/isEnum}}
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -23,7 +23,7 @@ import org.openapitools.codegen.CodegenConstants;
import org.openapitools.codegen.CodegenOperation;
import org.openapitools.codegen.CodegenParameter;
import org.openapitools.codegen.TestUtils;
import org.openapitools.codegen.languages.GoClientCodegen;
import org.openapitools.codegen.languages.GoDeprecatedClientCodegen;
import org.testng.Assert;
import org.testng.annotations.Test;
@ -31,7 +31,7 @@ public class GoClientCodegenTest {
@Test
public void testInitialConfigValues() throws Exception {
final GoClientCodegen codegen = new GoClientCodegen();
final GoDeprecatedClientCodegen codegen = new GoDeprecatedClientCodegen();
codegen.processOpts();
Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.TRUE);
@ -40,7 +40,7 @@ public class GoClientCodegenTest {
@Test
public void testSettersForConfigValues() throws Exception {
final GoClientCodegen codegen = new GoClientCodegen();
final GoDeprecatedClientCodegen codegen = new GoDeprecatedClientCodegen();
codegen.setHideGenerationTimestamp(false);
codegen.processOpts();
@ -50,7 +50,7 @@ public class GoClientCodegenTest {
@Test
public void testAdditionalPropertiesPutForConfigValues() throws Exception {
final GoClientCodegen codegen = new GoClientCodegen();
final GoDeprecatedClientCodegen codegen = new GoDeprecatedClientCodegen();
codegen.additionalProperties().put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, false);
codegen.processOpts();
@ -61,7 +61,7 @@ public class GoClientCodegenTest {
@Test(description = "test example value for body parameter")
public void bodyParameterTest() {
final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml");
final GoClientCodegen codegen = new GoClientCodegen();
final GoDeprecatedClientCodegen codegen = new GoDeprecatedClientCodegen();
codegen.setOpenAPI(openAPI);
final String path = "/fake";
final Operation p = openAPI.getPaths().get(path).getGet();
@ -73,7 +73,7 @@ public class GoClientCodegenTest {
@Test
public void testFilenames() throws Exception {
final GoClientCodegen codegen = new GoClientCodegen();
final GoDeprecatedClientCodegen codegen = new GoDeprecatedClientCodegen();
// Model names are generated from schema / definition names
Assert.assertEquals(codegen.toModelFilename("Animal"), "model_animal");

View File

@ -19,7 +19,7 @@ package org.openapitools.codegen.go;
import org.openapitools.codegen.AbstractOptionsTest;
import org.openapitools.codegen.CodegenConfig;
import org.openapitools.codegen.languages.GoClientCodegen;
import org.openapitools.codegen.languages.GoDeprecatedClientCodegen;
import org.openapitools.codegen.options.GoClientOptionsProvider;
import static org.mockito.Mockito.mock;
@ -27,7 +27,7 @@ import static org.mockito.Mockito.verify;
public class GoClientOptionsTest extends AbstractOptionsTest {
private GoClientCodegen clientCodegen = mock(GoClientCodegen.class, mockSettings);
private GoDeprecatedClientCodegen clientCodegen = mock(GoDeprecatedClientCodegen.class, mockSettings);
public GoClientOptionsTest() {
super(new GoClientOptionsProvider());

View File

@ -25,7 +25,7 @@ import org.openapitools.codegen.CodegenModel;
import org.openapitools.codegen.CodegenProperty;
import org.openapitools.codegen.DefaultCodegen;
import org.openapitools.codegen.TestUtils;
import org.openapitools.codegen.languages.GoClientCodegen;
import org.openapitools.codegen.languages.GoDeprecatedClientCodegen;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
@ -42,7 +42,7 @@ public class GoModelTest {
.addProperties("createdAt", new DateTimeSchema())
.addRequiredItem("id")
.addRequiredItem("name");
final DefaultCodegen codegen = new GoClientCodegen();
final DefaultCodegen codegen = new GoDeprecatedClientCodegen();
OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model);
codegen.setOpenAPI(openAPI);
final CodegenModel cm = codegen.fromModel("sample", model);
@ -92,7 +92,7 @@ public class GoModelTest {
.addProperties("urls", new ArraySchema()
.items(new StringSchema()))
.addRequiredItem("id");
final DefaultCodegen codegen = new GoClientCodegen();
final DefaultCodegen codegen = new GoDeprecatedClientCodegen();
OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model);
codegen.setOpenAPI(openAPI);
final CodegenModel cm = codegen.fromModel("sample", model);
@ -130,7 +130,7 @@ public class GoModelTest {
.addProperties("translations", new MapSchema()
.additionalProperties(new StringSchema()))
.addRequiredItem("id");
final DefaultCodegen codegen = new GoClientCodegen();
final DefaultCodegen codegen = new GoDeprecatedClientCodegen();
OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model);
codegen.setOpenAPI(openAPI);
final CodegenModel cm = codegen.fromModel("sample", model);
@ -156,7 +156,7 @@ public class GoModelTest {
final Schema model = new Schema()
.description("a sample model")
.addProperties("children", new Schema().$ref("#/definitions/Children"));
final DefaultCodegen codegen = new GoClientCodegen();
final DefaultCodegen codegen = new GoDeprecatedClientCodegen();
OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model);
codegen.setOpenAPI(openAPI);
final CodegenModel cm = codegen.fromModel("sample", model);
@ -180,7 +180,7 @@ public class GoModelTest {
.description("a sample model")
.addProperties("children", new ArraySchema()
.items(new Schema().$ref("#/definitions/Children")));
final DefaultCodegen codegen = new GoClientCodegen();
final DefaultCodegen codegen = new GoDeprecatedClientCodegen();
OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model);
codegen.setOpenAPI(openAPI);
final CodegenModel cm = codegen.fromModel("sample", model);
@ -206,7 +206,7 @@ public class GoModelTest {
.description("a sample model")
.addProperties("children", new MapSchema()
.additionalProperties(new Schema().$ref("#/definitions/Children")));
final DefaultCodegen codegen = new GoClientCodegen();
final DefaultCodegen codegen = new GoDeprecatedClientCodegen();
OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model);
codegen.setOpenAPI(openAPI);
final CodegenModel cm = codegen.fromModel("sample", model);
@ -233,7 +233,7 @@ public class GoModelTest {
final Schema model = new ArraySchema()
.items(new Schema().$ref("#/definitions/Children"))
.description("an array model");
final DefaultCodegen codegen = new GoClientCodegen();
final DefaultCodegen codegen = new GoDeprecatedClientCodegen();
OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model);
codegen.setOpenAPI(openAPI);
final CodegenModel cm = codegen.fromModel("sample", model);
@ -250,7 +250,7 @@ public class GoModelTest {
final Schema model = new Schema()
.additionalProperties(new Schema().$ref("#/definitions/Children"))
.description("a map model");
final DefaultCodegen codegen = new GoClientCodegen();
final DefaultCodegen codegen = new GoDeprecatedClientCodegen();
OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model);
codegen.setOpenAPI(openAPI);
final CodegenModel cm = codegen.fromModel("sample", model);
@ -265,7 +265,7 @@ public class GoModelTest {
@Test(description = "convert file type and file schema models")
public void filePropertyTest() {
final DefaultCodegen codegen = new GoClientCodegen();
final DefaultCodegen codegen = new GoDeprecatedClientCodegen();
final Schema model1 = new Schema().type("file");
Assert.assertEquals(codegen.getSchemaType(model1), "*os.File");
Assert.assertEquals(codegen.getTypeDeclaration(model1), "*os.File");
@ -295,7 +295,7 @@ public class GoModelTest {
@Test(dataProvider = "modelNames", description = "avoid inner class")
public void modelNameTest(String name, String expectedName) {
final Schema model = new Schema();
final DefaultCodegen codegen = new GoClientCodegen();
final DefaultCodegen codegen = new GoDeprecatedClientCodegen();
OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema(name, model);
codegen.setOpenAPI(openAPI);
final CodegenModel cm = codegen.fromModel(name, model);

View File

@ -1,9 +1,8 @@
package org.openapitools.codegen.utils;
import org.openapitools.codegen.CodegenConfig;
import org.openapitools.codegen.CodegenModel;
import org.openapitools.codegen.CodegenProperty;
import org.openapitools.codegen.languages.GoClientExperimentalCodegen;
import org.openapitools.codegen.languages.GoClientCodegen;
import org.testng.Assert;
import org.testng.annotations.Test;
@ -47,7 +46,7 @@ public class OneOfImplementorAdditionalDataTest {
cp3.hasMore = false;
implModel.vars.add(cp3);
List<Map<String, String>> implModelImports = new ArrayList<>();
GoClientExperimentalCodegen cc = new GoClientExperimentalCodegen();
GoClientCodegen cc = new GoClientCodegen();
cc.setModelPackage("openapi");
o.addToImplementor(cc, implModel, implModelImports, false);

View File

@ -1331,8 +1331,6 @@
<module>samples/client/petstore/groovy</module>
<!-- test non-java projects -->
<module>samples/client/petstore/go</module>
<module>samples/client/petstore/go-experimental</module>
<module>samples/openapi3/client/petstore/go-experimental</module>
<module>samples/openapi3/client/petstore/go</module>
<module>samples/client/petstore/javascript-es6</module>
<module>samples/client/petstore/javascript-promise-es6</module>

View File

@ -1,259 +0,0 @@
package main
import (
"context"
"net/http"
"net/http/httputil"
"strings"
"testing"
"time"
"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(context.Background(), sw.ContextOAuth2, tokenSource)
newPet := (sw.Pet{Id: sw.PtrInt64(12992), Name: "gopher",
PhotoUrls: []string{"http://1.com", "http://2.com"}, Status: sw.PtrString("pending"),
Tags: &[]sw.Tag{sw.Tag{Id: sw.PtrInt64(1), Name: sw.PtrString("tag2")}}})
r, err := client.PetApi.AddPet(context.Background()).Body(newPet).Execute()
if err != nil {
t.Fatalf("Error while adding pet: %v", err)
}
if r.StatusCode != 200 {
t.Log(r)
}
r, err = client.PetApi.DeletePet(auth, 12992).Execute()
if err != nil {
t.Fatalf("Error while deleting pet by id: %v", err)
}
if r.StatusCode != 200 {
t.Log(r)
}
reqb, _ := 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.Background(), sw.ContextBasicAuth, sw.BasicAuth{
UserName: "fakeUser",
Password: "f4k3p455",
})
newPet := (sw.Pet{Id: sw.PtrInt64(12992), Name: "gopher",
PhotoUrls: []string{"http://1.com", "http://2.com"}, Status: sw.PtrString("pending"),
Tags: &[]sw.Tag{sw.Tag{Id: sw.PtrInt64(1), Name: sw.PtrString("tag2")}}})
r, err := client.PetApi.AddPet(auth).Body(newPet).Execute()
if err != nil {
t.Fatalf("Error while adding pet: %v", err)
}
if r.StatusCode != 200 {
t.Log(r)
}
r, err = client.PetApi.DeletePet(auth, 12992).Execute()
if err != nil {
t.Fatalf("Error while deleting pet by id: %v", err)
}
if r.StatusCode != 200 {
t.Log(r)
}
reqb, _ := 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.Background(), sw.ContextAccessToken, "TESTFAKEACCESSTOKENISFAKE")
newPet := (sw.Pet{Id: sw.PtrInt64(12992), Name: "gopher",
PhotoUrls: []string{"http://1.com", "http://2.com"}, Status: sw.PtrString("pending"),
Tags: &[]sw.Tag{sw.Tag{Id: sw.PtrInt64(1), Name: sw.PtrString("tag2")}}})
r, err := client.PetApi.AddPet(nil).Body(newPet).Execute()
if err != nil {
t.Fatalf("Error while adding pet: %v", err)
}
if r.StatusCode != 200 {
t.Log(r)
}
r, err = client.PetApi.DeletePet(auth, 12992).Execute()
if err != nil {
t.Fatalf("Error while deleting pet by id: %v", err)
}
if r.StatusCode != 200 {
t.Log(r)
}
reqb, _ := 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.Background(), sw.ContextAPIKeys, map[string]sw.APIKey{"api_key": sw.APIKey{Key: "TEST123"}})
newPet := (sw.Pet{Id: sw.PtrInt64(12992), Name: "gopher",
PhotoUrls: []string{"http://1.com", "http://2.com"}, Status: sw.PtrString("pending"),
Tags: &[]sw.Tag{sw.Tag{Id: sw.PtrInt64(1), Name: sw.PtrString("tag2")}}})
r, err := client.PetApi.AddPet(context.Background()).Body(newPet).Execute()
if err != nil {
t.Fatalf("Error while adding pet: %v", err)
}
if r.StatusCode != 200 {
t.Log(r)
}
_, r, err = client.PetApi.GetPetById(auth, 12992).Execute()
if err != nil {
t.Fatalf("Error while deleting pet by id: %v", err)
}
reqb, _ := 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).Execute()
if err != nil {
t.Fatalf("Error while deleting pet by id: %v", err)
}
if r.StatusCode != 200 {
t.Log(r)
}
}
func TestAPIKeyWithPrefix(t *testing.T) {
auth := context.WithValue(context.Background(), sw.ContextAPIKeys, map[string]sw.APIKey{"api_key": sw.APIKey{Key: "TEST123", Prefix: "Bearer"}})
newPet := (sw.Pet{Id: sw.PtrInt64(12992), Name: "gopher",
PhotoUrls: []string{"http://1.com", "http://2.com"}, Status: sw.PtrString("pending"),
Tags: &[]sw.Tag{sw.Tag{Id: sw.PtrInt64(1), Name: sw.PtrString("tag2")}}})
r, err := client.PetApi.AddPet(nil).Body(newPet).Execute()
if err != nil {
t.Fatalf("Error while adding pet: %v", err)
}
if r.StatusCode != 200 {
t.Log(r)
}
_, r, err = client.PetApi.GetPetById(auth, 12992).Execute()
if err != nil {
t.Fatalf("Error while deleting pet by id: %v", err)
}
reqb, _ := 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).Execute()
if err != nil {
t.Fatalf("Error while deleting pet by id: %v", err)
}
if r.StatusCode != 200 {
t.Log(r)
}
}
func TestDefaultHeader(t *testing.T) {
newPet := (sw.Pet{Id: sw.PtrInt64(12992), Name: "gopher",
PhotoUrls: []string{"http://1.com", "http://2.com"}, Status: sw.PtrString("pending"),
Tags: &[]sw.Tag{sw.Tag{Id: sw.PtrInt64(1), Name: sw.PtrString("tag2")}}})
r, err := client.PetApi.AddPet(context.Background()).Body(newPet).Execute()
if err != nil {
t.Fatalf("Error while adding pet: %v", err)
}
if r.StatusCode != 200 {
t.Log(r)
}
r, err = client.PetApi.DeletePet(context.Background(), 12992).Execute()
if err != nil {
t.Fatalf("Error while deleting pet by id: %v", err)
}
if r.StatusCode != 200 {
t.Log(r)
}
reqb, _ := httputil.DumpRequest(r.Request, true)
if !strings.Contains((string)(reqb), "Testheader: testvalue") {
t.Errorf("Default Header is missing")
}
}
func TestHostOverride(t *testing.T) {
_, r, err := client.PetApi.FindPetsByStatus(context.Background()).Status(nil).Execute()
if err != nil {
t.Fatalf("Error while finding pets by status: %v", err)
}
if r.Request.URL.Host != testHost {
t.Errorf("Request Host is %v, expected %v", r.Request.Host, testHost)
}
}
func TestSchemeOverride(t *testing.T) {
_, r, err := client.PetApi.FindPetsByStatus(context.Background()).Status(nil).Execute()
if err != nil {
t.Fatalf("Error while finding pets by status: %v", err)
}
if r.Request.URL.Scheme != testScheme {
t.Errorf("Request Scheme is %v, expected %v", r.Request.URL.Scheme, testScheme)
}
}
// 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
}

View File

@ -1,28 +0,0 @@
package main
import (
"context"
"testing"
sw "./go-petstore"
)
// TestPutBodyWithFileSchema ensures a model with the name 'File'
// gets converted properly to the petstore.File struct vs. *os.File
// as specified in typeMapping for 'File'.
func TestPutBodyWithFileSchema(t *testing.T) {
return // early return to test compilation
schema := sw.FileSchemaTestClass{
File: &sw.File{SourceURI: sw.PtrString("https://example.com/image.png")},
Files: &[]sw.File{{SourceURI: sw.PtrString("https://example.com/image.png")}}}
r, err := client.FakeApi.TestBodyWithFileSchema(context.Background()).Body(schema).Execute()
if err != nil {
t.Fatalf("Error while adding pet: %v", err)
}
if r.StatusCode != 200 {
t.Log(r)
}
}

View File

@ -1,24 +0,0 @@
# Compiled Object files, Static and Dynamic libs (Shared Objects)
*.o
*.a
*.so
# Folders
_obj
_test
# Architecture specific extensions/prefixes
*.[568vq]
[568vq].out
*.cgo1.go
*.cgo2.c
_cgo_defun.c
_cgo_gotypes.go
_cgo_export.*
_testmain.go
*.exe
*.test
*.prof

View File

@ -1,23 +0,0 @@
# OpenAPI Generator Ignore
# Generated by openapi-generator https://github.com/openapitools/openapi-generator
# Use this file to prevent files from being overwritten by the generator.
# The patterns follow closely to .gitignore or .dockerignore.
# As an example, the C# client generator defines ApiClient.cs.
# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line:
#ApiClient.cs
# You can match any string of characters against a directory, file or extension with a single asterisk (*):
#foo/*/qux
# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux
# You can recursively match patterns against a directory, file or extension with a double asterisk (**):
#foo/**/qux
# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux
# You can also negate patterns with an exclamation (!).
# For example, you can ignore all files in a docs folder with the file extension .md:
#docs/*.md
# Then explicitly reverse the ignore rule for a single file:
#!docs/README.md

View File

@ -1,119 +0,0 @@
.gitignore
.travis.yml
README.md
api/openapi.yaml
api_another_fake.go
api_fake.go
api_fake_classname_tags123.go
api_pet.go
api_store.go
api_user.go
client.go
configuration.go
docs/AdditionalPropertiesAnyType.md
docs/AdditionalPropertiesArray.md
docs/AdditionalPropertiesBoolean.md
docs/AdditionalPropertiesClass.md
docs/AdditionalPropertiesInteger.md
docs/AdditionalPropertiesNumber.md
docs/AdditionalPropertiesObject.md
docs/AdditionalPropertiesString.md
docs/Animal.md
docs/AnotherFakeApi.md
docs/ApiResponse.md
docs/ArrayOfArrayOfNumberOnly.md
docs/ArrayOfNumberOnly.md
docs/ArrayTest.md
docs/BigCat.md
docs/BigCatAllOf.md
docs/Capitalization.md
docs/Cat.md
docs/CatAllOf.md
docs/Category.md
docs/ClassModel.md
docs/Client.md
docs/Dog.md
docs/DogAllOf.md
docs/EnumArrays.md
docs/EnumClass.md
docs/EnumTest.md
docs/FakeApi.md
docs/FakeClassnameTags123Api.md
docs/File.md
docs/FileSchemaTestClass.md
docs/FormatTest.md
docs/HasOnlyReadOnly.md
docs/List.md
docs/MapTest.md
docs/MixedPropertiesAndAdditionalPropertiesClass.md
docs/Model200Response.md
docs/Name.md
docs/NumberOnly.md
docs/Order.md
docs/OuterComposite.md
docs/OuterEnum.md
docs/Pet.md
docs/PetApi.md
docs/ReadOnlyFirst.md
docs/Return.md
docs/SpecialModelName.md
docs/StoreApi.md
docs/Tag.md
docs/TypeHolderDefault.md
docs/TypeHolderExample.md
docs/User.md
docs/UserApi.md
docs/XmlItem.md
git_push.sh
go.mod
go.sum
model_200_response.go
model_additional_properties_any_type.go
model_additional_properties_array.go
model_additional_properties_boolean.go
model_additional_properties_class.go
model_additional_properties_integer.go
model_additional_properties_number.go
model_additional_properties_object.go
model_additional_properties_string.go
model_animal.go
model_api_response.go
model_array_of_array_of_number_only.go
model_array_of_number_only.go
model_array_test_.go
model_big_cat.go
model_big_cat_all_of.go
model_capitalization.go
model_cat.go
model_cat_all_of.go
model_category.go
model_class_model.go
model_client.go
model_dog.go
model_dog_all_of.go
model_enum_arrays.go
model_enum_class.go
model_enum_test_.go
model_file.go
model_file_schema_test_class.go
model_format_test_.go
model_has_only_read_only.go
model_list.go
model_map_test_.go
model_mixed_properties_and_additional_properties_class.go
model_name.go
model_number_only.go
model_order.go
model_outer_composite.go
model_outer_enum.go
model_pet.go
model_read_only_first.go
model_return.go
model_special_model_name.go
model_tag.go
model_type_holder_default.go
model_type_holder_example.go
model_user.go
model_xml_item.go
response.go
utils.go

View File

@ -1,8 +0,0 @@
language: go
install:
- go get -d -v .
script:
- go build -v ./

View File

@ -1,252 +0,0 @@
# Go API client for petstore
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
## Overview
This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [OpenAPI-spec](https://www.openapis.org/) from a remote server, you can easily generate an API client.
- API version: 1.0.0
- Package version: 1.0.0
- Build package: org.openapitools.codegen.languages.GoClientExperimentalCodegen
## Installation
Install the following dependencies:
```shell
go get github.com/stretchr/testify/assert
go get golang.org/x/oauth2
go get golang.org/x/net/context
```
Put the package under your project folder and add the following in import:
```golang
import sw "./petstore"
```
## Configuration of Server URL
Default configuration comes with `Servers` field that contains server objects as defined in the OpenAPI specification.
### Select Server Configuration
For using other server than the one defined on index 0 set context value `sw.ContextServerIndex` of type `int`.
```golang
ctx := context.WithValue(context.Background(), sw.ContextServerIndex, 1)
```
### Templated Server URL
Templated server URL is formatted using default variables from configuration or from context value `sw.ContextServerVariables` of type `map[string]string`.
```golang
ctx := context.WithValue(context.Background(), sw.ContextServerVariables, map[string]string{
"basePath": "v2",
})
```
Note, enum values are always validated and all unused variables are silently ignored.
### URLs Configuration per Operation
Each operation can use different server URL defined using `OperationServers` map in the `Configuration`.
An operation is uniquely identifield by `"{classname}Service.{nickname}"` string.
Similar rules for overriding default operation server index and variables applies by using `sw.ContextOperationServerIndices` and `sw.ContextOperationServerVariables` context maps.
```
ctx := context.WithValue(context.Background(), sw.ContextOperationServerIndices, map[string]int{
"{classname}Service.{nickname}": 2,
})
ctx = context.WithValue(context.Background(), sw.ContextOperationServerVariables, map[string]map[string]string{
"{classname}Service.{nickname}": {
"port": "8443",
},
})
```
## Documentation for API Endpoints
All URIs are relative to *http://petstore.swagger.io:80/v2*
Class | Method | HTTP request | Description
------------ | ------------- | ------------- | -------------
*AnotherFakeApi* | [**Call123TestSpecialTags**](docs/AnotherFakeApi.md#call123testspecialtags) | **Patch** /another-fake/dummy | To test special tags
*FakeApi* | [**CreateXmlItem**](docs/FakeApi.md#createxmlitem) | **Post** /fake/create_xml_item | creates an XmlItem
*FakeApi* | [**FakeOuterBooleanSerialize**](docs/FakeApi.md#fakeouterbooleanserialize) | **Post** /fake/outer/boolean |
*FakeApi* | [**FakeOuterCompositeSerialize**](docs/FakeApi.md#fakeoutercompositeserialize) | **Post** /fake/outer/composite |
*FakeApi* | [**FakeOuterNumberSerialize**](docs/FakeApi.md#fakeouternumberserialize) | **Post** /fake/outer/number |
*FakeApi* | [**FakeOuterStringSerialize**](docs/FakeApi.md#fakeouterstringserialize) | **Post** /fake/outer/string |
*FakeApi* | [**TestBodyWithFileSchema**](docs/FakeApi.md#testbodywithfileschema) | **Put** /fake/body-with-file-schema |
*FakeApi* | [**TestBodyWithQueryParams**](docs/FakeApi.md#testbodywithqueryparams) | **Put** /fake/body-with-query-params |
*FakeApi* | [**TestClientModel**](docs/FakeApi.md#testclientmodel) | **Patch** /fake | To test \&quot;client\&quot; model
*FakeApi* | [**TestEndpointParameters**](docs/FakeApi.md#testendpointparameters) | **Post** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트
*FakeApi* | [**TestEnumParameters**](docs/FakeApi.md#testenumparameters) | **Get** /fake | To test enum parameters
*FakeApi* | [**TestGroupParameters**](docs/FakeApi.md#testgroupparameters) | **Delete** /fake | Fake endpoint to test group parameters (optional)
*FakeApi* | [**TestInlineAdditionalProperties**](docs/FakeApi.md#testinlineadditionalproperties) | **Post** /fake/inline-additionalProperties | test inline additionalProperties
*FakeApi* | [**TestJsonFormData**](docs/FakeApi.md#testjsonformdata) | **Get** /fake/jsonFormData | test json serialization of form data
*FakeApi* | [**TestQueryParameterCollectionFormat**](docs/FakeApi.md#testqueryparametercollectionformat) | **Put** /fake/test-query-paramters |
*FakeClassnameTags123Api* | [**TestClassname**](docs/FakeClassnameTags123Api.md#testclassname) | **Patch** /fake_classname_test | To test class name in snake case
*PetApi* | [**AddPet**](docs/PetApi.md#addpet) | **Post** /pet | Add a new pet to the store
*PetApi* | [**DeletePet**](docs/PetApi.md#deletepet) | **Delete** /pet/{petId} | Deletes a pet
*PetApi* | [**FindPetsByStatus**](docs/PetApi.md#findpetsbystatus) | **Get** /pet/findByStatus | Finds Pets by status
*PetApi* | [**FindPetsByTags**](docs/PetApi.md#findpetsbytags) | **Get** /pet/findByTags | Finds Pets by tags
*PetApi* | [**GetPetById**](docs/PetApi.md#getpetbyid) | **Get** /pet/{petId} | Find pet by ID
*PetApi* | [**UpdatePet**](docs/PetApi.md#updatepet) | **Put** /pet | Update an existing pet
*PetApi* | [**UpdatePetWithForm**](docs/PetApi.md#updatepetwithform) | **Post** /pet/{petId} | Updates a pet in the store with form data
*PetApi* | [**UploadFile**](docs/PetApi.md#uploadfile) | **Post** /pet/{petId}/uploadImage | uploads an image
*PetApi* | [**UploadFileWithRequiredFile**](docs/PetApi.md#uploadfilewithrequiredfile) | **Post** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required)
*StoreApi* | [**DeleteOrder**](docs/StoreApi.md#deleteorder) | **Delete** /store/order/{order_id} | Delete purchase order by ID
*StoreApi* | [**GetInventory**](docs/StoreApi.md#getinventory) | **Get** /store/inventory | Returns pet inventories by status
*StoreApi* | [**GetOrderById**](docs/StoreApi.md#getorderbyid) | **Get** /store/order/{order_id} | Find purchase order by ID
*StoreApi* | [**PlaceOrder**](docs/StoreApi.md#placeorder) | **Post** /store/order | Place an order for a pet
*UserApi* | [**CreateUser**](docs/UserApi.md#createuser) | **Post** /user | Create user
*UserApi* | [**CreateUsersWithArrayInput**](docs/UserApi.md#createuserswitharrayinput) | **Post** /user/createWithArray | Creates list of users with given input array
*UserApi* | [**CreateUsersWithListInput**](docs/UserApi.md#createuserswithlistinput) | **Post** /user/createWithList | Creates list of users with given input array
*UserApi* | [**DeleteUser**](docs/UserApi.md#deleteuser) | **Delete** /user/{username} | Delete user
*UserApi* | [**GetUserByName**](docs/UserApi.md#getuserbyname) | **Get** /user/{username} | Get user by user name
*UserApi* | [**LoginUser**](docs/UserApi.md#loginuser) | **Get** /user/login | Logs user into the system
*UserApi* | [**LogoutUser**](docs/UserApi.md#logoutuser) | **Get** /user/logout | Logs out current logged in user session
*UserApi* | [**UpdateUser**](docs/UserApi.md#updateuser) | **Put** /user/{username} | Updated user
## Documentation For Models
- [AdditionalPropertiesAnyType](docs/AdditionalPropertiesAnyType.md)
- [AdditionalPropertiesArray](docs/AdditionalPropertiesArray.md)
- [AdditionalPropertiesBoolean](docs/AdditionalPropertiesBoolean.md)
- [AdditionalPropertiesClass](docs/AdditionalPropertiesClass.md)
- [AdditionalPropertiesInteger](docs/AdditionalPropertiesInteger.md)
- [AdditionalPropertiesNumber](docs/AdditionalPropertiesNumber.md)
- [AdditionalPropertiesObject](docs/AdditionalPropertiesObject.md)
- [AdditionalPropertiesString](docs/AdditionalPropertiesString.md)
- [Animal](docs/Animal.md)
- [ApiResponse](docs/ApiResponse.md)
- [ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md)
- [ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md)
- [ArrayTest](docs/ArrayTest.md)
- [BigCat](docs/BigCat.md)
- [BigCatAllOf](docs/BigCatAllOf.md)
- [Capitalization](docs/Capitalization.md)
- [Cat](docs/Cat.md)
- [CatAllOf](docs/CatAllOf.md)
- [Category](docs/Category.md)
- [ClassModel](docs/ClassModel.md)
- [Client](docs/Client.md)
- [Dog](docs/Dog.md)
- [DogAllOf](docs/DogAllOf.md)
- [EnumArrays](docs/EnumArrays.md)
- [EnumClass](docs/EnumClass.md)
- [EnumTest](docs/EnumTest.md)
- [File](docs/File.md)
- [FileSchemaTestClass](docs/FileSchemaTestClass.md)
- [FormatTest](docs/FormatTest.md)
- [HasOnlyReadOnly](docs/HasOnlyReadOnly.md)
- [List](docs/List.md)
- [MapTest](docs/MapTest.md)
- [MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md)
- [Model200Response](docs/Model200Response.md)
- [Name](docs/Name.md)
- [NumberOnly](docs/NumberOnly.md)
- [Order](docs/Order.md)
- [OuterComposite](docs/OuterComposite.md)
- [OuterEnum](docs/OuterEnum.md)
- [Pet](docs/Pet.md)
- [ReadOnlyFirst](docs/ReadOnlyFirst.md)
- [Return](docs/Return.md)
- [SpecialModelName](docs/SpecialModelName.md)
- [Tag](docs/Tag.md)
- [TypeHolderDefault](docs/TypeHolderDefault.md)
- [TypeHolderExample](docs/TypeHolderExample.md)
- [User](docs/User.md)
- [XmlItem](docs/XmlItem.md)
## Documentation For Authorization
### api_key
- **Type**: API key
- **API key parameter name**: api_key
- **Location**: HTTP header
Note, each API key must be added to a map of `map[string]APIKey` where the key is: api_key and passed in as the auth context for each request.
### api_key_query
- **Type**: API key
- **API key parameter name**: api_key_query
- **Location**: URL query string
Note, each API key must be added to a map of `map[string]APIKey` where the key is: api_key_query and passed in as the auth context for each request.
### http_basic_test
- **Type**: HTTP basic authentication
Example
```golang
auth := context.WithValue(context.Background(), 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
- **Scopes**:
- **write:pets**: modify pets in your account
- **read:pets**: read your pets
Example
```golang
auth := context.WithValue(context.Background(), sw.ContextAccessToken, "ACCESSTOKENSTRING")
r, err := client.Service.Operation(auth, args)
```
Or via OAuth2 module to automatically refresh tokens and perform user authentication.
```golang
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)
```
## Documentation for Utility Methods
Due to the fact that model structure members are all pointers, this package contains
a number of utility functions to easily obtain pointers to values of basic types.
Each of these functions takes a value of the given basic type and returns a pointer to it:
* `PtrBool`
* `PtrInt`
* `PtrInt32`
* `PtrInt64`
* `PtrFloat`
* `PtrFloat32`
* `PtrFloat64`
* `PtrString`
* `PtrTime`
## Author

View File

@ -1,153 +0,0 @@
/*
* OpenAPI Petstore
*
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*
* API version: 1.0.0
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/
package petstore
import (
_context "context"
_ioutil "io/ioutil"
_nethttp "net/http"
_neturl "net/url"
)
// Linger please
var (
_ _context.Context
)
type AnotherFakeApi interface {
/*
* Call123TestSpecialTags To test special tags
* To test special tags and operation ID starting with number
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @return ApiCall123TestSpecialTagsRequest
*/
Call123TestSpecialTags(ctx _context.Context) ApiCall123TestSpecialTagsRequest
/*
* Call123TestSpecialTagsExecute executes the request
* @return Client
*/
Call123TestSpecialTagsExecute(r ApiCall123TestSpecialTagsRequest) (Client, *_nethttp.Response, error)
}
// AnotherFakeApiService AnotherFakeApi service
type AnotherFakeApiService service
type ApiCall123TestSpecialTagsRequest struct {
ctx _context.Context
ApiService AnotherFakeApi
body *Client
}
func (r ApiCall123TestSpecialTagsRequest) Body(body Client) ApiCall123TestSpecialTagsRequest {
r.body = &body
return r
}
func (r ApiCall123TestSpecialTagsRequest) Execute() (Client, *_nethttp.Response, error) {
return r.ApiService.Call123TestSpecialTagsExecute(r)
}
/*
* Call123TestSpecialTags To test special tags
* To test special tags and operation ID starting with number
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @return ApiCall123TestSpecialTagsRequest
*/
func (a *AnotherFakeApiService) Call123TestSpecialTags(ctx _context.Context) ApiCall123TestSpecialTagsRequest {
return ApiCall123TestSpecialTagsRequest{
ApiService: a,
ctx: ctx,
}
}
/*
* Execute executes the request
* @return Client
*/
func (a *AnotherFakeApiService) Call123TestSpecialTagsExecute(r ApiCall123TestSpecialTagsRequest) (Client, *_nethttp.Response, error) {
var (
localVarHTTPMethod = _nethttp.MethodPatch
localVarPostBody interface{}
localVarFormFileName string
localVarFileName string
localVarFileBytes []byte
localVarReturnValue Client
)
localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "AnotherFakeApiService.Call123TestSpecialTags")
if err != nil {
return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/another-fake/dummy"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
if r.body == nil {
return localVarReturnValue, nil, reportError("body is required and must be specified")
}
// to determine the Content-Type header
localVarHTTPContentTypes := []string{"application/json"}
// set Content-Type header
localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)
if localVarHTTPContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHTTPContentType
}
// to determine the Accept header
localVarHTTPHeaderAccepts := []string{"application/json"}
// set Accept header
localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)
if localVarHTTPHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept
}
// body params
localVarPostBody = r.body
req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)
if err != nil {
return localVarReturnValue, nil, err
}
localVarHTTPResponse, err := a.client.callAPI(req)
if err != nil || localVarHTTPResponse == nil {
return localVarReturnValue, localVarHTTPResponse, err
}
localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)
localVarHTTPResponse.Body.Close()
if err != nil {
return localVarReturnValue, localVarHTTPResponse, err
}
if localVarHTTPResponse.StatusCode >= 300 {
newErr := GenericOpenAPIError{
body: localVarBody,
error: localVarHTTPResponse.Status,
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr := GenericOpenAPIError{
body: localVarBody,
error: err.Error(),
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
return localVarReturnValue, localVarHTTPResponse, nil
}

File diff suppressed because it is too large Load Diff

View File

@ -1,167 +0,0 @@
/*
* OpenAPI Petstore
*
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*
* API version: 1.0.0
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/
package petstore
import (
_context "context"
_ioutil "io/ioutil"
_nethttp "net/http"
_neturl "net/url"
)
// Linger please
var (
_ _context.Context
)
type FakeClassnameTags123Api interface {
/*
* TestClassname To test class name in snake case
* To test class name in snake case
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @return ApiTestClassnameRequest
*/
TestClassname(ctx _context.Context) ApiTestClassnameRequest
/*
* TestClassnameExecute executes the request
* @return Client
*/
TestClassnameExecute(r ApiTestClassnameRequest) (Client, *_nethttp.Response, error)
}
// FakeClassnameTags123ApiService FakeClassnameTags123Api service
type FakeClassnameTags123ApiService service
type ApiTestClassnameRequest struct {
ctx _context.Context
ApiService FakeClassnameTags123Api
body *Client
}
func (r ApiTestClassnameRequest) Body(body Client) ApiTestClassnameRequest {
r.body = &body
return r
}
func (r ApiTestClassnameRequest) Execute() (Client, *_nethttp.Response, error) {
return r.ApiService.TestClassnameExecute(r)
}
/*
* TestClassname To test class name in snake case
* To test class name in snake case
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @return ApiTestClassnameRequest
*/
func (a *FakeClassnameTags123ApiService) TestClassname(ctx _context.Context) ApiTestClassnameRequest {
return ApiTestClassnameRequest{
ApiService: a,
ctx: ctx,
}
}
/*
* Execute executes the request
* @return Client
*/
func (a *FakeClassnameTags123ApiService) TestClassnameExecute(r ApiTestClassnameRequest) (Client, *_nethttp.Response, error) {
var (
localVarHTTPMethod = _nethttp.MethodPatch
localVarPostBody interface{}
localVarFormFileName string
localVarFileName string
localVarFileBytes []byte
localVarReturnValue Client
)
localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "FakeClassnameTags123ApiService.TestClassname")
if err != nil {
return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/fake_classname_test"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
if r.body == nil {
return localVarReturnValue, nil, reportError("body is required and must be specified")
}
// to determine the Content-Type header
localVarHTTPContentTypes := []string{"application/json"}
// set Content-Type header
localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)
if localVarHTTPContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHTTPContentType
}
// to determine the Accept header
localVarHTTPHeaderAccepts := []string{"application/json"}
// set Accept header
localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)
if localVarHTTPHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept
}
// body params
localVarPostBody = r.body
if r.ctx != nil {
// API Key Authentication
if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {
if apiKey, ok := auth["api_key_query"]; ok {
var key string
if apiKey.Prefix != "" {
key = apiKey.Prefix + " " + apiKey.Key
} else {
key = apiKey.Key
}
localVarQueryParams.Add("api_key_query", key)
}
}
}
req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)
if err != nil {
return localVarReturnValue, nil, err
}
localVarHTTPResponse, err := a.client.callAPI(req)
if err != nil || localVarHTTPResponse == nil {
return localVarReturnValue, localVarHTTPResponse, err
}
localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)
localVarHTTPResponse.Body.Close()
if err != nil {
return localVarReturnValue, localVarHTTPResponse, err
}
if localVarHTTPResponse.StatusCode >= 300 {
newErr := GenericOpenAPIError{
body: localVarBody,
error: localVarHTTPResponse.Status,
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr := GenericOpenAPIError{
body: localVarBody,
error: err.Error(),
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
return localVarReturnValue, localVarHTTPResponse, nil
}

File diff suppressed because it is too large Load Diff

View File

@ -1,515 +0,0 @@
/*
* OpenAPI Petstore
*
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*
* API version: 1.0.0
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/
package petstore
import (
_context "context"
_ioutil "io/ioutil"
_nethttp "net/http"
_neturl "net/url"
"strings"
)
// Linger please
var (
_ _context.Context
)
type StoreApi interface {
/*
* DeleteOrder Delete purchase order by ID
* For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @param orderId ID of the order that needs to be deleted
* @return ApiDeleteOrderRequest
*/
DeleteOrder(ctx _context.Context, orderId string) ApiDeleteOrderRequest
/*
* DeleteOrderExecute executes the request
*/
DeleteOrderExecute(r ApiDeleteOrderRequest) (*_nethttp.Response, error)
/*
* GetInventory Returns pet inventories by status
* Returns a map of status codes to quantities
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @return ApiGetInventoryRequest
*/
GetInventory(ctx _context.Context) ApiGetInventoryRequest
/*
* GetInventoryExecute executes the request
* @return map[string]int32
*/
GetInventoryExecute(r ApiGetInventoryRequest) (map[string]int32, *_nethttp.Response, error)
/*
* GetOrderById Find purchase order by ID
* For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @param orderId ID of pet that needs to be fetched
* @return ApiGetOrderByIdRequest
*/
GetOrderById(ctx _context.Context, orderId int64) ApiGetOrderByIdRequest
/*
* GetOrderByIdExecute executes the request
* @return Order
*/
GetOrderByIdExecute(r ApiGetOrderByIdRequest) (Order, *_nethttp.Response, error)
/*
* PlaceOrder Place an order for a pet
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @return ApiPlaceOrderRequest
*/
PlaceOrder(ctx _context.Context) ApiPlaceOrderRequest
/*
* PlaceOrderExecute executes the request
* @return Order
*/
PlaceOrderExecute(r ApiPlaceOrderRequest) (Order, *_nethttp.Response, error)
}
// StoreApiService StoreApi service
type StoreApiService service
type ApiDeleteOrderRequest struct {
ctx _context.Context
ApiService StoreApi
orderId string
}
func (r ApiDeleteOrderRequest) Execute() (*_nethttp.Response, error) {
return r.ApiService.DeleteOrderExecute(r)
}
/*
* DeleteOrder Delete purchase order by ID
* For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @param orderId ID of the order that needs to be deleted
* @return ApiDeleteOrderRequest
*/
func (a *StoreApiService) DeleteOrder(ctx _context.Context, orderId string) ApiDeleteOrderRequest {
return ApiDeleteOrderRequest{
ApiService: a,
ctx: ctx,
orderId: orderId,
}
}
/*
* Execute executes the request
*/
func (a *StoreApiService) DeleteOrderExecute(r ApiDeleteOrderRequest) (*_nethttp.Response, error) {
var (
localVarHTTPMethod = _nethttp.MethodDelete
localVarPostBody interface{}
localVarFormFileName string
localVarFileName string
localVarFileBytes []byte
)
localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "StoreApiService.DeleteOrder")
if err != nil {
return nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/store/order/{order_id}"
localVarPath = strings.Replace(localVarPath, "{"+"order_id"+"}", _neturl.PathEscape(parameterToString(r.orderId, "")) , -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
// to determine the Content-Type header
localVarHTTPContentTypes := []string{}
// set Content-Type header
localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)
if localVarHTTPContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHTTPContentType
}
// to determine the Accept header
localVarHTTPHeaderAccepts := []string{}
// set Accept header
localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)
if localVarHTTPHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept
}
req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)
if err != nil {
return nil, err
}
localVarHTTPResponse, err := a.client.callAPI(req)
if err != nil || localVarHTTPResponse == nil {
return localVarHTTPResponse, err
}
localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)
localVarHTTPResponse.Body.Close()
if err != nil {
return localVarHTTPResponse, err
}
if localVarHTTPResponse.StatusCode >= 300 {
newErr := GenericOpenAPIError{
body: localVarBody,
error: localVarHTTPResponse.Status,
}
return localVarHTTPResponse, newErr
}
return localVarHTTPResponse, nil
}
type ApiGetInventoryRequest struct {
ctx _context.Context
ApiService StoreApi
}
func (r ApiGetInventoryRequest) Execute() (map[string]int32, *_nethttp.Response, error) {
return r.ApiService.GetInventoryExecute(r)
}
/*
* GetInventory Returns pet inventories by status
* Returns a map of status codes to quantities
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @return ApiGetInventoryRequest
*/
func (a *StoreApiService) GetInventory(ctx _context.Context) ApiGetInventoryRequest {
return ApiGetInventoryRequest{
ApiService: a,
ctx: ctx,
}
}
/*
* Execute executes the request
* @return map[string]int32
*/
func (a *StoreApiService) GetInventoryExecute(r ApiGetInventoryRequest) (map[string]int32, *_nethttp.Response, error) {
var (
localVarHTTPMethod = _nethttp.MethodGet
localVarPostBody interface{}
localVarFormFileName string
localVarFileName string
localVarFileBytes []byte
localVarReturnValue map[string]int32
)
localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "StoreApiService.GetInventory")
if err != nil {
return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/store/inventory"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
// to determine the Content-Type header
localVarHTTPContentTypes := []string{}
// set Content-Type header
localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)
if localVarHTTPContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHTTPContentType
}
// to determine the Accept header
localVarHTTPHeaderAccepts := []string{"application/json"}
// set Accept header
localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)
if localVarHTTPHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept
}
if r.ctx != nil {
// API Key Authentication
if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {
if apiKey, ok := auth["api_key"]; ok {
var key string
if apiKey.Prefix != "" {
key = apiKey.Prefix + " " + apiKey.Key
} else {
key = apiKey.Key
}
localVarHeaderParams["api_key"] = key
}
}
}
req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)
if err != nil {
return localVarReturnValue, nil, err
}
localVarHTTPResponse, err := a.client.callAPI(req)
if err != nil || localVarHTTPResponse == nil {
return localVarReturnValue, localVarHTTPResponse, err
}
localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)
localVarHTTPResponse.Body.Close()
if err != nil {
return localVarReturnValue, localVarHTTPResponse, err
}
if localVarHTTPResponse.StatusCode >= 300 {
newErr := GenericOpenAPIError{
body: localVarBody,
error: localVarHTTPResponse.Status,
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr := GenericOpenAPIError{
body: localVarBody,
error: err.Error(),
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
return localVarReturnValue, localVarHTTPResponse, nil
}
type ApiGetOrderByIdRequest struct {
ctx _context.Context
ApiService StoreApi
orderId int64
}
func (r ApiGetOrderByIdRequest) Execute() (Order, *_nethttp.Response, error) {
return r.ApiService.GetOrderByIdExecute(r)
}
/*
* GetOrderById Find purchase order by ID
* For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @param orderId ID of pet that needs to be fetched
* @return ApiGetOrderByIdRequest
*/
func (a *StoreApiService) GetOrderById(ctx _context.Context, orderId int64) ApiGetOrderByIdRequest {
return ApiGetOrderByIdRequest{
ApiService: a,
ctx: ctx,
orderId: orderId,
}
}
/*
* Execute executes the request
* @return Order
*/
func (a *StoreApiService) GetOrderByIdExecute(r ApiGetOrderByIdRequest) (Order, *_nethttp.Response, error) {
var (
localVarHTTPMethod = _nethttp.MethodGet
localVarPostBody interface{}
localVarFormFileName string
localVarFileName string
localVarFileBytes []byte
localVarReturnValue Order
)
localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "StoreApiService.GetOrderById")
if err != nil {
return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/store/order/{order_id}"
localVarPath = strings.Replace(localVarPath, "{"+"order_id"+"}", _neturl.PathEscape(parameterToString(r.orderId, "")) , -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
if r.orderId < 1 {
return localVarReturnValue, nil, reportError("orderId must be greater than 1")
}
if r.orderId > 5 {
return localVarReturnValue, nil, reportError("orderId must be less than 5")
}
// to determine the Content-Type header
localVarHTTPContentTypes := []string{}
// set Content-Type header
localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)
if localVarHTTPContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHTTPContentType
}
// to determine the Accept header
localVarHTTPHeaderAccepts := []string{"application/xml", "application/json"}
// set Accept header
localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)
if localVarHTTPHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept
}
req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)
if err != nil {
return localVarReturnValue, nil, err
}
localVarHTTPResponse, err := a.client.callAPI(req)
if err != nil || localVarHTTPResponse == nil {
return localVarReturnValue, localVarHTTPResponse, err
}
localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)
localVarHTTPResponse.Body.Close()
if err != nil {
return localVarReturnValue, localVarHTTPResponse, err
}
if localVarHTTPResponse.StatusCode >= 300 {
newErr := GenericOpenAPIError{
body: localVarBody,
error: localVarHTTPResponse.Status,
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr := GenericOpenAPIError{
body: localVarBody,
error: err.Error(),
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
return localVarReturnValue, localVarHTTPResponse, nil
}
type ApiPlaceOrderRequest struct {
ctx _context.Context
ApiService StoreApi
body *Order
}
func (r ApiPlaceOrderRequest) Body(body Order) ApiPlaceOrderRequest {
r.body = &body
return r
}
func (r ApiPlaceOrderRequest) Execute() (Order, *_nethttp.Response, error) {
return r.ApiService.PlaceOrderExecute(r)
}
/*
* PlaceOrder Place an order for a pet
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @return ApiPlaceOrderRequest
*/
func (a *StoreApiService) PlaceOrder(ctx _context.Context) ApiPlaceOrderRequest {
return ApiPlaceOrderRequest{
ApiService: a,
ctx: ctx,
}
}
/*
* Execute executes the request
* @return Order
*/
func (a *StoreApiService) PlaceOrderExecute(r ApiPlaceOrderRequest) (Order, *_nethttp.Response, error) {
var (
localVarHTTPMethod = _nethttp.MethodPost
localVarPostBody interface{}
localVarFormFileName string
localVarFileName string
localVarFileBytes []byte
localVarReturnValue Order
)
localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "StoreApiService.PlaceOrder")
if err != nil {
return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/store/order"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
if r.body == nil {
return localVarReturnValue, nil, reportError("body is required and must be specified")
}
// to determine the Content-Type header
localVarHTTPContentTypes := []string{}
// set Content-Type header
localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)
if localVarHTTPContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHTTPContentType
}
// to determine the Accept header
localVarHTTPHeaderAccepts := []string{"application/xml", "application/json"}
// set Accept header
localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)
if localVarHTTPHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept
}
// body params
localVarPostBody = r.body
req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)
if err != nil {
return localVarReturnValue, nil, err
}
localVarHTTPResponse, err := a.client.callAPI(req)
if err != nil || localVarHTTPResponse == nil {
return localVarReturnValue, localVarHTTPResponse, err
}
localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)
localVarHTTPResponse.Body.Close()
if err != nil {
return localVarReturnValue, localVarHTTPResponse, err
}
if localVarHTTPResponse.StatusCode >= 300 {
newErr := GenericOpenAPIError{
body: localVarBody,
error: localVarHTTPResponse.Status,
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr := GenericOpenAPIError{
body: localVarBody,
error: err.Error(),
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
return localVarReturnValue, localVarHTTPResponse, nil
}

View File

@ -1,940 +0,0 @@
/*
* OpenAPI Petstore
*
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*
* API version: 1.0.0
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/
package petstore
import (
_context "context"
_ioutil "io/ioutil"
_nethttp "net/http"
_neturl "net/url"
"strings"
)
// Linger please
var (
_ _context.Context
)
type UserApi interface {
/*
* CreateUser Create user
* This can only be done by the logged in user.
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @return ApiCreateUserRequest
*/
CreateUser(ctx _context.Context) ApiCreateUserRequest
/*
* CreateUserExecute executes the request
*/
CreateUserExecute(r ApiCreateUserRequest) (*_nethttp.Response, error)
/*
* CreateUsersWithArrayInput Creates list of users with given input array
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @return ApiCreateUsersWithArrayInputRequest
*/
CreateUsersWithArrayInput(ctx _context.Context) ApiCreateUsersWithArrayInputRequest
/*
* CreateUsersWithArrayInputExecute executes the request
*/
CreateUsersWithArrayInputExecute(r ApiCreateUsersWithArrayInputRequest) (*_nethttp.Response, error)
/*
* CreateUsersWithListInput Creates list of users with given input array
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @return ApiCreateUsersWithListInputRequest
*/
CreateUsersWithListInput(ctx _context.Context) ApiCreateUsersWithListInputRequest
/*
* CreateUsersWithListInputExecute executes the request
*/
CreateUsersWithListInputExecute(r ApiCreateUsersWithListInputRequest) (*_nethttp.Response, error)
/*
* DeleteUser Delete user
* This can only be done by the logged in user.
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @param username The name that needs to be deleted
* @return ApiDeleteUserRequest
*/
DeleteUser(ctx _context.Context, username string) ApiDeleteUserRequest
/*
* DeleteUserExecute executes the request
*/
DeleteUserExecute(r ApiDeleteUserRequest) (*_nethttp.Response, error)
/*
* GetUserByName Get user by user name
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @param username The name that needs to be fetched. Use user1 for testing.
* @return ApiGetUserByNameRequest
*/
GetUserByName(ctx _context.Context, username string) ApiGetUserByNameRequest
/*
* GetUserByNameExecute executes the request
* @return User
*/
GetUserByNameExecute(r ApiGetUserByNameRequest) (User, *_nethttp.Response, error)
/*
* LoginUser Logs user into the system
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @return ApiLoginUserRequest
*/
LoginUser(ctx _context.Context) ApiLoginUserRequest
/*
* LoginUserExecute executes the request
* @return string
*/
LoginUserExecute(r ApiLoginUserRequest) (string, *_nethttp.Response, error)
/*
* LogoutUser Logs out current logged in user session
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @return ApiLogoutUserRequest
*/
LogoutUser(ctx _context.Context) ApiLogoutUserRequest
/*
* LogoutUserExecute executes the request
*/
LogoutUserExecute(r ApiLogoutUserRequest) (*_nethttp.Response, error)
/*
* UpdateUser Updated user
* This can only be done by the logged in user.
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @param username name that need to be deleted
* @return ApiUpdateUserRequest
*/
UpdateUser(ctx _context.Context, username string) ApiUpdateUserRequest
/*
* UpdateUserExecute executes the request
*/
UpdateUserExecute(r ApiUpdateUserRequest) (*_nethttp.Response, error)
}
// UserApiService UserApi service
type UserApiService service
type ApiCreateUserRequest struct {
ctx _context.Context
ApiService UserApi
body *User
}
func (r ApiCreateUserRequest) Body(body User) ApiCreateUserRequest {
r.body = &body
return r
}
func (r ApiCreateUserRequest) Execute() (*_nethttp.Response, error) {
return r.ApiService.CreateUserExecute(r)
}
/*
* CreateUser Create user
* This can only be done by the logged in user.
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @return ApiCreateUserRequest
*/
func (a *UserApiService) CreateUser(ctx _context.Context) ApiCreateUserRequest {
return ApiCreateUserRequest{
ApiService: a,
ctx: ctx,
}
}
/*
* Execute executes the request
*/
func (a *UserApiService) CreateUserExecute(r ApiCreateUserRequest) (*_nethttp.Response, error) {
var (
localVarHTTPMethod = _nethttp.MethodPost
localVarPostBody interface{}
localVarFormFileName string
localVarFileName string
localVarFileBytes []byte
)
localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "UserApiService.CreateUser")
if err != nil {
return nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/user"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
if r.body == nil {
return nil, reportError("body is required and must be specified")
}
// to determine the Content-Type header
localVarHTTPContentTypes := []string{}
// set Content-Type header
localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)
if localVarHTTPContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHTTPContentType
}
// to determine the Accept header
localVarHTTPHeaderAccepts := []string{}
// set Accept header
localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)
if localVarHTTPHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept
}
// body params
localVarPostBody = r.body
req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)
if err != nil {
return nil, err
}
localVarHTTPResponse, err := a.client.callAPI(req)
if err != nil || localVarHTTPResponse == nil {
return localVarHTTPResponse, err
}
localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)
localVarHTTPResponse.Body.Close()
if err != nil {
return localVarHTTPResponse, err
}
if localVarHTTPResponse.StatusCode >= 300 {
newErr := GenericOpenAPIError{
body: localVarBody,
error: localVarHTTPResponse.Status,
}
return localVarHTTPResponse, newErr
}
return localVarHTTPResponse, nil
}
type ApiCreateUsersWithArrayInputRequest struct {
ctx _context.Context
ApiService UserApi
body *[]User
}
func (r ApiCreateUsersWithArrayInputRequest) Body(body []User) ApiCreateUsersWithArrayInputRequest {
r.body = &body
return r
}
func (r ApiCreateUsersWithArrayInputRequest) Execute() (*_nethttp.Response, error) {
return r.ApiService.CreateUsersWithArrayInputExecute(r)
}
/*
* CreateUsersWithArrayInput Creates list of users with given input array
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @return ApiCreateUsersWithArrayInputRequest
*/
func (a *UserApiService) CreateUsersWithArrayInput(ctx _context.Context) ApiCreateUsersWithArrayInputRequest {
return ApiCreateUsersWithArrayInputRequest{
ApiService: a,
ctx: ctx,
}
}
/*
* Execute executes the request
*/
func (a *UserApiService) CreateUsersWithArrayInputExecute(r ApiCreateUsersWithArrayInputRequest) (*_nethttp.Response, error) {
var (
localVarHTTPMethod = _nethttp.MethodPost
localVarPostBody interface{}
localVarFormFileName string
localVarFileName string
localVarFileBytes []byte
)
localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "UserApiService.CreateUsersWithArrayInput")
if err != nil {
return nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/user/createWithArray"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
if r.body == nil {
return nil, reportError("body is required and must be specified")
}
// to determine the Content-Type header
localVarHTTPContentTypes := []string{}
// set Content-Type header
localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)
if localVarHTTPContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHTTPContentType
}
// to determine the Accept header
localVarHTTPHeaderAccepts := []string{}
// set Accept header
localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)
if localVarHTTPHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept
}
// body params
localVarPostBody = r.body
req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)
if err != nil {
return nil, err
}
localVarHTTPResponse, err := a.client.callAPI(req)
if err != nil || localVarHTTPResponse == nil {
return localVarHTTPResponse, err
}
localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)
localVarHTTPResponse.Body.Close()
if err != nil {
return localVarHTTPResponse, err
}
if localVarHTTPResponse.StatusCode >= 300 {
newErr := GenericOpenAPIError{
body: localVarBody,
error: localVarHTTPResponse.Status,
}
return localVarHTTPResponse, newErr
}
return localVarHTTPResponse, nil
}
type ApiCreateUsersWithListInputRequest struct {
ctx _context.Context
ApiService UserApi
body *[]User
}
func (r ApiCreateUsersWithListInputRequest) Body(body []User) ApiCreateUsersWithListInputRequest {
r.body = &body
return r
}
func (r ApiCreateUsersWithListInputRequest) Execute() (*_nethttp.Response, error) {
return r.ApiService.CreateUsersWithListInputExecute(r)
}
/*
* CreateUsersWithListInput Creates list of users with given input array
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @return ApiCreateUsersWithListInputRequest
*/
func (a *UserApiService) CreateUsersWithListInput(ctx _context.Context) ApiCreateUsersWithListInputRequest {
return ApiCreateUsersWithListInputRequest{
ApiService: a,
ctx: ctx,
}
}
/*
* Execute executes the request
*/
func (a *UserApiService) CreateUsersWithListInputExecute(r ApiCreateUsersWithListInputRequest) (*_nethttp.Response, error) {
var (
localVarHTTPMethod = _nethttp.MethodPost
localVarPostBody interface{}
localVarFormFileName string
localVarFileName string
localVarFileBytes []byte
)
localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "UserApiService.CreateUsersWithListInput")
if err != nil {
return nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/user/createWithList"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
if r.body == nil {
return nil, reportError("body is required and must be specified")
}
// to determine the Content-Type header
localVarHTTPContentTypes := []string{}
// set Content-Type header
localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)
if localVarHTTPContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHTTPContentType
}
// to determine the Accept header
localVarHTTPHeaderAccepts := []string{}
// set Accept header
localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)
if localVarHTTPHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept
}
// body params
localVarPostBody = r.body
req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)
if err != nil {
return nil, err
}
localVarHTTPResponse, err := a.client.callAPI(req)
if err != nil || localVarHTTPResponse == nil {
return localVarHTTPResponse, err
}
localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)
localVarHTTPResponse.Body.Close()
if err != nil {
return localVarHTTPResponse, err
}
if localVarHTTPResponse.StatusCode >= 300 {
newErr := GenericOpenAPIError{
body: localVarBody,
error: localVarHTTPResponse.Status,
}
return localVarHTTPResponse, newErr
}
return localVarHTTPResponse, nil
}
type ApiDeleteUserRequest struct {
ctx _context.Context
ApiService UserApi
username string
}
func (r ApiDeleteUserRequest) Execute() (*_nethttp.Response, error) {
return r.ApiService.DeleteUserExecute(r)
}
/*
* DeleteUser Delete user
* This can only be done by the logged in user.
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @param username The name that needs to be deleted
* @return ApiDeleteUserRequest
*/
func (a *UserApiService) DeleteUser(ctx _context.Context, username string) ApiDeleteUserRequest {
return ApiDeleteUserRequest{
ApiService: a,
ctx: ctx,
username: username,
}
}
/*
* Execute executes the request
*/
func (a *UserApiService) DeleteUserExecute(r ApiDeleteUserRequest) (*_nethttp.Response, error) {
var (
localVarHTTPMethod = _nethttp.MethodDelete
localVarPostBody interface{}
localVarFormFileName string
localVarFileName string
localVarFileBytes []byte
)
localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "UserApiService.DeleteUser")
if err != nil {
return nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/user/{username}"
localVarPath = strings.Replace(localVarPath, "{"+"username"+"}", _neturl.PathEscape(parameterToString(r.username, "")) , -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
// to determine the Content-Type header
localVarHTTPContentTypes := []string{}
// set Content-Type header
localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)
if localVarHTTPContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHTTPContentType
}
// to determine the Accept header
localVarHTTPHeaderAccepts := []string{}
// set Accept header
localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)
if localVarHTTPHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept
}
req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)
if err != nil {
return nil, err
}
localVarHTTPResponse, err := a.client.callAPI(req)
if err != nil || localVarHTTPResponse == nil {
return localVarHTTPResponse, err
}
localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)
localVarHTTPResponse.Body.Close()
if err != nil {
return localVarHTTPResponse, err
}
if localVarHTTPResponse.StatusCode >= 300 {
newErr := GenericOpenAPIError{
body: localVarBody,
error: localVarHTTPResponse.Status,
}
return localVarHTTPResponse, newErr
}
return localVarHTTPResponse, nil
}
type ApiGetUserByNameRequest struct {
ctx _context.Context
ApiService UserApi
username string
}
func (r ApiGetUserByNameRequest) Execute() (User, *_nethttp.Response, error) {
return r.ApiService.GetUserByNameExecute(r)
}
/*
* GetUserByName Get user by user name
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @param username The name that needs to be fetched. Use user1 for testing.
* @return ApiGetUserByNameRequest
*/
func (a *UserApiService) GetUserByName(ctx _context.Context, username string) ApiGetUserByNameRequest {
return ApiGetUserByNameRequest{
ApiService: a,
ctx: ctx,
username: username,
}
}
/*
* Execute executes the request
* @return User
*/
func (a *UserApiService) GetUserByNameExecute(r ApiGetUserByNameRequest) (User, *_nethttp.Response, error) {
var (
localVarHTTPMethod = _nethttp.MethodGet
localVarPostBody interface{}
localVarFormFileName string
localVarFileName string
localVarFileBytes []byte
localVarReturnValue User
)
localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "UserApiService.GetUserByName")
if err != nil {
return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/user/{username}"
localVarPath = strings.Replace(localVarPath, "{"+"username"+"}", _neturl.PathEscape(parameterToString(r.username, "")) , -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
// to determine the Content-Type header
localVarHTTPContentTypes := []string{}
// set Content-Type header
localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)
if localVarHTTPContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHTTPContentType
}
// to determine the Accept header
localVarHTTPHeaderAccepts := []string{"application/xml", "application/json"}
// set Accept header
localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)
if localVarHTTPHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept
}
req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)
if err != nil {
return localVarReturnValue, nil, err
}
localVarHTTPResponse, err := a.client.callAPI(req)
if err != nil || localVarHTTPResponse == nil {
return localVarReturnValue, localVarHTTPResponse, err
}
localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)
localVarHTTPResponse.Body.Close()
if err != nil {
return localVarReturnValue, localVarHTTPResponse, err
}
if localVarHTTPResponse.StatusCode >= 300 {
newErr := GenericOpenAPIError{
body: localVarBody,
error: localVarHTTPResponse.Status,
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr := GenericOpenAPIError{
body: localVarBody,
error: err.Error(),
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
return localVarReturnValue, localVarHTTPResponse, nil
}
type ApiLoginUserRequest struct {
ctx _context.Context
ApiService UserApi
username *string
password *string
}
func (r ApiLoginUserRequest) Username(username string) ApiLoginUserRequest {
r.username = &username
return r
}
func (r ApiLoginUserRequest) Password(password string) ApiLoginUserRequest {
r.password = &password
return r
}
func (r ApiLoginUserRequest) Execute() (string, *_nethttp.Response, error) {
return r.ApiService.LoginUserExecute(r)
}
/*
* LoginUser Logs user into the system
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @return ApiLoginUserRequest
*/
func (a *UserApiService) LoginUser(ctx _context.Context) ApiLoginUserRequest {
return ApiLoginUserRequest{
ApiService: a,
ctx: ctx,
}
}
/*
* Execute executes the request
* @return string
*/
func (a *UserApiService) LoginUserExecute(r ApiLoginUserRequest) (string, *_nethttp.Response, error) {
var (
localVarHTTPMethod = _nethttp.MethodGet
localVarPostBody interface{}
localVarFormFileName string
localVarFileName string
localVarFileBytes []byte
localVarReturnValue string
)
localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "UserApiService.LoginUser")
if err != nil {
return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/user/login"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
if r.username == nil {
return localVarReturnValue, nil, reportError("username is required and must be specified")
}
if r.password == nil {
return localVarReturnValue, nil, reportError("password is required and must be specified")
}
localVarQueryParams.Add("username", parameterToString(*r.username, ""))
localVarQueryParams.Add("password", parameterToString(*r.password, ""))
// to determine the Content-Type header
localVarHTTPContentTypes := []string{}
// set Content-Type header
localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)
if localVarHTTPContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHTTPContentType
}
// to determine the Accept header
localVarHTTPHeaderAccepts := []string{"application/xml", "application/json"}
// set Accept header
localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)
if localVarHTTPHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept
}
req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)
if err != nil {
return localVarReturnValue, nil, err
}
localVarHTTPResponse, err := a.client.callAPI(req)
if err != nil || localVarHTTPResponse == nil {
return localVarReturnValue, localVarHTTPResponse, err
}
localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)
localVarHTTPResponse.Body.Close()
if err != nil {
return localVarReturnValue, localVarHTTPResponse, err
}
if localVarHTTPResponse.StatusCode >= 300 {
newErr := GenericOpenAPIError{
body: localVarBody,
error: localVarHTTPResponse.Status,
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr := GenericOpenAPIError{
body: localVarBody,
error: err.Error(),
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
return localVarReturnValue, localVarHTTPResponse, nil
}
type ApiLogoutUserRequest struct {
ctx _context.Context
ApiService UserApi
}
func (r ApiLogoutUserRequest) Execute() (*_nethttp.Response, error) {
return r.ApiService.LogoutUserExecute(r)
}
/*
* LogoutUser Logs out current logged in user session
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @return ApiLogoutUserRequest
*/
func (a *UserApiService) LogoutUser(ctx _context.Context) ApiLogoutUserRequest {
return ApiLogoutUserRequest{
ApiService: a,
ctx: ctx,
}
}
/*
* Execute executes the request
*/
func (a *UserApiService) LogoutUserExecute(r ApiLogoutUserRequest) (*_nethttp.Response, error) {
var (
localVarHTTPMethod = _nethttp.MethodGet
localVarPostBody interface{}
localVarFormFileName string
localVarFileName string
localVarFileBytes []byte
)
localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "UserApiService.LogoutUser")
if err != nil {
return nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/user/logout"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
// to determine the Content-Type header
localVarHTTPContentTypes := []string{}
// set Content-Type header
localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)
if localVarHTTPContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHTTPContentType
}
// to determine the Accept header
localVarHTTPHeaderAccepts := []string{}
// set Accept header
localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)
if localVarHTTPHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept
}
req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)
if err != nil {
return nil, err
}
localVarHTTPResponse, err := a.client.callAPI(req)
if err != nil || localVarHTTPResponse == nil {
return localVarHTTPResponse, err
}
localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)
localVarHTTPResponse.Body.Close()
if err != nil {
return localVarHTTPResponse, err
}
if localVarHTTPResponse.StatusCode >= 300 {
newErr := GenericOpenAPIError{
body: localVarBody,
error: localVarHTTPResponse.Status,
}
return localVarHTTPResponse, newErr
}
return localVarHTTPResponse, nil
}
type ApiUpdateUserRequest struct {
ctx _context.Context
ApiService UserApi
username string
body *User
}
func (r ApiUpdateUserRequest) Body(body User) ApiUpdateUserRequest {
r.body = &body
return r
}
func (r ApiUpdateUserRequest) Execute() (*_nethttp.Response, error) {
return r.ApiService.UpdateUserExecute(r)
}
/*
* UpdateUser Updated user
* This can only be done by the logged in user.
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @param username name that need to be deleted
* @return ApiUpdateUserRequest
*/
func (a *UserApiService) UpdateUser(ctx _context.Context, username string) ApiUpdateUserRequest {
return ApiUpdateUserRequest{
ApiService: a,
ctx: ctx,
username: username,
}
}
/*
* Execute executes the request
*/
func (a *UserApiService) UpdateUserExecute(r ApiUpdateUserRequest) (*_nethttp.Response, error) {
var (
localVarHTTPMethod = _nethttp.MethodPut
localVarPostBody interface{}
localVarFormFileName string
localVarFileName string
localVarFileBytes []byte
)
localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "UserApiService.UpdateUser")
if err != nil {
return nil, GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/user/{username}"
localVarPath = strings.Replace(localVarPath, "{"+"username"+"}", _neturl.PathEscape(parameterToString(r.username, "")) , -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
if r.body == nil {
return nil, reportError("body is required and must be specified")
}
// to determine the Content-Type header
localVarHTTPContentTypes := []string{}
// set Content-Type header
localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)
if localVarHTTPContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHTTPContentType
}
// to determine the Accept header
localVarHTTPHeaderAccepts := []string{}
// set Accept header
localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)
if localVarHTTPHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept
}
// body params
localVarPostBody = r.body
req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)
if err != nil {
return nil, err
}
localVarHTTPResponse, err := a.client.callAPI(req)
if err != nil || localVarHTTPResponse == nil {
return localVarHTTPResponse, err
}
localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)
localVarHTTPResponse.Body.Close()
if err != nil {
return localVarHTTPResponse, err
}
if localVarHTTPResponse.StatusCode >= 300 {
newErr := GenericOpenAPIError{
body: localVarBody,
error: localVarHTTPResponse.Status,
}
return localVarHTTPResponse, newErr
}
return localVarHTTPResponse, nil
}

View File

@ -1,548 +0,0 @@
/*
* OpenAPI Petstore
*
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*
* API version: 1.0.0
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/
package petstore
import (
"bytes"
"context"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"io"
"log"
"mime/multipart"
"net/http"
"net/http/httputil"
"net/url"
"os"
"path/filepath"
"reflect"
"regexp"
"strconv"
"strings"
"time"
"unicode/utf8"
"golang.org/x/oauth2"
)
var (
jsonCheck = regexp.MustCompile(`(?i:(?:application|text)/(?:vnd\.[^;]+\+)?json)`)
xmlCheck = regexp.MustCompile(`(?i:(?:application|text)/xml)`)
)
// APIClient manages communication with the OpenAPI Petstore API v1.0.0
// In most cases there should be only one, shared, APIClient.
type APIClient struct {
cfg *Configuration
common service // Reuse a single struct instead of allocating one for each service on the heap.
// API Services
AnotherFakeApi AnotherFakeApi
FakeApi FakeApi
FakeClassnameTags123Api FakeClassnameTags123Api
PetApi PetApi
StoreApi StoreApi
UserApi UserApi
}
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.AnotherFakeApi = (*AnotherFakeApiService)(&c.common)
c.FakeApi = (*FakeApiService)(&c.common)
c.FakeClassnameTags123Api = (*FakeClassnameTags123ApiService)(&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)
}
// selectHeaderContentType select a content type from the available list.
func selectHeaderContentType(contentTypes []string) string {
if len(contentTypes) == 0 {
return ""
}
if contains(contentTypes, "application/json") {
return "application/json"
}
return contentTypes[0] // use the first content type specified in 'consumes'
}
// 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) {
return true
}
}
return false
}
// 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 = "|"
case "ssv":
delimiter = " "
case "tsv":
delimiter = "\t"
case "csv":
delimiter = ","
}
if reflect.TypeOf(obj).Kind() == reflect.Slice {
return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", delimiter, -1), "[]")
} else if t, ok := obj.(time.Time); ok {
return t.Format(time.RFC3339)
}
return fmt.Sprintf("%v", obj)
}
// helper for converting interface{} parameters to json strings
func parameterToJson(obj interface{}) (string, error) {
jsonBuf, err := json.Marshal(obj)
if err != nil {
return "", err
}
return string(jsonBuf), err
}
// callAPI do the request.
func (c *APIClient) callAPI(request *http.Request) (*http.Response, error) {
if c.cfg.Debug {
dump, err := httputil.DumpRequestOut(request, true)
if err != nil {
return nil, err
}
log.Printf("\n%s\n", string(dump))
}
resp, err := c.cfg.HTTPClient.Do(request)
if err != nil {
return resp, err
}
if c.cfg.Debug {
dump, err := httputil.DumpResponse(resp, true)
if err != nil {
return resp, err
}
log.Printf("\n%s\n", string(dump))
}
return resp, err
}
// Allow modification of underlying config for alternate implementations and testing
// Caution: modifying the configuration while live can cause data races and potentially unwanted behavior
func (c *APIClient) GetConfig() *Configuration {
return c.cfg
}
// 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 url.Values,
formFileName string,
fileName string,
fileBytes []byte) (localVarRequest *http.Request, err error) {
var body *bytes.Buffer
// Detect postBody type and post.
if postBody != nil {
contentType := headerParams["Content-Type"]
if contentType == "" {
contentType = detectContentType(postBody)
headerParams["Content-Type"] = contentType
}
body, err = setBody(postBody, contentType)
if err != nil {
return nil, err
}
}
// add form parameters and file if available.
if strings.HasPrefix(headerParams["Content-Type"], "multipart/form-data") && 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(formFileName, 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()
}
if strings.HasPrefix(headerParams["Content-Type"], "application/x-www-form-urlencoded") && len(formParams) > 0 {
if body != nil {
return nil, errors.New("Cannot specify postBody and x-www-form-urlencoded form at the same time.")
}
body = &bytes.Buffer{}
body.WriteString(formParams.Encode())
// Set Content-Length
headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len())
}
// Setup path and query parameters
url, err := url.Parse(path)
if err != nil {
return nil, err
}
// Override request host, if applicable
if c.cfg.Host != "" {
url.Host = c.cfg.Host
}
// Override request scheme, if applicable
if c.cfg.Scheme != "" {
url.Scheme = c.cfg.Scheme
}
// 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 {
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)
if ctx != nil {
// add context to the request
localVarRequest = localVarRequest.WithContext(ctx)
// Walk through any authentication.
// 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
}
func (c *APIClient) decode(v interface{}, b []byte, contentType string) (err error) {
if len(b) == 0 {
return nil
}
if s, ok := v.(*string); ok {
*s = string(b)
return nil
}
if xmlCheck.MatchString(contentType) {
if err = xml.Unmarshal(b, v); err != nil {
return err
}
return nil
}
if jsonCheck.MatchString(contentType) {
if actualObj, ok := v.(interface{GetActualInstance() interface{}}); ok { // oneOf, anyOf schemas
if unmarshalObj, ok := actualObj.(interface{UnmarshalJSON([]byte) error}); ok { // make sure it has UnmarshalJSON defined
if err = unmarshalObj.UnmarshalJSON(b); err!= nil {
return err
}
} else {
errors.New("Unknown type with GetActualInstance but no unmarshalObj.UnmarshalJSON defined")
}
} else if err = json.Unmarshal(b, v); err != nil { // simple model
return err
}
return nil
}
return errors.New("undefined response type")
}
// 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 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) {
err = xml.NewEncoder(bodyBuf).Encode(body)
}
if err != nil {
return nil, err
}
if bodyBuf.Len() == 0 {
err = fmt.Errorf("Invalid body type %s\n", contentType)
return nil, err
}
return bodyBuf, nil
}
// 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 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
} else {
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)
}
// GenericOpenAPIError Provides access to the body, error and model on returned errors.
type GenericOpenAPIError struct {
body []byte
error string
model interface{}
}
// Error returns non-empty string if there was an error.
func (e GenericOpenAPIError) Error() string {
return e.error
}
// Body returns the raw bytes of the response
func (e GenericOpenAPIError) Body() []byte {
return e.body
}
// Model returns the unpacked model of the error
func (e GenericOpenAPIError) Model() interface{} {
return e.model
}

View File

@ -1,229 +0,0 @@
/*
* OpenAPI Petstore
*
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*
* API version: 1.0.0
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/
package petstore
import (
"context"
"fmt"
"net/http"
"strings"
)
// contextKeys are used to identify the type of value in the context.
// Since these are string, it is possible to get a short description of the
// context key for logging and debugging using key.String().
type contextKey string
func (c contextKey) String() string {
return "auth " + string(c)
}
var (
// ContextOAuth2 takes an oauth2.TokenSource as authentication for the request.
ContextOAuth2 = contextKey("token")
// ContextBasicAuth takes BasicAuth as authentication for the request.
ContextBasicAuth = contextKey("basic")
// ContextAccessToken takes a string oauth2 access token as authentication for the request.
ContextAccessToken = contextKey("accesstoken")
// ContextAPIKeys takes a string apikey as authentication for the request
ContextAPIKeys = contextKey("apiKeys")
// ContextHttpSignatureAuth takes HttpSignatureAuth as authentication for the request.
ContextHttpSignatureAuth = contextKey("httpsignature")
// ContextServerIndex uses a server configuration from the index.
ContextServerIndex = contextKey("serverIndex")
// ContextOperationServerIndices uses a server configuration from the index mapping.
ContextOperationServerIndices = contextKey("serverOperationIndices")
// ContextServerVariables overrides a server configuration variables.
ContextServerVariables = contextKey("serverVariables")
// ContextOperationServerVariables overrides a server configuration variables using operation specific values.
ContextOperationServerVariables = contextKey("serverOperationVariables")
)
// BasicAuth provides basic http authentication to a request passed via context using ContextBasicAuth
type BasicAuth struct {
UserName string `json:"userName,omitempty"`
Password string `json:"password,omitempty"`
}
// APIKey provides API key based authentication to a request passed via context using ContextAPIKey
type APIKey struct {
Key string
Prefix string
}
// ServerVariable stores the information about a server variable
type ServerVariable struct {
Description string
DefaultValue string
EnumValues []string
}
// ServerConfiguration stores the information about a server
type ServerConfiguration struct {
URL string
Description string
Variables map[string]ServerVariable
}
// ServerConfigurations stores multiple ServerConfiguration items
type ServerConfigurations []ServerConfiguration
// Configuration stores the configuration of the API client
type Configuration struct {
Host string `json:"host,omitempty"`
Scheme string `json:"scheme,omitempty"`
DefaultHeader map[string]string `json:"defaultHeader,omitempty"`
UserAgent string `json:"userAgent,omitempty"`
Debug bool `json:"debug,omitempty"`
Servers ServerConfigurations
OperationServers map[string]ServerConfigurations
HTTPClient *http.Client
}
// NewConfiguration returns a new Configuration object
func NewConfiguration() *Configuration {
cfg := &Configuration{
DefaultHeader: make(map[string]string),
UserAgent: "OpenAPI-Generator/1.0.0/go",
Debug: false,
Servers: ServerConfigurations{
{
URL: "http://petstore.swagger.io:80/v2",
Description: "No description provided",
},
},
OperationServers: map[string]ServerConfigurations{
},
}
return cfg
}
// AddDefaultHeader adds a new HTTP header to the default header in the request
func (c *Configuration) AddDefaultHeader(key string, value string) {
c.DefaultHeader[key] = value
}
// URL formats template on a index using given variables
func (sc ServerConfigurations) URL(index int, variables map[string]string) (string, error) {
if index < 0 || len(sc) <= index {
return "", fmt.Errorf("Index %v out of range %v", index, len(sc)-1)
}
server := sc[index]
url := server.URL
// go through variables and replace placeholders
for name, variable := range server.Variables {
if value, ok := variables[name]; ok {
found := bool(len(variable.EnumValues) == 0)
for _, enumValue := range variable.EnumValues {
if value == enumValue {
found = true
}
}
if !found {
return "", fmt.Errorf("The variable %s in the server URL has invalid value %v. Must be %v", name, value, variable.EnumValues)
}
url = strings.Replace(url, "{"+name+"}", value, -1)
} else {
url = strings.Replace(url, "{"+name+"}", variable.DefaultValue, -1)
}
}
return url, nil
}
// ServerURL returns URL based on server settings
func (c *Configuration) ServerURL(index int, variables map[string]string) (string, error) {
return c.Servers.URL(index, variables)
}
func getServerIndex(ctx context.Context) (int, error) {
si := ctx.Value(ContextServerIndex)
if si != nil {
if index, ok := si.(int); ok {
return index, nil
}
return 0, reportError("Invalid type %T should be int", si)
}
return 0, nil
}
func getServerOperationIndex(ctx context.Context, endpoint string) (int, error) {
osi := ctx.Value(ContextOperationServerIndices)
if osi != nil {
if operationIndices, ok := osi.(map[string]int); !ok {
return 0, reportError("Invalid type %T should be map[string]int", osi)
} else {
index, ok := operationIndices[endpoint]
if ok {
return index, nil
}
}
}
return getServerIndex(ctx)
}
func getServerVariables(ctx context.Context) (map[string]string, error) {
sv := ctx.Value(ContextServerVariables)
if sv != nil {
if variables, ok := sv.(map[string]string); ok {
return variables, nil
}
return nil, reportError("ctx value of ContextServerVariables has invalid type %T should be map[string]string", sv)
}
return nil, nil
}
func getServerOperationVariables(ctx context.Context, endpoint string) (map[string]string, error) {
osv := ctx.Value(ContextOperationServerVariables)
if osv != nil {
if operationVariables, ok := osv.(map[string]map[string]string); !ok {
return nil, reportError("ctx value of ContextOperationServerVariables has invalid type %T should be map[string]map[string]string", osv)
} else {
variables, ok := operationVariables[endpoint]
if ok {
return variables, nil
}
}
}
return getServerVariables(ctx)
}
// ServerURLWithContext returns a new server URL given an endpoint
func (c *Configuration) ServerURLWithContext(ctx context.Context, endpoint string) (string, error) {
sc, ok := c.OperationServers[endpoint]
if !ok {
sc = c.Servers
}
if ctx == nil {
return sc.URL(0, nil)
}
index, err := getServerOperationIndex(ctx, endpoint)
if err != nil {
return "", err
}
variables, err := getServerOperationVariables(ctx, endpoint)
if err != nil {
return "", err
}
return sc.URL(index, variables)
}

View File

@ -1,56 +0,0 @@
# AdditionalPropertiesAnyType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**Name** | Pointer to **string** | | [optional]
## Methods
### NewAdditionalPropertiesAnyType
`func NewAdditionalPropertiesAnyType() *AdditionalPropertiesAnyType`
NewAdditionalPropertiesAnyType instantiates a new AdditionalPropertiesAnyType object
This constructor will assign default values to properties that have it defined,
and makes sure properties required by API are set, but the set of arguments
will change when the set of required properties is changed
### NewAdditionalPropertiesAnyTypeWithDefaults
`func NewAdditionalPropertiesAnyTypeWithDefaults() *AdditionalPropertiesAnyType`
NewAdditionalPropertiesAnyTypeWithDefaults instantiates a new AdditionalPropertiesAnyType object
This constructor will only assign default values to properties that have it defined,
but it doesn't guarantee that properties required by API are set
### GetName
`func (o *AdditionalPropertiesAnyType) GetName() string`
GetName returns the Name field if non-nil, zero value otherwise.
### GetNameOk
`func (o *AdditionalPropertiesAnyType) GetNameOk() (*string, bool)`
GetNameOk returns a tuple with the Name field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetName
`func (o *AdditionalPropertiesAnyType) SetName(v string)`
SetName sets Name field to given value.
### HasName
`func (o *AdditionalPropertiesAnyType) HasName() bool`
HasName returns a boolean if a field has been set.
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -1,56 +0,0 @@
# AdditionalPropertiesArray
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**Name** | Pointer to **string** | | [optional]
## Methods
### NewAdditionalPropertiesArray
`func NewAdditionalPropertiesArray() *AdditionalPropertiesArray`
NewAdditionalPropertiesArray instantiates a new AdditionalPropertiesArray object
This constructor will assign default values to properties that have it defined,
and makes sure properties required by API are set, but the set of arguments
will change when the set of required properties is changed
### NewAdditionalPropertiesArrayWithDefaults
`func NewAdditionalPropertiesArrayWithDefaults() *AdditionalPropertiesArray`
NewAdditionalPropertiesArrayWithDefaults instantiates a new AdditionalPropertiesArray object
This constructor will only assign default values to properties that have it defined,
but it doesn't guarantee that properties required by API are set
### GetName
`func (o *AdditionalPropertiesArray) GetName() string`
GetName returns the Name field if non-nil, zero value otherwise.
### GetNameOk
`func (o *AdditionalPropertiesArray) GetNameOk() (*string, bool)`
GetNameOk returns a tuple with the Name field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetName
`func (o *AdditionalPropertiesArray) SetName(v string)`
SetName sets Name field to given value.
### HasName
`func (o *AdditionalPropertiesArray) HasName() bool`
HasName returns a boolean if a field has been set.
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -1,56 +0,0 @@
# AdditionalPropertiesBoolean
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**Name** | Pointer to **string** | | [optional]
## Methods
### NewAdditionalPropertiesBoolean
`func NewAdditionalPropertiesBoolean() *AdditionalPropertiesBoolean`
NewAdditionalPropertiesBoolean instantiates a new AdditionalPropertiesBoolean object
This constructor will assign default values to properties that have it defined,
and makes sure properties required by API are set, but the set of arguments
will change when the set of required properties is changed
### NewAdditionalPropertiesBooleanWithDefaults
`func NewAdditionalPropertiesBooleanWithDefaults() *AdditionalPropertiesBoolean`
NewAdditionalPropertiesBooleanWithDefaults instantiates a new AdditionalPropertiesBoolean object
This constructor will only assign default values to properties that have it defined,
but it doesn't guarantee that properties required by API are set
### GetName
`func (o *AdditionalPropertiesBoolean) GetName() string`
GetName returns the Name field if non-nil, zero value otherwise.
### GetNameOk
`func (o *AdditionalPropertiesBoolean) GetNameOk() (*string, bool)`
GetNameOk returns a tuple with the Name field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetName
`func (o *AdditionalPropertiesBoolean) SetName(v string)`
SetName sets Name field to given value.
### HasName
`func (o *AdditionalPropertiesBoolean) HasName() bool`
HasName returns a boolean if a field has been set.
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -1,316 +0,0 @@
# AdditionalPropertiesClass
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**MapString** | Pointer to **map[string]string** | | [optional]
**MapNumber** | Pointer to **map[string]float32** | | [optional]
**MapInteger** | Pointer to **map[string]int32** | | [optional]
**MapBoolean** | Pointer to **map[string]bool** | | [optional]
**MapArrayInteger** | Pointer to [**map[string][]int32**](array.md) | | [optional]
**MapArrayAnytype** | Pointer to [**map[string][]map[string]interface{}**](array.md) | | [optional]
**MapMapString** | Pointer to [**map[string]map[string]string**](map.md) | | [optional]
**MapMapAnytype** | Pointer to [**map[string]map[string]map[string]interface{}**](map.md) | | [optional]
**Anytype1** | Pointer to **map[string]interface{}** | | [optional]
**Anytype2** | Pointer to **map[string]interface{}** | | [optional]
**Anytype3** | Pointer to **map[string]interface{}** | | [optional]
## Methods
### NewAdditionalPropertiesClass
`func NewAdditionalPropertiesClass() *AdditionalPropertiesClass`
NewAdditionalPropertiesClass instantiates a new AdditionalPropertiesClass object
This constructor will assign default values to properties that have it defined,
and makes sure properties required by API are set, but the set of arguments
will change when the set of required properties is changed
### NewAdditionalPropertiesClassWithDefaults
`func NewAdditionalPropertiesClassWithDefaults() *AdditionalPropertiesClass`
NewAdditionalPropertiesClassWithDefaults instantiates a new AdditionalPropertiesClass object
This constructor will only assign default values to properties that have it defined,
but it doesn't guarantee that properties required by API are set
### GetMapString
`func (o *AdditionalPropertiesClass) GetMapString() map[string]string`
GetMapString returns the MapString field if non-nil, zero value otherwise.
### GetMapStringOk
`func (o *AdditionalPropertiesClass) GetMapStringOk() (*map[string]string, bool)`
GetMapStringOk returns a tuple with the MapString field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetMapString
`func (o *AdditionalPropertiesClass) SetMapString(v map[string]string)`
SetMapString sets MapString field to given value.
### HasMapString
`func (o *AdditionalPropertiesClass) HasMapString() bool`
HasMapString returns a boolean if a field has been set.
### GetMapNumber
`func (o *AdditionalPropertiesClass) GetMapNumber() map[string]float32`
GetMapNumber returns the MapNumber field if non-nil, zero value otherwise.
### GetMapNumberOk
`func (o *AdditionalPropertiesClass) GetMapNumberOk() (*map[string]float32, bool)`
GetMapNumberOk returns a tuple with the MapNumber field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetMapNumber
`func (o *AdditionalPropertiesClass) SetMapNumber(v map[string]float32)`
SetMapNumber sets MapNumber field to given value.
### HasMapNumber
`func (o *AdditionalPropertiesClass) HasMapNumber() bool`
HasMapNumber returns a boolean if a field has been set.
### GetMapInteger
`func (o *AdditionalPropertiesClass) GetMapInteger() map[string]int32`
GetMapInteger returns the MapInteger field if non-nil, zero value otherwise.
### GetMapIntegerOk
`func (o *AdditionalPropertiesClass) GetMapIntegerOk() (*map[string]int32, bool)`
GetMapIntegerOk returns a tuple with the MapInteger field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetMapInteger
`func (o *AdditionalPropertiesClass) SetMapInteger(v map[string]int32)`
SetMapInteger sets MapInteger field to given value.
### HasMapInteger
`func (o *AdditionalPropertiesClass) HasMapInteger() bool`
HasMapInteger returns a boolean if a field has been set.
### GetMapBoolean
`func (o *AdditionalPropertiesClass) GetMapBoolean() map[string]bool`
GetMapBoolean returns the MapBoolean field if non-nil, zero value otherwise.
### GetMapBooleanOk
`func (o *AdditionalPropertiesClass) GetMapBooleanOk() (*map[string]bool, bool)`
GetMapBooleanOk returns a tuple with the MapBoolean field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetMapBoolean
`func (o *AdditionalPropertiesClass) SetMapBoolean(v map[string]bool)`
SetMapBoolean sets MapBoolean field to given value.
### HasMapBoolean
`func (o *AdditionalPropertiesClass) HasMapBoolean() bool`
HasMapBoolean returns a boolean if a field has been set.
### GetMapArrayInteger
`func (o *AdditionalPropertiesClass) GetMapArrayInteger() map[string][]int32`
GetMapArrayInteger returns the MapArrayInteger field if non-nil, zero value otherwise.
### GetMapArrayIntegerOk
`func (o *AdditionalPropertiesClass) GetMapArrayIntegerOk() (*map[string][]int32, bool)`
GetMapArrayIntegerOk returns a tuple with the MapArrayInteger field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetMapArrayInteger
`func (o *AdditionalPropertiesClass) SetMapArrayInteger(v map[string][]int32)`
SetMapArrayInteger sets MapArrayInteger field to given value.
### HasMapArrayInteger
`func (o *AdditionalPropertiesClass) HasMapArrayInteger() bool`
HasMapArrayInteger returns a boolean if a field has been set.
### GetMapArrayAnytype
`func (o *AdditionalPropertiesClass) GetMapArrayAnytype() map[string][]map[string]interface{}`
GetMapArrayAnytype returns the MapArrayAnytype field if non-nil, zero value otherwise.
### GetMapArrayAnytypeOk
`func (o *AdditionalPropertiesClass) GetMapArrayAnytypeOk() (*map[string][]map[string]interface{}, bool)`
GetMapArrayAnytypeOk returns a tuple with the MapArrayAnytype field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetMapArrayAnytype
`func (o *AdditionalPropertiesClass) SetMapArrayAnytype(v map[string][]map[string]interface{})`
SetMapArrayAnytype sets MapArrayAnytype field to given value.
### HasMapArrayAnytype
`func (o *AdditionalPropertiesClass) HasMapArrayAnytype() bool`
HasMapArrayAnytype returns a boolean if a field has been set.
### GetMapMapString
`func (o *AdditionalPropertiesClass) GetMapMapString() map[string]map[string]string`
GetMapMapString returns the MapMapString field if non-nil, zero value otherwise.
### GetMapMapStringOk
`func (o *AdditionalPropertiesClass) GetMapMapStringOk() (*map[string]map[string]string, bool)`
GetMapMapStringOk returns a tuple with the MapMapString field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetMapMapString
`func (o *AdditionalPropertiesClass) SetMapMapString(v map[string]map[string]string)`
SetMapMapString sets MapMapString field to given value.
### HasMapMapString
`func (o *AdditionalPropertiesClass) HasMapMapString() bool`
HasMapMapString returns a boolean if a field has been set.
### GetMapMapAnytype
`func (o *AdditionalPropertiesClass) GetMapMapAnytype() map[string]map[string]map[string]interface{}`
GetMapMapAnytype returns the MapMapAnytype field if non-nil, zero value otherwise.
### GetMapMapAnytypeOk
`func (o *AdditionalPropertiesClass) GetMapMapAnytypeOk() (*map[string]map[string]map[string]interface{}, bool)`
GetMapMapAnytypeOk returns a tuple with the MapMapAnytype field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetMapMapAnytype
`func (o *AdditionalPropertiesClass) SetMapMapAnytype(v map[string]map[string]map[string]interface{})`
SetMapMapAnytype sets MapMapAnytype field to given value.
### HasMapMapAnytype
`func (o *AdditionalPropertiesClass) HasMapMapAnytype() bool`
HasMapMapAnytype returns a boolean if a field has been set.
### GetAnytype1
`func (o *AdditionalPropertiesClass) GetAnytype1() map[string]interface{}`
GetAnytype1 returns the Anytype1 field if non-nil, zero value otherwise.
### GetAnytype1Ok
`func (o *AdditionalPropertiesClass) GetAnytype1Ok() (*map[string]interface{}, bool)`
GetAnytype1Ok returns a tuple with the Anytype1 field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetAnytype1
`func (o *AdditionalPropertiesClass) SetAnytype1(v map[string]interface{})`
SetAnytype1 sets Anytype1 field to given value.
### HasAnytype1
`func (o *AdditionalPropertiesClass) HasAnytype1() bool`
HasAnytype1 returns a boolean if a field has been set.
### GetAnytype2
`func (o *AdditionalPropertiesClass) GetAnytype2() map[string]interface{}`
GetAnytype2 returns the Anytype2 field if non-nil, zero value otherwise.
### GetAnytype2Ok
`func (o *AdditionalPropertiesClass) GetAnytype2Ok() (*map[string]interface{}, bool)`
GetAnytype2Ok returns a tuple with the Anytype2 field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetAnytype2
`func (o *AdditionalPropertiesClass) SetAnytype2(v map[string]interface{})`
SetAnytype2 sets Anytype2 field to given value.
### HasAnytype2
`func (o *AdditionalPropertiesClass) HasAnytype2() bool`
HasAnytype2 returns a boolean if a field has been set.
### GetAnytype3
`func (o *AdditionalPropertiesClass) GetAnytype3() map[string]interface{}`
GetAnytype3 returns the Anytype3 field if non-nil, zero value otherwise.
### GetAnytype3Ok
`func (o *AdditionalPropertiesClass) GetAnytype3Ok() (*map[string]interface{}, bool)`
GetAnytype3Ok returns a tuple with the Anytype3 field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetAnytype3
`func (o *AdditionalPropertiesClass) SetAnytype3(v map[string]interface{})`
SetAnytype3 sets Anytype3 field to given value.
### HasAnytype3
`func (o *AdditionalPropertiesClass) HasAnytype3() bool`
HasAnytype3 returns a boolean if a field has been set.
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -1,56 +0,0 @@
# AdditionalPropertiesInteger
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**Name** | Pointer to **string** | | [optional]
## Methods
### NewAdditionalPropertiesInteger
`func NewAdditionalPropertiesInteger() *AdditionalPropertiesInteger`
NewAdditionalPropertiesInteger instantiates a new AdditionalPropertiesInteger object
This constructor will assign default values to properties that have it defined,
and makes sure properties required by API are set, but the set of arguments
will change when the set of required properties is changed
### NewAdditionalPropertiesIntegerWithDefaults
`func NewAdditionalPropertiesIntegerWithDefaults() *AdditionalPropertiesInteger`
NewAdditionalPropertiesIntegerWithDefaults instantiates a new AdditionalPropertiesInteger object
This constructor will only assign default values to properties that have it defined,
but it doesn't guarantee that properties required by API are set
### GetName
`func (o *AdditionalPropertiesInteger) GetName() string`
GetName returns the Name field if non-nil, zero value otherwise.
### GetNameOk
`func (o *AdditionalPropertiesInteger) GetNameOk() (*string, bool)`
GetNameOk returns a tuple with the Name field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetName
`func (o *AdditionalPropertiesInteger) SetName(v string)`
SetName sets Name field to given value.
### HasName
`func (o *AdditionalPropertiesInteger) HasName() bool`
HasName returns a boolean if a field has been set.
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -1,56 +0,0 @@
# AdditionalPropertiesNumber
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**Name** | Pointer to **string** | | [optional]
## Methods
### NewAdditionalPropertiesNumber
`func NewAdditionalPropertiesNumber() *AdditionalPropertiesNumber`
NewAdditionalPropertiesNumber instantiates a new AdditionalPropertiesNumber object
This constructor will assign default values to properties that have it defined,
and makes sure properties required by API are set, but the set of arguments
will change when the set of required properties is changed
### NewAdditionalPropertiesNumberWithDefaults
`func NewAdditionalPropertiesNumberWithDefaults() *AdditionalPropertiesNumber`
NewAdditionalPropertiesNumberWithDefaults instantiates a new AdditionalPropertiesNumber object
This constructor will only assign default values to properties that have it defined,
but it doesn't guarantee that properties required by API are set
### GetName
`func (o *AdditionalPropertiesNumber) GetName() string`
GetName returns the Name field if non-nil, zero value otherwise.
### GetNameOk
`func (o *AdditionalPropertiesNumber) GetNameOk() (*string, bool)`
GetNameOk returns a tuple with the Name field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetName
`func (o *AdditionalPropertiesNumber) SetName(v string)`
SetName sets Name field to given value.
### HasName
`func (o *AdditionalPropertiesNumber) HasName() bool`
HasName returns a boolean if a field has been set.
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -1,56 +0,0 @@
# AdditionalPropertiesObject
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**Name** | Pointer to **string** | | [optional]
## Methods
### NewAdditionalPropertiesObject
`func NewAdditionalPropertiesObject() *AdditionalPropertiesObject`
NewAdditionalPropertiesObject instantiates a new AdditionalPropertiesObject object
This constructor will assign default values to properties that have it defined,
and makes sure properties required by API are set, but the set of arguments
will change when the set of required properties is changed
### NewAdditionalPropertiesObjectWithDefaults
`func NewAdditionalPropertiesObjectWithDefaults() *AdditionalPropertiesObject`
NewAdditionalPropertiesObjectWithDefaults instantiates a new AdditionalPropertiesObject object
This constructor will only assign default values to properties that have it defined,
but it doesn't guarantee that properties required by API are set
### GetName
`func (o *AdditionalPropertiesObject) GetName() string`
GetName returns the Name field if non-nil, zero value otherwise.
### GetNameOk
`func (o *AdditionalPropertiesObject) GetNameOk() (*string, bool)`
GetNameOk returns a tuple with the Name field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetName
`func (o *AdditionalPropertiesObject) SetName(v string)`
SetName sets Name field to given value.
### HasName
`func (o *AdditionalPropertiesObject) HasName() bool`
HasName returns a boolean if a field has been set.
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -1,56 +0,0 @@
# AdditionalPropertiesString
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**Name** | Pointer to **string** | | [optional]
## Methods
### NewAdditionalPropertiesString
`func NewAdditionalPropertiesString() *AdditionalPropertiesString`
NewAdditionalPropertiesString instantiates a new AdditionalPropertiesString object
This constructor will assign default values to properties that have it defined,
and makes sure properties required by API are set, but the set of arguments
will change when the set of required properties is changed
### NewAdditionalPropertiesStringWithDefaults
`func NewAdditionalPropertiesStringWithDefaults() *AdditionalPropertiesString`
NewAdditionalPropertiesStringWithDefaults instantiates a new AdditionalPropertiesString object
This constructor will only assign default values to properties that have it defined,
but it doesn't guarantee that properties required by API are set
### GetName
`func (o *AdditionalPropertiesString) GetName() string`
GetName returns the Name field if non-nil, zero value otherwise.
### GetNameOk
`func (o *AdditionalPropertiesString) GetNameOk() (*string, bool)`
GetNameOk returns a tuple with the Name field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetName
`func (o *AdditionalPropertiesString) SetName(v string)`
SetName sets Name field to given value.
### HasName
`func (o *AdditionalPropertiesString) HasName() bool`
HasName returns a boolean if a field has been set.
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -1,77 +0,0 @@
# Animal
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**ClassName** | **string** | |
**Color** | Pointer to **string** | | [optional] [default to "red"]
## Methods
### NewAnimal
`func NewAnimal(className string, ) *Animal`
NewAnimal instantiates a new Animal object
This constructor will assign default values to properties that have it defined,
and makes sure properties required by API are set, but the set of arguments
will change when the set of required properties is changed
### NewAnimalWithDefaults
`func NewAnimalWithDefaults() *Animal`
NewAnimalWithDefaults instantiates a new Animal object
This constructor will only assign default values to properties that have it defined,
but it doesn't guarantee that properties required by API are set
### GetClassName
`func (o *Animal) GetClassName() string`
GetClassName returns the ClassName field if non-nil, zero value otherwise.
### GetClassNameOk
`func (o *Animal) GetClassNameOk() (*string, bool)`
GetClassNameOk returns a tuple with the ClassName field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetClassName
`func (o *Animal) SetClassName(v string)`
SetClassName sets ClassName field to given value.
### GetColor
`func (o *Animal) GetColor() string`
GetColor returns the Color field if non-nil, zero value otherwise.
### GetColorOk
`func (o *Animal) GetColorOk() (*string, bool)`
GetColorOk returns a tuple with the Color field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetColor
`func (o *Animal) SetColor(v string)`
SetColor sets Color field to given value.
### HasColor
`func (o *Animal) HasColor() bool`
HasColor returns a boolean if a field has been set.
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -1,75 +0,0 @@
# \AnotherFakeApi
All URIs are relative to *http://petstore.swagger.io:80/v2*
Method | HTTP request | Description
------------- | ------------- | -------------
[**Call123TestSpecialTags**](AnotherFakeApi.md#Call123TestSpecialTags) | **Patch** /another-fake/dummy | To test special tags
## Call123TestSpecialTags
> Client Call123TestSpecialTags(ctx).Body(body).Execute()
To test special tags
### Example
```go
package main
import (
"context"
"fmt"
"os"
openapiclient "./openapi"
)
func main() {
body := openapiclient.Client{Client: "Client_example"} // Client | client model
configuration := openapiclient.NewConfiguration()
api_client := openapiclient.NewAPIClient(configuration)
resp, r, err := api_client.AnotherFakeApi.Call123TestSpecialTags(context.Background(), body).Execute()
if err != nil {
fmt.Fprintf(os.Stderr, "Error when calling `AnotherFakeApi.Call123TestSpecialTags``: %v\n", err)
fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r)
}
// response from `Call123TestSpecialTags`: Client
fmt.Fprintf(os.Stdout, "Response from `AnotherFakeApi.Call123TestSpecialTags`: %v\n", resp)
}
```
### Path Parameters
### Other Parameters
Other parameters are passed through a pointer to a apiCall123TestSpecialTagsRequest struct via the builder pattern
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**body** | [**Client**](Client.md) | client model |
### Return type
[**Client**](Client.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: application/json
[[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)

View File

@ -1,108 +0,0 @@
# ApiResponse
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**Code** | Pointer to **int32** | | [optional]
**Type** | Pointer to **string** | | [optional]
**Message** | Pointer to **string** | | [optional]
## Methods
### NewApiResponse
`func NewApiResponse() *ApiResponse`
NewApiResponse instantiates a new ApiResponse object
This constructor will assign default values to properties that have it defined,
and makes sure properties required by API are set, but the set of arguments
will change when the set of required properties is changed
### NewApiResponseWithDefaults
`func NewApiResponseWithDefaults() *ApiResponse`
NewApiResponseWithDefaults instantiates a new ApiResponse object
This constructor will only assign default values to properties that have it defined,
but it doesn't guarantee that properties required by API are set
### GetCode
`func (o *ApiResponse) GetCode() int32`
GetCode returns the Code field if non-nil, zero value otherwise.
### GetCodeOk
`func (o *ApiResponse) GetCodeOk() (*int32, bool)`
GetCodeOk returns a tuple with the Code field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetCode
`func (o *ApiResponse) SetCode(v int32)`
SetCode sets Code field to given value.
### HasCode
`func (o *ApiResponse) HasCode() bool`
HasCode returns a boolean if a field has been set.
### GetType
`func (o *ApiResponse) GetType() string`
GetType returns the Type field if non-nil, zero value otherwise.
### GetTypeOk
`func (o *ApiResponse) GetTypeOk() (*string, bool)`
GetTypeOk returns a tuple with the Type field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetType
`func (o *ApiResponse) SetType(v string)`
SetType sets Type field to given value.
### HasType
`func (o *ApiResponse) HasType() bool`
HasType returns a boolean if a field has been set.
### GetMessage
`func (o *ApiResponse) GetMessage() string`
GetMessage returns the Message field if non-nil, zero value otherwise.
### GetMessageOk
`func (o *ApiResponse) GetMessageOk() (*string, bool)`
GetMessageOk returns a tuple with the Message field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetMessage
`func (o *ApiResponse) SetMessage(v string)`
SetMessage sets Message field to given value.
### HasMessage
`func (o *ApiResponse) HasMessage() bool`
HasMessage returns a boolean if a field has been set.
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -1,56 +0,0 @@
# ArrayOfArrayOfNumberOnly
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**ArrayArrayNumber** | Pointer to [**[][]float32**](array.md) | | [optional]
## Methods
### NewArrayOfArrayOfNumberOnly
`func NewArrayOfArrayOfNumberOnly() *ArrayOfArrayOfNumberOnly`
NewArrayOfArrayOfNumberOnly instantiates a new ArrayOfArrayOfNumberOnly object
This constructor will assign default values to properties that have it defined,
and makes sure properties required by API are set, but the set of arguments
will change when the set of required properties is changed
### NewArrayOfArrayOfNumberOnlyWithDefaults
`func NewArrayOfArrayOfNumberOnlyWithDefaults() *ArrayOfArrayOfNumberOnly`
NewArrayOfArrayOfNumberOnlyWithDefaults instantiates a new ArrayOfArrayOfNumberOnly object
This constructor will only assign default values to properties that have it defined,
but it doesn't guarantee that properties required by API are set
### GetArrayArrayNumber
`func (o *ArrayOfArrayOfNumberOnly) GetArrayArrayNumber() [][]float32`
GetArrayArrayNumber returns the ArrayArrayNumber field if non-nil, zero value otherwise.
### GetArrayArrayNumberOk
`func (o *ArrayOfArrayOfNumberOnly) GetArrayArrayNumberOk() (*[][]float32, bool)`
GetArrayArrayNumberOk returns a tuple with the ArrayArrayNumber field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetArrayArrayNumber
`func (o *ArrayOfArrayOfNumberOnly) SetArrayArrayNumber(v [][]float32)`
SetArrayArrayNumber sets ArrayArrayNumber field to given value.
### HasArrayArrayNumber
`func (o *ArrayOfArrayOfNumberOnly) HasArrayArrayNumber() bool`
HasArrayArrayNumber returns a boolean if a field has been set.
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -1,56 +0,0 @@
# ArrayOfNumberOnly
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**ArrayNumber** | Pointer to **[]float32** | | [optional]
## Methods
### NewArrayOfNumberOnly
`func NewArrayOfNumberOnly() *ArrayOfNumberOnly`
NewArrayOfNumberOnly instantiates a new ArrayOfNumberOnly object
This constructor will assign default values to properties that have it defined,
and makes sure properties required by API are set, but the set of arguments
will change when the set of required properties is changed
### NewArrayOfNumberOnlyWithDefaults
`func NewArrayOfNumberOnlyWithDefaults() *ArrayOfNumberOnly`
NewArrayOfNumberOnlyWithDefaults instantiates a new ArrayOfNumberOnly object
This constructor will only assign default values to properties that have it defined,
but it doesn't guarantee that properties required by API are set
### GetArrayNumber
`func (o *ArrayOfNumberOnly) GetArrayNumber() []float32`
GetArrayNumber returns the ArrayNumber field if non-nil, zero value otherwise.
### GetArrayNumberOk
`func (o *ArrayOfNumberOnly) GetArrayNumberOk() (*[]float32, bool)`
GetArrayNumberOk returns a tuple with the ArrayNumber field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetArrayNumber
`func (o *ArrayOfNumberOnly) SetArrayNumber(v []float32)`
SetArrayNumber sets ArrayNumber field to given value.
### HasArrayNumber
`func (o *ArrayOfNumberOnly) HasArrayNumber() bool`
HasArrayNumber returns a boolean if a field has been set.
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -1,108 +0,0 @@
# ArrayTest
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**ArrayOfString** | Pointer to **[]string** | | [optional]
**ArrayArrayOfInteger** | Pointer to [**[][]int64**](array.md) | | [optional]
**ArrayArrayOfModel** | Pointer to [**[][]ReadOnlyFirst**](array.md) | | [optional]
## Methods
### NewArrayTest
`func NewArrayTest() *ArrayTest`
NewArrayTest instantiates a new ArrayTest object
This constructor will assign default values to properties that have it defined,
and makes sure properties required by API are set, but the set of arguments
will change when the set of required properties is changed
### NewArrayTestWithDefaults
`func NewArrayTestWithDefaults() *ArrayTest`
NewArrayTestWithDefaults instantiates a new ArrayTest object
This constructor will only assign default values to properties that have it defined,
but it doesn't guarantee that properties required by API are set
### GetArrayOfString
`func (o *ArrayTest) GetArrayOfString() []string`
GetArrayOfString returns the ArrayOfString field if non-nil, zero value otherwise.
### GetArrayOfStringOk
`func (o *ArrayTest) GetArrayOfStringOk() (*[]string, bool)`
GetArrayOfStringOk returns a tuple with the ArrayOfString field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetArrayOfString
`func (o *ArrayTest) SetArrayOfString(v []string)`
SetArrayOfString sets ArrayOfString field to given value.
### HasArrayOfString
`func (o *ArrayTest) HasArrayOfString() bool`
HasArrayOfString returns a boolean if a field has been set.
### GetArrayArrayOfInteger
`func (o *ArrayTest) GetArrayArrayOfInteger() [][]int64`
GetArrayArrayOfInteger returns the ArrayArrayOfInteger field if non-nil, zero value otherwise.
### GetArrayArrayOfIntegerOk
`func (o *ArrayTest) GetArrayArrayOfIntegerOk() (*[][]int64, bool)`
GetArrayArrayOfIntegerOk returns a tuple with the ArrayArrayOfInteger field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetArrayArrayOfInteger
`func (o *ArrayTest) SetArrayArrayOfInteger(v [][]int64)`
SetArrayArrayOfInteger sets ArrayArrayOfInteger field to given value.
### HasArrayArrayOfInteger
`func (o *ArrayTest) HasArrayArrayOfInteger() bool`
HasArrayArrayOfInteger returns a boolean if a field has been set.
### GetArrayArrayOfModel
`func (o *ArrayTest) GetArrayArrayOfModel() [][]ReadOnlyFirst`
GetArrayArrayOfModel returns the ArrayArrayOfModel field if non-nil, zero value otherwise.
### GetArrayArrayOfModelOk
`func (o *ArrayTest) GetArrayArrayOfModelOk() (*[][]ReadOnlyFirst, bool)`
GetArrayArrayOfModelOk returns a tuple with the ArrayArrayOfModel field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetArrayArrayOfModel
`func (o *ArrayTest) SetArrayArrayOfModel(v [][]ReadOnlyFirst)`
SetArrayArrayOfModel sets ArrayArrayOfModel field to given value.
### HasArrayArrayOfModel
`func (o *ArrayTest) HasArrayArrayOfModel() bool`
HasArrayArrayOfModel returns a boolean if a field has been set.
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -1,56 +0,0 @@
# BigCat
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**Kind** | Pointer to **string** | | [optional]
## Methods
### NewBigCat
`func NewBigCat() *BigCat`
NewBigCat instantiates a new BigCat object
This constructor will assign default values to properties that have it defined,
and makes sure properties required by API are set, but the set of arguments
will change when the set of required properties is changed
### NewBigCatWithDefaults
`func NewBigCatWithDefaults() *BigCat`
NewBigCatWithDefaults instantiates a new BigCat object
This constructor will only assign default values to properties that have it defined,
but it doesn't guarantee that properties required by API are set
### GetKind
`func (o *BigCat) GetKind() string`
GetKind returns the Kind field if non-nil, zero value otherwise.
### GetKindOk
`func (o *BigCat) GetKindOk() (*string, bool)`
GetKindOk returns a tuple with the Kind field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetKind
`func (o *BigCat) SetKind(v string)`
SetKind sets Kind field to given value.
### HasKind
`func (o *BigCat) HasKind() bool`
HasKind returns a boolean if a field has been set.
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -1,56 +0,0 @@
# BigCatAllOf
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**Kind** | Pointer to **string** | | [optional]
## Methods
### NewBigCatAllOf
`func NewBigCatAllOf() *BigCatAllOf`
NewBigCatAllOf instantiates a new BigCatAllOf object
This constructor will assign default values to properties that have it defined,
and makes sure properties required by API are set, but the set of arguments
will change when the set of required properties is changed
### NewBigCatAllOfWithDefaults
`func NewBigCatAllOfWithDefaults() *BigCatAllOf`
NewBigCatAllOfWithDefaults instantiates a new BigCatAllOf object
This constructor will only assign default values to properties that have it defined,
but it doesn't guarantee that properties required by API are set
### GetKind
`func (o *BigCatAllOf) GetKind() string`
GetKind returns the Kind field if non-nil, zero value otherwise.
### GetKindOk
`func (o *BigCatAllOf) GetKindOk() (*string, bool)`
GetKindOk returns a tuple with the Kind field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetKind
`func (o *BigCatAllOf) SetKind(v string)`
SetKind sets Kind field to given value.
### HasKind
`func (o *BigCatAllOf) HasKind() bool`
HasKind returns a boolean if a field has been set.
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -1,186 +0,0 @@
# Capitalization
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**SmallCamel** | Pointer to **string** | | [optional]
**CapitalCamel** | Pointer to **string** | | [optional]
**SmallSnake** | Pointer to **string** | | [optional]
**CapitalSnake** | Pointer to **string** | | [optional]
**SCAETHFlowPoints** | Pointer to **string** | | [optional]
**ATT_NAME** | Pointer to **string** | Name of the pet | [optional]
## Methods
### NewCapitalization
`func NewCapitalization() *Capitalization`
NewCapitalization instantiates a new Capitalization object
This constructor will assign default values to properties that have it defined,
and makes sure properties required by API are set, but the set of arguments
will change when the set of required properties is changed
### NewCapitalizationWithDefaults
`func NewCapitalizationWithDefaults() *Capitalization`
NewCapitalizationWithDefaults instantiates a new Capitalization object
This constructor will only assign default values to properties that have it defined,
but it doesn't guarantee that properties required by API are set
### GetSmallCamel
`func (o *Capitalization) GetSmallCamel() string`
GetSmallCamel returns the SmallCamel field if non-nil, zero value otherwise.
### GetSmallCamelOk
`func (o *Capitalization) GetSmallCamelOk() (*string, bool)`
GetSmallCamelOk returns a tuple with the SmallCamel field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetSmallCamel
`func (o *Capitalization) SetSmallCamel(v string)`
SetSmallCamel sets SmallCamel field to given value.
### HasSmallCamel
`func (o *Capitalization) HasSmallCamel() bool`
HasSmallCamel returns a boolean if a field has been set.
### GetCapitalCamel
`func (o *Capitalization) GetCapitalCamel() string`
GetCapitalCamel returns the CapitalCamel field if non-nil, zero value otherwise.
### GetCapitalCamelOk
`func (o *Capitalization) GetCapitalCamelOk() (*string, bool)`
GetCapitalCamelOk returns a tuple with the CapitalCamel field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetCapitalCamel
`func (o *Capitalization) SetCapitalCamel(v string)`
SetCapitalCamel sets CapitalCamel field to given value.
### HasCapitalCamel
`func (o *Capitalization) HasCapitalCamel() bool`
HasCapitalCamel returns a boolean if a field has been set.
### GetSmallSnake
`func (o *Capitalization) GetSmallSnake() string`
GetSmallSnake returns the SmallSnake field if non-nil, zero value otherwise.
### GetSmallSnakeOk
`func (o *Capitalization) GetSmallSnakeOk() (*string, bool)`
GetSmallSnakeOk returns a tuple with the SmallSnake field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetSmallSnake
`func (o *Capitalization) SetSmallSnake(v string)`
SetSmallSnake sets SmallSnake field to given value.
### HasSmallSnake
`func (o *Capitalization) HasSmallSnake() bool`
HasSmallSnake returns a boolean if a field has been set.
### GetCapitalSnake
`func (o *Capitalization) GetCapitalSnake() string`
GetCapitalSnake returns the CapitalSnake field if non-nil, zero value otherwise.
### GetCapitalSnakeOk
`func (o *Capitalization) GetCapitalSnakeOk() (*string, bool)`
GetCapitalSnakeOk returns a tuple with the CapitalSnake field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetCapitalSnake
`func (o *Capitalization) SetCapitalSnake(v string)`
SetCapitalSnake sets CapitalSnake field to given value.
### HasCapitalSnake
`func (o *Capitalization) HasCapitalSnake() bool`
HasCapitalSnake returns a boolean if a field has been set.
### GetSCAETHFlowPoints
`func (o *Capitalization) GetSCAETHFlowPoints() string`
GetSCAETHFlowPoints returns the SCAETHFlowPoints field if non-nil, zero value otherwise.
### GetSCAETHFlowPointsOk
`func (o *Capitalization) GetSCAETHFlowPointsOk() (*string, bool)`
GetSCAETHFlowPointsOk returns a tuple with the SCAETHFlowPoints field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetSCAETHFlowPoints
`func (o *Capitalization) SetSCAETHFlowPoints(v string)`
SetSCAETHFlowPoints sets SCAETHFlowPoints field to given value.
### HasSCAETHFlowPoints
`func (o *Capitalization) HasSCAETHFlowPoints() bool`
HasSCAETHFlowPoints returns a boolean if a field has been set.
### GetATT_NAME
`func (o *Capitalization) GetATT_NAME() string`
GetATT_NAME returns the ATT_NAME field if non-nil, zero value otherwise.
### GetATT_NAMEOk
`func (o *Capitalization) GetATT_NAMEOk() (*string, bool)`
GetATT_NAMEOk returns a tuple with the ATT_NAME field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetATT_NAME
`func (o *Capitalization) SetATT_NAME(v string)`
SetATT_NAME sets ATT_NAME field to given value.
### HasATT_NAME
`func (o *Capitalization) HasATT_NAME() bool`
HasATT_NAME returns a boolean if a field has been set.
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -1,56 +0,0 @@
# Cat
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**Declawed** | Pointer to **bool** | | [optional]
## Methods
### NewCat
`func NewCat() *Cat`
NewCat instantiates a new Cat object
This constructor will assign default values to properties that have it defined,
and makes sure properties required by API are set, but the set of arguments
will change when the set of required properties is changed
### NewCatWithDefaults
`func NewCatWithDefaults() *Cat`
NewCatWithDefaults instantiates a new Cat object
This constructor will only assign default values to properties that have it defined,
but it doesn't guarantee that properties required by API are set
### GetDeclawed
`func (o *Cat) GetDeclawed() bool`
GetDeclawed returns the Declawed field if non-nil, zero value otherwise.
### GetDeclawedOk
`func (o *Cat) GetDeclawedOk() (*bool, bool)`
GetDeclawedOk returns a tuple with the Declawed field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetDeclawed
`func (o *Cat) SetDeclawed(v bool)`
SetDeclawed sets Declawed field to given value.
### HasDeclawed
`func (o *Cat) HasDeclawed() bool`
HasDeclawed returns a boolean if a field has been set.
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -1,56 +0,0 @@
# CatAllOf
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**Declawed** | Pointer to **bool** | | [optional]
## Methods
### NewCatAllOf
`func NewCatAllOf() *CatAllOf`
NewCatAllOf instantiates a new CatAllOf object
This constructor will assign default values to properties that have it defined,
and makes sure properties required by API are set, but the set of arguments
will change when the set of required properties is changed
### NewCatAllOfWithDefaults
`func NewCatAllOfWithDefaults() *CatAllOf`
NewCatAllOfWithDefaults instantiates a new CatAllOf object
This constructor will only assign default values to properties that have it defined,
but it doesn't guarantee that properties required by API are set
### GetDeclawed
`func (o *CatAllOf) GetDeclawed() bool`
GetDeclawed returns the Declawed field if non-nil, zero value otherwise.
### GetDeclawedOk
`func (o *CatAllOf) GetDeclawedOk() (*bool, bool)`
GetDeclawedOk returns a tuple with the Declawed field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetDeclawed
`func (o *CatAllOf) SetDeclawed(v bool)`
SetDeclawed sets Declawed field to given value.
### HasDeclawed
`func (o *CatAllOf) HasDeclawed() bool`
HasDeclawed returns a boolean if a field has been set.
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -1,77 +0,0 @@
# Category
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**Id** | Pointer to **int64** | | [optional]
**Name** | **string** | | [default to "default-name"]
## Methods
### NewCategory
`func NewCategory(name string, ) *Category`
NewCategory instantiates a new Category object
This constructor will assign default values to properties that have it defined,
and makes sure properties required by API are set, but the set of arguments
will change when the set of required properties is changed
### NewCategoryWithDefaults
`func NewCategoryWithDefaults() *Category`
NewCategoryWithDefaults instantiates a new Category object
This constructor will only assign default values to properties that have it defined,
but it doesn't guarantee that properties required by API are set
### GetId
`func (o *Category) GetId() int64`
GetId returns the Id field if non-nil, zero value otherwise.
### GetIdOk
`func (o *Category) GetIdOk() (*int64, bool)`
GetIdOk returns a tuple with the Id field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetId
`func (o *Category) SetId(v int64)`
SetId sets Id field to given value.
### HasId
`func (o *Category) HasId() bool`
HasId returns a boolean if a field has been set.
### GetName
`func (o *Category) GetName() string`
GetName returns the Name field if non-nil, zero value otherwise.
### GetNameOk
`func (o *Category) GetNameOk() (*string, bool)`
GetNameOk returns a tuple with the Name field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetName
`func (o *Category) SetName(v string)`
SetName sets Name field to given value.
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -1,56 +0,0 @@
# ClassModel
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**Class** | Pointer to **string** | | [optional]
## Methods
### NewClassModel
`func NewClassModel() *ClassModel`
NewClassModel instantiates a new ClassModel object
This constructor will assign default values to properties that have it defined,
and makes sure properties required by API are set, but the set of arguments
will change when the set of required properties is changed
### NewClassModelWithDefaults
`func NewClassModelWithDefaults() *ClassModel`
NewClassModelWithDefaults instantiates a new ClassModel object
This constructor will only assign default values to properties that have it defined,
but it doesn't guarantee that properties required by API are set
### GetClass
`func (o *ClassModel) GetClass() string`
GetClass returns the Class field if non-nil, zero value otherwise.
### GetClassOk
`func (o *ClassModel) GetClassOk() (*string, bool)`
GetClassOk returns a tuple with the Class field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetClass
`func (o *ClassModel) SetClass(v string)`
SetClass sets Class field to given value.
### HasClass
`func (o *ClassModel) HasClass() bool`
HasClass returns a boolean if a field has been set.
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -1,56 +0,0 @@
# Client
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**Client** | Pointer to **string** | | [optional]
## Methods
### NewClient
`func NewClient() *Client`
NewClient instantiates a new Client object
This constructor will assign default values to properties that have it defined,
and makes sure properties required by API are set, but the set of arguments
will change when the set of required properties is changed
### NewClientWithDefaults
`func NewClientWithDefaults() *Client`
NewClientWithDefaults instantiates a new Client object
This constructor will only assign default values to properties that have it defined,
but it doesn't guarantee that properties required by API are set
### GetClient
`func (o *Client) GetClient() string`
GetClient returns the Client field if non-nil, zero value otherwise.
### GetClientOk
`func (o *Client) GetClientOk() (*string, bool)`
GetClientOk returns a tuple with the Client field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetClient
`func (o *Client) SetClient(v string)`
SetClient sets Client field to given value.
### HasClient
`func (o *Client) HasClient() bool`
HasClient returns a boolean if a field has been set.
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -1,56 +0,0 @@
# Dog
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**Breed** | Pointer to **string** | | [optional]
## Methods
### NewDog
`func NewDog() *Dog`
NewDog instantiates a new Dog object
This constructor will assign default values to properties that have it defined,
and makes sure properties required by API are set, but the set of arguments
will change when the set of required properties is changed
### NewDogWithDefaults
`func NewDogWithDefaults() *Dog`
NewDogWithDefaults instantiates a new Dog object
This constructor will only assign default values to properties that have it defined,
but it doesn't guarantee that properties required by API are set
### GetBreed
`func (o *Dog) GetBreed() string`
GetBreed returns the Breed field if non-nil, zero value otherwise.
### GetBreedOk
`func (o *Dog) GetBreedOk() (*string, bool)`
GetBreedOk returns a tuple with the Breed field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetBreed
`func (o *Dog) SetBreed(v string)`
SetBreed sets Breed field to given value.
### HasBreed
`func (o *Dog) HasBreed() bool`
HasBreed returns a boolean if a field has been set.
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -1,56 +0,0 @@
# DogAllOf
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**Breed** | Pointer to **string** | | [optional]
## Methods
### NewDogAllOf
`func NewDogAllOf() *DogAllOf`
NewDogAllOf instantiates a new DogAllOf object
This constructor will assign default values to properties that have it defined,
and makes sure properties required by API are set, but the set of arguments
will change when the set of required properties is changed
### NewDogAllOfWithDefaults
`func NewDogAllOfWithDefaults() *DogAllOf`
NewDogAllOfWithDefaults instantiates a new DogAllOf object
This constructor will only assign default values to properties that have it defined,
but it doesn't guarantee that properties required by API are set
### GetBreed
`func (o *DogAllOf) GetBreed() string`
GetBreed returns the Breed field if non-nil, zero value otherwise.
### GetBreedOk
`func (o *DogAllOf) GetBreedOk() (*string, bool)`
GetBreedOk returns a tuple with the Breed field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetBreed
`func (o *DogAllOf) SetBreed(v string)`
SetBreed sets Breed field to given value.
### HasBreed
`func (o *DogAllOf) HasBreed() bool`
HasBreed returns a boolean if a field has been set.
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -1,82 +0,0 @@
# EnumArrays
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**JustSymbol** | Pointer to **string** | | [optional]
**ArrayEnum** | Pointer to **[]string** | | [optional]
## Methods
### NewEnumArrays
`func NewEnumArrays() *EnumArrays`
NewEnumArrays instantiates a new EnumArrays object
This constructor will assign default values to properties that have it defined,
and makes sure properties required by API are set, but the set of arguments
will change when the set of required properties is changed
### NewEnumArraysWithDefaults
`func NewEnumArraysWithDefaults() *EnumArrays`
NewEnumArraysWithDefaults instantiates a new EnumArrays object
This constructor will only assign default values to properties that have it defined,
but it doesn't guarantee that properties required by API are set
### GetJustSymbol
`func (o *EnumArrays) GetJustSymbol() string`
GetJustSymbol returns the JustSymbol field if non-nil, zero value otherwise.
### GetJustSymbolOk
`func (o *EnumArrays) GetJustSymbolOk() (*string, bool)`
GetJustSymbolOk returns a tuple with the JustSymbol field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetJustSymbol
`func (o *EnumArrays) SetJustSymbol(v string)`
SetJustSymbol sets JustSymbol field to given value.
### HasJustSymbol
`func (o *EnumArrays) HasJustSymbol() bool`
HasJustSymbol returns a boolean if a field has been set.
### GetArrayEnum
`func (o *EnumArrays) GetArrayEnum() []string`
GetArrayEnum returns the ArrayEnum field if non-nil, zero value otherwise.
### GetArrayEnumOk
`func (o *EnumArrays) GetArrayEnumOk() (*[]string, bool)`
GetArrayEnumOk returns a tuple with the ArrayEnum field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetArrayEnum
`func (o *EnumArrays) SetArrayEnum(v []string)`
SetArrayEnum sets ArrayEnum field to given value.
### HasArrayEnum
`func (o *EnumArrays) HasArrayEnum() bool`
HasArrayEnum returns a boolean if a field has been set.
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -1,11 +0,0 @@
# EnumClass
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

Some files were not shown because too many files have changed in this diff Show More