diff --git a/.github/workflows/samples-go-client.yaml b/.github/workflows/samples-go-client.yaml index 295b8cb1a87c..cea80e635249 100644 --- a/.github/workflows/samples-go-client.yaml +++ b/.github/workflows/samples-go-client.yaml @@ -9,6 +9,7 @@ on: - samples/client/others/go/allof_multiple_ref_and_discriminator/** - samples/client/others/go/oneof-anyof-required/** - samples/client/others/go/oneof-discriminator-lookup/** + - samples/client/others/go/oneof-not-enum/** - samples/client/others/go/issue_20079_go_regex_wrongly_translated/** pull_request: paths: @@ -18,6 +19,7 @@ on: - samples/client/others/go/allof_multiple_ref_and_discriminator/** - samples/client/others/go/oneof-anyof-required/** - samples/client/others/go/oneof-discriminator-lookup/** + - samples/client/others/go/oneof-not-enum/** - samples/client/others/go/issue_20079_go_regex_wrongly_translated/** jobs: build: @@ -33,6 +35,7 @@ jobs: - samples/client/others/go/allof_multiple_ref_and_discriminator/ - samples/client/others/go/oneof-anyof-required/ - samples/client/others/go/oneof-discriminator-lookup/ + - samples/client/others/go/oneof-not-enum/ - samples/client/others/go/issue_20079_go_regex_wrongly_translated/ steps: - uses: actions/checkout@v7 diff --git a/bin/configs/go-oneof-not-enum.yaml b/bin/configs/go-oneof-not-enum.yaml new file mode 100644 index 000000000000..60caea7ca389 --- /dev/null +++ b/bin/configs/go-oneof-not-enum.yaml @@ -0,0 +1,9 @@ +generatorName: go +outputDir: samples/client/others/go/oneof-not-enum +inputSpec: modules/openapi-generator/src/test/resources/3_1/go/oneof-not-enum.yaml +templateDir: modules/openapi-generator/src/test/resources/3_1/go +additionalProperties: + hideGenerationTimestamp: "true" +files: + oneof-not-enum_test.go: + destinationFilename: oneof-not-enum_test.go diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoClientCodegen.java index b350f19efa97..ddbe28864073 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoClientCodegen.java @@ -18,6 +18,7 @@ package org.openapitools.codegen.languages; import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.TextNode; import com.google.common.collect.Iterables; import com.samskivert.mustache.Mustache; import io.swagger.v3.oas.models.media.Schema; @@ -600,6 +601,147 @@ public ModelsMap postProcessModels(ModelsMap objs) { return objs; } + @Override + public Map postProcessAllModels(Map objs) { + objs = super.postProcessAllModels(objs); + if (!generateUnmarshalJSON) { + return objs; + } + + // Scope allowed-enum checks to oneOf variants whose sibling excludes values of the same property. + Map> allowedOneOfProperties = new IdentityHashMap<>(); + for (ModelsMap models : objs.values()) { + for (ModelMap modelMap : models.getModels()) { + CodegenModel union = modelMap.getModel(); + for (String excludedMemberName : union.oneOf) { + CodegenModel excludedMember = ModelUtils.getModelByName(excludedMemberName, objs); + if (excludedMember == null) { + continue; + } + for (CodegenProperty excludedProperty : effectiveVars(excludedMember).values()) { + CodegenProperty not = excludedProperty.getComposedSchemas() == null + ? null : excludedProperty.getComposedSchemas().getNot(); + if (stringEnumComparison(not, true) == null) { + continue; + } + for (String allowedMemberName : union.oneOf) { + if (allowedMemberName.equals(excludedMemberName)) { + continue; + } + CodegenModel allowedMember = ModelUtils.getModelByName(allowedMemberName, objs); + if (allowedMember == null) { + continue; + } + CodegenProperty allowedProperty = effectiveVars(allowedMember).get(excludedProperty.baseName); + if (stringEnumComparison(allowedProperty, false) != null) { + allowedOneOfProperties.computeIfAbsent(allowedMember, ignored -> new HashSet<>()) + .add(excludedProperty.baseName); + } + } + } + } + } + } + + for (ModelsMap models : objs.values()) { + for (ModelMap modelMap : models.getModels()) { + CodegenModel model = modelMap.getModel(); + if (model.isEnum || hasOneOf(model) || hasAnyOf(model)) { + continue; + } + // allOf children may need to validate properties inherited from their parent. + Map effectiveVars = effectiveVars(model); + Map ownVars = new HashMap<>(); + for (CodegenProperty param : model.vars) { + ownVars.put(param.baseName, param); + } + List validationVars = new ArrayList<>(); + boolean hasInheritedStringEnumValidation = false; + for (CodegenProperty param : effectiveVars.values()) { + String allowed = allowedOneOfProperties.getOrDefault(model, Collections.emptySet()).contains(param.baseName) + ? stringEnumComparison(param, false) : null; + CodegenProperty not = param.getComposedSchemas() == null ? null : param.getComposedSchemas().getNot(); + String excluded = stringEnumComparison(not, true); + if (allowed != null || excluded != null) { + hasInheritedStringEnumValidation |= !ownVars.containsKey(param.baseName); + if (ownVars.containsKey(param.baseName) && ownVars.get(param.baseName).vendorExtensions.containsKey("x-go-datatag") + && !param.vendorExtensions.containsKey("x-go-datatag")) { + param.vendorExtensions.put("x-go-datatag", ownVars.get(param.baseName).vendorExtensions.get("x-go-datatag")); + } + validationVars.add(param); + param.vendorExtensions.put("x-go-enum-property-name", TextNode.valueOf(param.baseName).toString()); + if (allowed != null) { + param.vendorExtensions.put("x-go-allowed-string-enum-comparison", allowed); + if (param.isNullable && (param.isEnumRef || ((List) param.allowableValues.get("values")).contains(null))) { + param.vendorExtensions.put("x-go-allowed-string-enum-null", true); + } + } + if (excluded != null) { + param.vendorExtensions.put("x-go-excluded-string-enum-comparison", excluded); + } + } + } + if (!validationVars.isEmpty()) { + model.vendorExtensions.put("x-go-has-string-enum-validation", true); + model.vendorExtensions.put("x-go-string-enum-validation-vars", validationVars); + List> imports = models.getImports(); + if (imports.stream().noneMatch(i -> "fmt".equals(i.get("import")))) { + imports.add(createMapping("import", "fmt")); + } + if (model.hasRequired && validationVars.stream().anyMatch(param -> param.required)) { + // Required-key checks must match the case-insensitive field names accepted by encoding/json. + model.vendorExtensions.put("x-go-enum-required-case-fold", true); + if (imports.stream().noneMatch(i -> "strings".equals(i.get("import")))) { + imports.add(createMapping("import", "strings")); + } + } + imports.sort(Comparator.comparing(i -> i.get("import"))); + } + if (hasInheritedStringEnumValidation && !model.isAdditionalPropertiesTrue) { + for (CodegenProperty param : effectiveVars.values()) { + param.vendorExtensions.put("x-go-flattened-json-name", TextNode.valueOf(param.baseName + (param.required ? "" : ",omitempty")).toString()); + } + model.vendorExtensions.put("x-go-inherited-string-enum-validation", true); + model.vendorExtensions.put("x-go-flattened-vars", new ArrayList<>(effectiveVars.values())); + } + } + } + return objs; + } + + /** Returns properties used for validation, including inherited allOf properties when present. */ + private static Map effectiveVars(CodegenModel model) { + Map vars = new LinkedHashMap<>(); + for (CodegenProperty param : model.parent == null ? model.vars : model.allVars) { + vars.put(param.baseName, param); + } + return vars; + } + + /** Builds a Go comparison for supported string/null enum values, using equality in exclusion mode. */ + private static String stringEnumComparison(CodegenProperty property, boolean excluded) { + if (property == null || !(property.isString && property.isEnum || property.isEnumRef) + || property.allowableValues == null + || !(property.allowableValues.get("values") instanceof List)) { + return null; + } + StringJoiner comparisons = new StringJoiner(excluded ? " || " : " && "); + for (Object value : (List) property.allowableValues.get("values")) { + if (value == null && excluded) { + comparisons.add("value == nil"); + continue; + } + if (value == null && property.isNullable) { + continue; + } + if (!(value instanceof String)) { + return null; + } + comparisons.add("value " + (excluded ? "==" : "!=") + " " + TextNode.valueOf((String) value)); + } + return comparisons.length() == 0 ? (property.isNullable && !excluded ? "true" : null) : comparisons.toString(); + } + /** * Prefixes the generated {@code unknown_default_open_api} enum case with the model name when enum class prefixing * is disabled. diff --git a/modules/openapi-generator/src/main/resources/go/model_simple.mustache b/modules/openapi-generator/src/main/resources/go/model_simple.mustache index 2690fb9bbf5d..0812882ce2ae 100644 --- a/modules/openapi-generator/src/main/resources/go/model_simple.mustache +++ b/modules/openapi-generator/src/main/resources/go/model_simple.mustache @@ -37,6 +37,89 @@ type _{{{classname}}} {{{classname}}} {{/hasRequired}} {{/isAdditionalPropertiesTrue}} +{{#vendorExtensions.x-go-has-string-enum-validation}} +func (o *{{{classname}}}) validateStringEnumValues(data []byte) error { + var fields struct { +{{#vendorExtensions.x-go-string-enum-validation-vars}} + {{name}} json.RawMessage{{#vendorExtensions.x-go-datatag}}{{{.}}}{{/vendorExtensions.x-go-datatag}}{{^vendorExtensions.x-go-datatag}} `json:{{{vendorExtensions.x-go-enum-property-name}}}`{{/vendorExtensions.x-go-datatag}} +{{/vendorExtensions.x-go-string-enum-validation-vars}} + } + if err := json.Unmarshal(data, &fields); err != nil { + return err + } +{{#vendorExtensions.x-go-string-enum-validation-vars}} +{{#vendorExtensions.x-go-allowed-string-enum-comparison}} + if raw := fields.{{name}}; raw != nil { +{{^vendorExtensions.x-go-allowed-string-enum-null}} + if string(raw) == "null" { + return fmt.Errorf("invalid null value for property %s", {{{vendorExtensions.x-go-enum-property-name}}}) + } +{{/vendorExtensions.x-go-allowed-string-enum-null}} + var value string + if err := json.Unmarshal(raw, &value); err != nil { + return err + } + if {{#vendorExtensions.x-go-allowed-string-enum-null}}string(raw) != "null" && ({{/vendorExtensions.x-go-allowed-string-enum-null}}{{{vendorExtensions.x-go-allowed-string-enum-comparison}}}{{#vendorExtensions.x-go-allowed-string-enum-null}}){{/vendorExtensions.x-go-allowed-string-enum-null}} { + return fmt.Errorf("invalid value %q for property %s", value, {{{vendorExtensions.x-go-enum-property-name}}}) + } + } +{{/vendorExtensions.x-go-allowed-string-enum-comparison}} +{{#vendorExtensions.x-go-excluded-string-enum-comparison}} + if raw := fields.{{name}}; raw != nil { + var value interface{} + if err := json.Unmarshal(raw, &value); err != nil { + return err + } + if {{{vendorExtensions.x-go-excluded-string-enum-comparison}}} { + return fmt.Errorf("excluded value %v for property %s", value, {{{vendorExtensions.x-go-enum-property-name}}}) + } + } +{{/vendorExtensions.x-go-excluded-string-enum-comparison}} +{{/vendorExtensions.x-go-string-enum-validation-vars}} + return nil +} + +{{^isAdditionalPropertiesTrue}} +{{^hasRequired}} +type _{{{classname}}} {{{classname}}} + +func (o *{{{classname}}}) UnmarshalJSON(data []byte) error { + if err := o.validateStringEnumValues(data); err != nil { + return err + } +{{#vendorExtensions.x-go-inherited-string-enum-validation}} + var decoded struct { +{{#vendorExtensions.x-go-flattened-vars}} +{{^-first}} + +{{/-first}} + {{name}} {{^required}}{{^isNullable}}{{^isArray}}{{^isFreeFormObject}}*{{/isFreeFormObject}}{{/isArray}}{{/isNullable}}{{/required}}{{{dataType}}}{{#vendorExtensions.x-go-datatag}}{{{.}}}{{/vendorExtensions.x-go-datatag}}{{^vendorExtensions.x-go-datatag}} `json:{{{vendorExtensions.x-go-flattened-json-name}}}`{{/vendorExtensions.x-go-datatag}} +{{/vendorExtensions.x-go-flattened-vars}} + } +{{#vendorExtensions.x-go-flattened-vars}} + decoded.{{name}} = o.{{name}} +{{/vendorExtensions.x-go-flattened-vars}} + if err := json.Unmarshal(data, &decoded); err != nil { + return err + } + *o = {{{classname}}}{} +{{#vendorExtensions.x-go-flattened-vars}} + o.{{name}} = decoded.{{name}} +{{/vendorExtensions.x-go-flattened-vars}} +{{/vendorExtensions.x-go-inherited-string-enum-validation}} +{{^vendorExtensions.x-go-inherited-string-enum-validation}} + value := _{{{classname}}}(*o) + if err := json.Unmarshal(data, &value); err != nil { + return err + } + *o = {{{classname}}}(value) +{{/vendorExtensions.x-go-inherited-string-enum-validation}} + return nil +} + +{{/hasRequired}} +{{/isAdditionalPropertiesTrue}} +{{/vendorExtensions.x-go-has-string-enum-validation}} // 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 @@ -360,10 +443,20 @@ func (o {{classname}}) ToMap() (map[string]interface{}, error) { {{#vendorExtensions.x-go-generate-unmarshal-json}} {{#isAdditionalPropertiesTrue}} func (o *{{{classname}}}) UnmarshalJSON(data []byte) (err error) { +{{#vendorExtensions.x-go-has-string-enum-validation}} + if err := o.validateStringEnumValues(data); err != nil { + return err + } +{{/vendorExtensions.x-go-has-string-enum-validation}} {{/isAdditionalPropertiesTrue}} {{^isAdditionalPropertiesTrue}} {{#hasRequired}} func (o *{{{classname}}}) UnmarshalJSON(data []byte) (err error) { +{{#vendorExtensions.x-go-has-string-enum-validation}} + if err := o.validateStringEnumValues(data); err != nil { + return err + } +{{/vendorExtensions.x-go-has-string-enum-validation}} {{/hasRequired}} {{/isAdditionalPropertiesTrue}} {{#hasRequired}} @@ -398,18 +491,51 @@ func (o *{{{classname}}}) UnmarshalJSON(data []byte) (err error) { return err; } +{{#vendorExtensions.x-go-enum-required-case-fold}} + lookupRequiredProperty := func(requiredProperty string) (interface{}, string, bool) { + if value, exists := allProperties[requiredProperty]; exists { + return value, requiredProperty, true + } + for name, value := range allProperties { + if strings.EqualFold(name, requiredProperty) { + return value, name, true + } + } + return nil, "", false + } +{{/vendorExtensions.x-go-enum-required-case-fold}} for _, requiredProperty := range(requiredProperties) { {{#useDefaultValuesForRequiredVars}} +{{#vendorExtensions.x-go-enum-required-case-fold}} + if value, matchedKey, exists := lookupRequiredProperty(requiredProperty); !exists || value == "" { +{{/vendorExtensions.x-go-enum-required-case-fold}} +{{^vendorExtensions.x-go-enum-required-case-fold}} if value, exists := allProperties[requiredProperty]; !exists || value == "" { +{{/vendorExtensions.x-go-enum-required-case-fold}} if _, ok := defaultValueFuncMap[requiredProperty]; ok { +{{#vendorExtensions.x-go-enum-required-case-fold}} + if exists && matchedKey != requiredProperty { + delete(allProperties, matchedKey) + } +{{/vendorExtensions.x-go-enum-required-case-fold}} allProperties[requiredProperty] = defaultValueFuncMap[requiredProperty]() defaultValueApplied = true } } +{{#vendorExtensions.x-go-enum-required-case-fold}} + if value, _, exists := lookupRequiredProperty(requiredProperty); !exists || value == ""{ +{{/vendorExtensions.x-go-enum-required-case-fold}} +{{^vendorExtensions.x-go-enum-required-case-fold}} if value, exists := allProperties[requiredProperty]; !exists || value == ""{ +{{/vendorExtensions.x-go-enum-required-case-fold}} {{/useDefaultValuesForRequiredVars}} {{^useDefaultValuesForRequiredVars}} +{{#vendorExtensions.x-go-enum-required-case-fold}} + if _, _, exists := lookupRequiredProperty(requiredProperty); !exists { +{{/vendorExtensions.x-go-enum-required-case-fold}} +{{^vendorExtensions.x-go-enum-required-case-fold}} if _, exists := allProperties[requiredProperty]; !exists { +{{/vendorExtensions.x-go-enum-required-case-fold}} {{/useDefaultValuesForRequiredVars}} return fmt.Errorf("no value given for required property %v", requiredProperty) } @@ -545,6 +671,29 @@ func (o *{{{classname}}}) UnmarshalJSON(data []byte) (err error) { {{/isAdditionalPropertiesTrue}} {{^isAdditionalPropertiesTrue}} {{#hasRequired}} +{{#vendorExtensions.x-go-inherited-string-enum-validation}} + var decoded struct { +{{#vendorExtensions.x-go-flattened-vars}} +{{^-first}} + +{{/-first}} + {{name}} {{^required}}{{^isNullable}}{{^isArray}}{{^isFreeFormObject}}*{{/isFreeFormObject}}{{/isArray}}{{/isNullable}}{{/required}}{{{dataType}}}{{#vendorExtensions.x-go-datatag}}{{{.}}}{{/vendorExtensions.x-go-datatag}}{{^vendorExtensions.x-go-datatag}} `json:{{{vendorExtensions.x-go-flattened-json-name}}}`{{/vendorExtensions.x-go-datatag}} +{{/vendorExtensions.x-go-flattened-vars}} + } + + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.DisallowUnknownFields() + if err = decoder.Decode(&decoded); err != nil { + return err + } + + *o = {{{classname}}}{} +{{#vendorExtensions.x-go-flattened-vars}} + o.{{name}} = decoded.{{name}} +{{/vendorExtensions.x-go-flattened-vars}} + return nil +{{/vendorExtensions.x-go-inherited-string-enum-validation}} +{{^vendorExtensions.x-go-inherited-string-enum-validation}} var{{{classname}}} := _{{{classname}}}{} decoder := json.NewDecoder(bytes.NewReader(data)) @@ -558,6 +707,7 @@ func (o *{{{classname}}}) UnmarshalJSON(data []byte) (err error) { *o = {{{classname}}}(var{{{classname}}}) return err +{{/vendorExtensions.x-go-inherited-string-enum-validation}} } {{/hasRequired}} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/go/GoClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/go/GoClientCodegenTest.java index 2614af52c801..bcfed0e4aca7 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/go/GoClientCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/go/GoClientCodegenTest.java @@ -27,12 +27,15 @@ import java.io.File; import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; public class GoClientCodegenTest { @@ -200,6 +203,109 @@ public void testJsonHeaderHelperDoesNotLeakAcrossGenerations() throws IOExceptio "parameterToJSONHeaderValue"); } + @Test + public void testStringNotEnumValidation() throws IOException, InterruptedException { + File output = Files.createTempDirectory("go-not-enum").toFile(); + output.deleteOnExit(); + + final CodegenConfigurator configurator = new CodegenConfigurator() + .setGeneratorName("go") + .setInputSpec("src/test/resources/3_1/go/oneof-not-enum.yaml") + .setOutputDir(output.getAbsolutePath()); + + new DefaultGenerator().opts(configurator.toClientOptInput()).generate().forEach(File::deleteOnExit); + + TestUtils.assertFileContains(Paths.get(output.getAbsolutePath(), "model_known.go"), + "if value != \"known\"", + "Kind json.RawMessage `json:\"kind\"`", + "strings.EqualFold(name, requiredProperty)", + "if raw := fields.Kind; raw != nil", + "if err := o.validateStringEnumValues(data); err != nil"); + TestUtils.assertFileContains(Paths.get(output.getAbsolutePath(), "model_other.go"), + "if value == \"known\"", + "excluded value %v for property %s", + "strings.EqualFold(name, requiredProperty)", + "if err := o.validateStringEnumValues(data); err != nil"); + TestUtils.assertFileContains(Paths.get(output.getAbsolutePath(), "model_optional_other.go"), + "if value == \"known\" || value == \"a\\\"b\"", + "Kind json.RawMessage `json:\"kind,omitempty\"`", + "value := _OptionalOther(*o)", + "func (o *OptionalOther) UnmarshalJSON(data []byte) error", + "if err := o.validateStringEnumValues(data); err != nil"); + TestUtils.assertFileContains(Paths.get(output.getAbsolutePath(), "model_any_other.go"), + "var value interface{}", + "if value == \"known\""); + TestUtils.assertFileContains(Paths.get(output.getAbsolutePath(), "model_nullable_enum.go"), + "if raw := fields.Kind; raw != nil", + "if string(raw) != \"null\" && (value != \"known\")"); + TestUtils.assertFileContains(Paths.get(output.getAbsolutePath(), "model_nullable_excluded_enum.go"), + "if value == \"known\" || value == nil", + "if err := o.validateStringEnumValues(data); err != nil"); + TestUtils.assertFileNotContains(Paths.get(output.getAbsolutePath(), "model_nullable_enum_without_null_value.go"), + "validateStringEnumValues"); + TestUtils.assertFileNotContains(Paths.get(output.getAbsolutePath(), "model_ordinary_enum.go"), + "validateStringEnumValues", "func (o *OrdinaryEnum) UnmarshalJSON"); + TestUtils.assertFileNotContains(Paths.get(output.getAbsolutePath(), "model_optional_enum_parent.go"), + "validateStringEnumValues"); + TestUtils.assertFileContains(Paths.get(output.getAbsolutePath(), "model_optional_enum_child.go"), + "func (o *OptionalEnumChild) validateStringEnumValues(data []byte) error", + "Kind json.RawMessage `json:\"kind\"`", + "if value != \"allowed\"", + "decoded.Kind = o.Kind", + "o.Kind = decoded.Kind", + "o.Label = decoded.Label", + "Dash *string `json:\"dash,omitempty\"`", + "o.Dash = decoded.Dash"); + + File allOfOutput = Files.createTempDirectory("go-inherited-enum").toFile(); + allOfOutput.deleteOnExit(); + final CodegenConfigurator allOfConfigurator = new CodegenConfigurator() + .setGeneratorName("go") + .setInputSpec("src/test/resources/3_0/go/allof_multiple_ref_and_discriminator.yaml") + .setOutputDir(allOfOutput.getAbsolutePath()); + new DefaultGenerator().opts(allOfConfigurator.toClientOptInput()).generate().forEach(File::deleteOnExit); + + TestUtils.assertFileNotContains(Paths.get(allOfOutput.getAbsolutePath(), "model_final_item.go"), + "validateStringEnumValues"); + + try { + Process goVersion = new ProcessBuilder("go", "version").start(); + if (goVersion.waitFor() != 0) { + return; + } + Matcher version = Pattern.compile("go(\\d+)\\.(\\d+)") + .matcher(new String(goVersion.getInputStream().readAllBytes(), StandardCharsets.UTF_8)); + if (!version.find() || Integer.parseInt(version.group(1)) < 1 + || (Integer.parseInt(version.group(1)) == 1 && Integer.parseInt(version.group(2)) < 23)) { + return; + } + } catch (IOException ignored) { + return; + } + Files.copy(Paths.get("src/test/resources/3_1/go/oneof-not-enum_test.go"), + Paths.get(output.getAbsolutePath(), "oneof-not-enum_test.go")).toFile().deleteOnExit(); + Process goTest = new ProcessBuilder("go", "test", "-mod=mod", "-run", "^TestStringEnumScope$", ".") + .directory(output).redirectErrorStream(true).start(); + String goOutput = new String(goTest.getInputStream().readAllBytes(), StandardCharsets.UTF_8); + Assert.assertEquals(goTest.waitFor(), 0, goOutput); + } + + @Test + public void testNullableStringEnumRefValidation() throws IOException { + File output = Files.createTempDirectory("go-nullable-enum-ref").toFile(); + output.deleteOnExit(); + + final CodegenConfigurator configurator = new CodegenConfigurator() + .setGeneratorName("go") + .setInputSpec("src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml") + .setOutputDir(output.getAbsolutePath()); + + new DefaultGenerator().opts(configurator.toClientOptInput()).generate().forEach(File::deleteOnExit); + + Path model = Paths.get(output.getAbsolutePath(), "model_enum_test_.go"); + TestUtils.assertFileNotContains(model, "validateStringEnumValues"); + } + @Test(description = "Verify form style query parameters explode an object instead of bracketing it") public void testExplodedObjectQueryParameter() throws IOException { File output = Files.createTempDirectory("test").toFile(); diff --git a/modules/openapi-generator/src/test/resources/3_1/go/oneof-not-enum.yaml b/modules/openapi-generator/src/test/resources/3_1/go/oneof-not-enum.yaml new file mode 100644 index 000000000000..868bfbccd9e5 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_1/go/oneof-not-enum.yaml @@ -0,0 +1,106 @@ +openapi: 3.1.0 +info: + title: oneOf not enum test + version: 1.0.0 +paths: {} +components: + schemas: + Known: + type: object + required: [kind] + properties: + kind: + type: string + enum: [known] + Other: + type: object + required: [kind] + properties: + kind: + type: string + not: + enum: [known] + TaggedUnion: + oneOf: + - $ref: '#/components/schemas/Known' + - $ref: '#/components/schemas/Other' + OrdinaryEnum: + type: object + properties: + status: + type: string + enum: [known] + ExcludedKinds: + type: string + enum: [known, 'a"b'] + OptionalOther: + type: object + properties: + kind: + type: string + not: + $ref: '#/components/schemas/ExcludedKinds' + label: + type: string + AnyOther: + type: object + properties: + kind: + not: + enum: [known] + NullableEnum: + type: object + properties: + kind: + type: [string, 'null'] + enum: [known, null] + NullableEnumWithoutNullValue: + type: object + properties: + kind: + type: [string, 'null'] + enum: [known] + NullableExcludedEnum: + type: object + properties: + kind: + type: [string, 'null'] + not: + enum: [known, null] + EnumNullUnion: + oneOf: + - $ref: '#/components/schemas/NullableEnum' + - $ref: '#/components/schemas/NullableExcludedEnum' + OptionalEnumParent: + type: object + properties: + kind: + type: string + enum: [allowed] + dash: + type: string + discriminator: + propertyName: kind + mapping: + allowed: '#/components/schemas/OptionalEnumChild' + OptionalEnumChildFields: + type: object + properties: + label: + type: string + OptionalEnumChild: + type: object + allOf: + - $ref: '#/components/schemas/OptionalEnumParent' + - $ref: '#/components/schemas/OptionalEnumChildFields' + OptionalEnumOther: + type: object + properties: + kind: + type: string + not: + enum: [allowed] + OptionalEnumUnion: + oneOf: + - $ref: '#/components/schemas/OptionalEnumChild' + - $ref: '#/components/schemas/OptionalEnumOther' diff --git a/modules/openapi-generator/src/test/resources/3_1/go/oneof-not-enum_test.go b/modules/openapi-generator/src/test/resources/3_1/go/oneof-not-enum_test.go new file mode 100644 index 000000000000..12bd8ac2c59f --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_1/go/oneof-not-enum_test.go @@ -0,0 +1,40 @@ +package openapi + +import ( + "encoding/json" + "testing" +) + +func TestStringEnumScope(t *testing.T) { + cases := []struct { + name string + model interface{} + payload string + valid bool + }{ + {"Known accepts known", &Known{}, `{"kind":"known"}`, true}, + {"Known rejects other", &Known{}, `{"kind":"other"}`, false}, + {"Other rejects known", &Other{}, `{"kind":"known"}`, false}, + {"Other accepts other", &Other{}, `{"kind":"other"}`, true}, + {"Known accepts KIND", &Known{}, `{"KIND":"known"}`, true}, + {"Other rejects KIND", &Other{}, `{"KIND":"known"}`, false}, + {"ordinary enum accepts unknown", &OrdinaryEnum{}, `{"status":"future"}`, true}, + } + for _, test := range cases { + t.Run(test.name, func(t *testing.T) { + err := json.Unmarshal([]byte(test.payload), test.model) + if (err == nil) != test.valid { + t.Errorf("UnmarshalJSON error = %v, valid = %v", err, test.valid) + } + }) + } + + var known TaggedUnion + if err := json.Unmarshal([]byte(`{"kind":"known"}`), &known); err != nil || known.Known == nil || known.Other != nil { + t.Errorf("known union variant: %+v, error: %v", known, err) + } + var other TaggedUnion + if err := json.Unmarshal([]byte(`{"kind":"other"}`), &other); err != nil || other.Other == nil || other.Known != nil { + t.Errorf("other union variant: %+v, error: %v", other, err) + } +} diff --git a/samples/client/others/go/oneof-not-enum/.gitignore b/samples/client/others/go/oneof-not-enum/.gitignore new file mode 100644 index 000000000000..daf913b1b347 --- /dev/null +++ b/samples/client/others/go/oneof-not-enum/.gitignore @@ -0,0 +1,24 @@ +# 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 diff --git a/samples/client/others/go/oneof-not-enum/.openapi-generator-ignore b/samples/client/others/go/oneof-not-enum/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/client/others/go/oneof-not-enum/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# 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 diff --git a/samples/client/others/go/oneof-not-enum/.openapi-generator/FILES b/samples/client/others/go/oneof-not-enum/.openapi-generator/FILES new file mode 100644 index 000000000000..e65403d6af4f --- /dev/null +++ b/samples/client/others/go/oneof-not-enum/.openapi-generator/FILES @@ -0,0 +1,44 @@ +.gitignore +.travis.yml +README.md +api/openapi.yaml +client.go +configuration.go +docs/AnyOther.md +docs/EnumNullUnion.md +docs/ExcludedKinds.md +docs/Known.md +docs/NullableEnum.md +docs/NullableEnumWithoutNullValue.md +docs/NullableExcludedEnum.md +docs/OptionalEnumChild.md +docs/OptionalEnumChildFields.md +docs/OptionalEnumOther.md +docs/OptionalEnumParent.md +docs/OptionalEnumUnion.md +docs/OptionalOther.md +docs/OrdinaryEnum.md +docs/Other.md +docs/TaggedUnion.md +git_push.sh +go.mod +go.sum +model_any_other.go +model_enum_null_union.go +model_excluded_kinds.go +model_known.go +model_nullable_enum.go +model_nullable_enum_without_null_value.go +model_nullable_excluded_enum.go +model_optional_enum_child.go +model_optional_enum_child_fields.go +model_optional_enum_other.go +model_optional_enum_parent.go +model_optional_enum_union.go +model_optional_other.go +model_ordinary_enum.go +model_other.go +model_tagged_union.go +oneof-not-enum_test.go +response.go +utils.go diff --git a/samples/client/others/go/oneof-not-enum/.openapi-generator/VERSION b/samples/client/others/go/oneof-not-enum/.openapi-generator/VERSION new file mode 100644 index 000000000000..32a8cfaceeb9 --- /dev/null +++ b/samples/client/others/go/oneof-not-enum/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.26.0-SNAPSHOT diff --git a/samples/client/others/go/oneof-not-enum/.travis.yml b/samples/client/others/go/oneof-not-enum/.travis.yml new file mode 100644 index 000000000000..f5cb2ce9a5aa --- /dev/null +++ b/samples/client/others/go/oneof-not-enum/.travis.yml @@ -0,0 +1,8 @@ +language: go + +install: + - go get -d -v . + +script: + - go build -v ./ + diff --git a/samples/client/others/go/oneof-not-enum/README.md b/samples/client/others/go/oneof-not-enum/README.md new file mode 100644 index 000000000000..11df24e6bc08 --- /dev/null +++ b/samples/client/others/go/oneof-not-enum/README.md @@ -0,0 +1,119 @@ +# Go API client for openapi + +No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + +## 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 +- Generator version: 7.26.0-SNAPSHOT +- Build package: org.openapitools.codegen.languages.GoClientCodegen + +## Installation + +Import the package in a go file in your project and run `go mod tidy`: + +```go +import openapi "github.com/GIT_USER_ID/GIT_REPO_ID" +``` + +To use a proxy, set the environment variable `HTTP_PROXY`: + +```go +os.Setenv("HTTP_PROXY", "http://proxy_name:proxy_port") +``` + +## 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 `openapi.ContextServerIndex` of type `int`. + +```go +ctx := context.WithValue(context.Background(), openapi.ContextServerIndex, 1) +``` + +### Templated Server URL + +Templated server URL is formatted using default variables from configuration or from context value `openapi.ContextServerVariables` of type `map[string]string`. + +```go +ctx := context.WithValue(context.Background(), openapi.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 identified by `"{classname}Service.{nickname}"` string. +Similar rules for overriding default operation server index and variables applies by using `openapi.ContextOperationServerIndices` and `openapi.ContextOperationServerVariables` context maps. + +```go +ctx := context.WithValue(context.Background(), openapi.ContextOperationServerIndices, map[string]int{ + "{classname}Service.{nickname}": 2, +}) +ctx = context.WithValue(context.Background(), openapi.ContextOperationServerVariables, map[string]map[string]string{ + "{classname}Service.{nickname}": { + "port": "8443", + }, +}) +``` + +## Documentation for API Endpoints + +All URIs are relative to *http://localhost* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- + + +## Documentation For Models + + - [AnyOther](docs/AnyOther.md) + - [EnumNullUnion](docs/EnumNullUnion.md) + - [ExcludedKinds](docs/ExcludedKinds.md) + - [Known](docs/Known.md) + - [NullableEnum](docs/NullableEnum.md) + - [NullableEnumWithoutNullValue](docs/NullableEnumWithoutNullValue.md) + - [NullableExcludedEnum](docs/NullableExcludedEnum.md) + - [OptionalEnumChild](docs/OptionalEnumChild.md) + - [OptionalEnumChildFields](docs/OptionalEnumChildFields.md) + - [OptionalEnumOther](docs/OptionalEnumOther.md) + - [OptionalEnumParent](docs/OptionalEnumParent.md) + - [OptionalEnumUnion](docs/OptionalEnumUnion.md) + - [OptionalOther](docs/OptionalOther.md) + - [OrdinaryEnum](docs/OrdinaryEnum.md) + - [Other](docs/Other.md) + - [TaggedUnion](docs/TaggedUnion.md) + + +## Documentation For Authorization + +Endpoints do not require authorization. + + +## 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 + + diff --git a/samples/client/others/go/oneof-not-enum/api/openapi.yaml b/samples/client/others/go/oneof-not-enum/api/openapi.yaml new file mode 100644 index 000000000000..2ee34dab93f9 --- /dev/null +++ b/samples/client/others/go/oneof-not-enum/api/openapi.yaml @@ -0,0 +1,115 @@ +openapi: 3.1.0 +info: + title: oneOf not enum test + version: 1.0.0 +servers: +- url: / +paths: {} +components: + schemas: + Known: + properties: + kind: + enum: + - known + type: string + required: + - kind + Other: + properties: + kind: + not: + enum: + - known + type: string + required: + - kind + TaggedUnion: + oneOf: + - $ref: "#/components/schemas/Known" + - $ref: "#/components/schemas/Other" + OrdinaryEnum: + properties: + status: + enum: + - known + type: string + ExcludedKinds: + enum: + - known + - a"b + type: string + OptionalOther: + properties: + kind: + not: + $ref: "#/components/schemas/ExcludedKinds" + type: string + label: + type: string + AnyOther: + properties: + kind: + not: + enum: + - known + type: string + NullableEnum: + properties: + kind: + enum: + - known + - null + nullable: true + type: string + NullableEnumWithoutNullValue: + properties: + kind: + enum: + - known + nullable: true + type: string + NullableExcludedEnum: + properties: + kind: + not: + enum: + - known + - null + nullable: true + type: string + EnumNullUnion: + oneOf: + - $ref: "#/components/schemas/NullableEnum" + - $ref: "#/components/schemas/NullableExcludedEnum" + OptionalEnumParent: + discriminator: + mapping: + allowed: "#/components/schemas/OptionalEnumChild" + propertyName: kind + properties: + kind: + enum: + - allowed + type: string + dash: + type: string + OptionalEnumChildFields: + properties: + label: + type: string + OptionalEnumChild: + allOf: + - $ref: "#/components/schemas/OptionalEnumParent" + - $ref: "#/components/schemas/OptionalEnumChildFields" + OptionalEnumOther: + properties: + kind: + not: + enum: + - allowed + type: string + OptionalEnumUnion: + oneOf: + - $ref: "#/components/schemas/OptionalEnumChild" + - $ref: "#/components/schemas/OptionalEnumOther" diff --git a/samples/client/others/go/oneof-not-enum/client.go b/samples/client/others/go/oneof-not-enum/client.go new file mode 100644 index 000000000000..a14506ac8a87 --- /dev/null +++ b/samples/client/others/go/oneof-not-enum/client.go @@ -0,0 +1,698 @@ +/* +oneOf not enum test + +No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + +API version: 1.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +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" + +) + +var ( + JsonCheck = regexp.MustCompile(`(?i:(?:application|text)/(?:[^;]+\+)?json)`) + XmlCheck = regexp.MustCompile(`(?i:(?:application|text)/(?:[^;]+\+)?xml)`) + queryParamSplit = regexp.MustCompile(`(^|&)([^&]+)`) + queryDescape = strings.NewReplacer( "%5B", "[", "%5D", "]" ) +) + +// APIClient manages communication with the oneOf not enum test 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 +} + +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 + + 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 insensitive match, finding needle in a haystack +func contains(haystack []string, needle string) bool { + for _, a := range haystack { + if strings.EqualFold(a, 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 +} + +func parameterValueToString( obj interface{}, key string ) string { + if reflect.TypeOf(obj).Kind() != reflect.Ptr { + if actualObj, ok := obj.(interface{ GetActualInstanceValue() interface{} }); ok { + return fmt.Sprintf("%v", actualObj.GetActualInstanceValue()) + } + + return fmt.Sprintf("%v", obj) + } + var param,ok = obj.(MappedNullable) + if !ok { + return "" + } + dataMap,err := param.ToMap() + if err != nil { + return "" + } + return fmt.Sprintf("%v", dataMap[key]) +} + +// parameterAddToHeaderOrQuery adds the provided object to the request header or url query +// supporting deep object syntax +func parameterAddToHeaderOrQuery(headerOrQueryParams interface{}, keyPrefix string, obj interface{}, style string, collectionType string) { + var v = reflect.ValueOf(obj) + var value = "" + if v == reflect.ValueOf(nil) { + value = "null" + } else { + switch v.Kind() { + case reflect.Invalid: + value = "invalid" + + case reflect.Struct: + if t,ok := obj.(MappedNullable); ok { + dataMap,err := t.ToMap() + if err != nil { + return + } + parameterAddToHeaderOrQuery(headerOrQueryParams, keyPrefix, dataMap, style, collectionType) + return + } + if t, ok := obj.(time.Time); ok { + parameterAddToHeaderOrQuery(headerOrQueryParams, keyPrefix, t.Format(time.RFC3339Nano), style, collectionType) + return + } + value = v.Type().String() + " value" + case reflect.Slice: + var indValue = reflect.ValueOf(obj) + if indValue == reflect.ValueOf(nil) { + return + } + var lenIndValue = indValue.Len() + for i:=0;i 0 || (len(formFiles) > 0) { + 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) + } + } + } + for _, formFile := range formFiles { + if len(formFile.fileBytes) > 0 && formFile.fileName != "" { + w.Boundary() + part, err := w.CreateFormFile(formFile.formFileName, filepath.Base(formFile.fileName)) + if err != nil { + return nil, err + } + _, err = part.Write(formFile.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 = queryParamSplit.ReplaceAllStringFunc(query.Encode(), func(s string) string { + pieces := strings.Split(s, "=") + pieces[0] = queryDescape.Replace(pieces[0]) + return strings.Join(pieces, "=") + }) + + // 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[h] = []string{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. + + } + + 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 r, ok := v.(*io.Reader); ok { + *r = bytes.NewReader(b) + return nil + } + // Must stay before the JSON branch: json.Unmarshal would base64-decode into *[]byte. + if p, ok := v.(*[]byte); ok { + *p = b + return nil + } + if f, ok := v.(*os.File); ok { + f, err = os.CreateTemp("", "HttpClientFile") + if err != nil { + return + } + _, err = f.Write(b) + if err != nil { + return + } + _, err = f.Seek(0, io.SeekStart) + return + } + if f, ok := v.(**os.File); ok { + *f, err = os.CreateTemp("", "HttpClientFile") + if err != nil { + return + } + _, err = (*f).Write(b) + if err != nil { + return + } + _, err = (*f).Seek(0, io.SeekStart) + return + } + 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 { + return 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(filepath.Clean(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 +} + +// 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 fp, ok := body.(*os.File); ok { + _, err = bodyBuf.ReadFrom(fp) + } 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) { + var bs []byte + bs, err = xml.Marshal(body) + if err == nil { + bodyBuf.Write(bs) + } + } + + 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 +} + +// format error message using title and detail when model implements rfc7807 +func formatErrorMessage(status string, v interface{}) string { + str := "" + metaValue := reflect.ValueOf(v).Elem() + + if metaValue.Kind() == reflect.Struct { + field := metaValue.FieldByName("Title") + if field != (reflect.Value{}) { + str = fmt.Sprintf("%s", field.Interface()) + } + + field = metaValue.FieldByName("Detail") + if field != (reflect.Value{}) { + str = fmt.Sprintf("%s (%s)", str, field.Interface()) + } + } + + return strings.TrimSpace(fmt.Sprintf("%s %s", status, str)) +} diff --git a/samples/client/others/go/oneof-not-enum/configuration.go b/samples/client/others/go/oneof-not-enum/configuration.go new file mode 100644 index 000000000000..f5867a344ed4 --- /dev/null +++ b/samples/client/others/go/oneof-not-enum/configuration.go @@ -0,0 +1,215 @@ +/* +oneOf not enum test + +No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + +API version: 1.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +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 ( + // 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: "", + 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) +} diff --git a/samples/client/others/go/oneof-not-enum/docs/AnyOther.md b/samples/client/others/go/oneof-not-enum/docs/AnyOther.md new file mode 100644 index 000000000000..6fbe57990ae3 --- /dev/null +++ b/samples/client/others/go/oneof-not-enum/docs/AnyOther.md @@ -0,0 +1,66 @@ +# AnyOther + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Kind** | Pointer to **interface{}** | | [optional] + +## Methods + +### NewAnyOther + +`func NewAnyOther() *AnyOther` + +NewAnyOther instantiates a new AnyOther 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 + +### NewAnyOtherWithDefaults + +`func NewAnyOtherWithDefaults() *AnyOther` + +NewAnyOtherWithDefaults instantiates a new AnyOther 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 *AnyOther) GetKind() interface{}` + +GetKind returns the Kind field if non-nil, zero value otherwise. + +### GetKindOk + +`func (o *AnyOther) GetKindOk() (*interface{}, 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 *AnyOther) SetKind(v interface{})` + +SetKind sets Kind field to given value. + +### HasKind + +`func (o *AnyOther) HasKind() bool` + +HasKind returns a boolean if a field has been set. + +### SetKindNil + +`func (o *AnyOther) SetKindNil(b bool)` + + SetKindNil sets the value for Kind to be an explicit nil + +### UnsetKind +`func (o *AnyOther) UnsetKind()` + +UnsetKind ensures that no value is present for Kind, not even an explicit nil + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/others/go/oneof-not-enum/docs/EnumNullUnion.md b/samples/client/others/go/oneof-not-enum/docs/EnumNullUnion.md new file mode 100644 index 000000000000..3dcae4fc7ccd --- /dev/null +++ b/samples/client/others/go/oneof-not-enum/docs/EnumNullUnion.md @@ -0,0 +1,56 @@ +# EnumNullUnion + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Kind** | Pointer to **string** | | [optional] + +## Methods + +### NewEnumNullUnion + +`func NewEnumNullUnion() *EnumNullUnion` + +NewEnumNullUnion instantiates a new EnumNullUnion 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 + +### NewEnumNullUnionWithDefaults + +`func NewEnumNullUnionWithDefaults() *EnumNullUnion` + +NewEnumNullUnionWithDefaults instantiates a new EnumNullUnion 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 *EnumNullUnion) GetKind() string` + +GetKind returns the Kind field if non-nil, zero value otherwise. + +### GetKindOk + +`func (o *EnumNullUnion) 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 *EnumNullUnion) SetKind(v string)` + +SetKind sets Kind field to given value. + +### HasKind + +`func (o *EnumNullUnion) 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) + + diff --git a/samples/client/others/go/oneof-not-enum/docs/ExcludedKinds.md b/samples/client/others/go/oneof-not-enum/docs/ExcludedKinds.md new file mode 100644 index 000000000000..99b496b130ac --- /dev/null +++ b/samples/client/others/go/oneof-not-enum/docs/ExcludedKinds.md @@ -0,0 +1,13 @@ +# ExcludedKinds + +## Enum + + +* `KNOWN` (value: `"known"`) + +* `AB` (value: `"a\"b"`) + + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/others/go/oneof-not-enum/docs/Known.md b/samples/client/others/go/oneof-not-enum/docs/Known.md new file mode 100644 index 000000000000..c92d8c6650e4 --- /dev/null +++ b/samples/client/others/go/oneof-not-enum/docs/Known.md @@ -0,0 +1,51 @@ +# Known + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Kind** | **string** | | + +## Methods + +### NewKnown + +`func NewKnown(kind string, ) *Known` + +NewKnown instantiates a new Known 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 + +### NewKnownWithDefaults + +`func NewKnownWithDefaults() *Known` + +NewKnownWithDefaults instantiates a new Known 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 *Known) GetKind() string` + +GetKind returns the Kind field if non-nil, zero value otherwise. + +### GetKindOk + +`func (o *Known) 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 *Known) SetKind(v string)` + +SetKind sets Kind 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) + + diff --git a/samples/client/others/go/oneof-not-enum/docs/NullableEnum.md b/samples/client/others/go/oneof-not-enum/docs/NullableEnum.md new file mode 100644 index 000000000000..2eff9f5a83f3 --- /dev/null +++ b/samples/client/others/go/oneof-not-enum/docs/NullableEnum.md @@ -0,0 +1,66 @@ +# NullableEnum + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Kind** | Pointer to **NullableString** | | [optional] + +## Methods + +### NewNullableEnum + +`func NewNullableEnum() *NullableEnum` + +NewNullableEnum instantiates a new NullableEnum 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 + +### NewNullableEnumWithDefaults + +`func NewNullableEnumWithDefaults() *NullableEnum` + +NewNullableEnumWithDefaults instantiates a new NullableEnum 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 *NullableEnum) GetKind() string` + +GetKind returns the Kind field if non-nil, zero value otherwise. + +### GetKindOk + +`func (o *NullableEnum) 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 *NullableEnum) SetKind(v string)` + +SetKind sets Kind field to given value. + +### HasKind + +`func (o *NullableEnum) HasKind() bool` + +HasKind returns a boolean if a field has been set. + +### SetKindNil + +`func (o *NullableEnum) SetKindNil(b bool)` + + SetKindNil sets the value for Kind to be an explicit nil + +### UnsetKind +`func (o *NullableEnum) UnsetKind()` + +UnsetKind ensures that no value is present for Kind, not even an explicit nil + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/others/go/oneof-not-enum/docs/NullableEnumWithoutNullValue.md b/samples/client/others/go/oneof-not-enum/docs/NullableEnumWithoutNullValue.md new file mode 100644 index 000000000000..4fcbbb918cb1 --- /dev/null +++ b/samples/client/others/go/oneof-not-enum/docs/NullableEnumWithoutNullValue.md @@ -0,0 +1,66 @@ +# NullableEnumWithoutNullValue + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Kind** | Pointer to **NullableString** | | [optional] + +## Methods + +### NewNullableEnumWithoutNullValue + +`func NewNullableEnumWithoutNullValue() *NullableEnumWithoutNullValue` + +NewNullableEnumWithoutNullValue instantiates a new NullableEnumWithoutNullValue 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 + +### NewNullableEnumWithoutNullValueWithDefaults + +`func NewNullableEnumWithoutNullValueWithDefaults() *NullableEnumWithoutNullValue` + +NewNullableEnumWithoutNullValueWithDefaults instantiates a new NullableEnumWithoutNullValue 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 *NullableEnumWithoutNullValue) GetKind() string` + +GetKind returns the Kind field if non-nil, zero value otherwise. + +### GetKindOk + +`func (o *NullableEnumWithoutNullValue) 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 *NullableEnumWithoutNullValue) SetKind(v string)` + +SetKind sets Kind field to given value. + +### HasKind + +`func (o *NullableEnumWithoutNullValue) HasKind() bool` + +HasKind returns a boolean if a field has been set. + +### SetKindNil + +`func (o *NullableEnumWithoutNullValue) SetKindNil(b bool)` + + SetKindNil sets the value for Kind to be an explicit nil + +### UnsetKind +`func (o *NullableEnumWithoutNullValue) UnsetKind()` + +UnsetKind ensures that no value is present for Kind, not even an explicit nil + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/others/go/oneof-not-enum/docs/NullableExcludedEnum.md b/samples/client/others/go/oneof-not-enum/docs/NullableExcludedEnum.md new file mode 100644 index 000000000000..9d219683806a --- /dev/null +++ b/samples/client/others/go/oneof-not-enum/docs/NullableExcludedEnum.md @@ -0,0 +1,66 @@ +# NullableExcludedEnum + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Kind** | Pointer to **NullableString** | | [optional] + +## Methods + +### NewNullableExcludedEnum + +`func NewNullableExcludedEnum() *NullableExcludedEnum` + +NewNullableExcludedEnum instantiates a new NullableExcludedEnum 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 + +### NewNullableExcludedEnumWithDefaults + +`func NewNullableExcludedEnumWithDefaults() *NullableExcludedEnum` + +NewNullableExcludedEnumWithDefaults instantiates a new NullableExcludedEnum 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 *NullableExcludedEnum) GetKind() string` + +GetKind returns the Kind field if non-nil, zero value otherwise. + +### GetKindOk + +`func (o *NullableExcludedEnum) 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 *NullableExcludedEnum) SetKind(v string)` + +SetKind sets Kind field to given value. + +### HasKind + +`func (o *NullableExcludedEnum) HasKind() bool` + +HasKind returns a boolean if a field has been set. + +### SetKindNil + +`func (o *NullableExcludedEnum) SetKindNil(b bool)` + + SetKindNil sets the value for Kind to be an explicit nil + +### UnsetKind +`func (o *NullableExcludedEnum) UnsetKind()` + +UnsetKind ensures that no value is present for Kind, not even an explicit nil + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/others/go/oneof-not-enum/docs/OptionalEnumChild.md b/samples/client/others/go/oneof-not-enum/docs/OptionalEnumChild.md new file mode 100644 index 000000000000..a582da35cd5c --- /dev/null +++ b/samples/client/others/go/oneof-not-enum/docs/OptionalEnumChild.md @@ -0,0 +1,56 @@ +# OptionalEnumChild + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Label** | Pointer to **string** | | [optional] + +## Methods + +### NewOptionalEnumChild + +`func NewOptionalEnumChild() *OptionalEnumChild` + +NewOptionalEnumChild instantiates a new OptionalEnumChild 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 + +### NewOptionalEnumChildWithDefaults + +`func NewOptionalEnumChildWithDefaults() *OptionalEnumChild` + +NewOptionalEnumChildWithDefaults instantiates a new OptionalEnumChild 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 + +### GetLabel + +`func (o *OptionalEnumChild) GetLabel() string` + +GetLabel returns the Label field if non-nil, zero value otherwise. + +### GetLabelOk + +`func (o *OptionalEnumChild) GetLabelOk() (*string, bool)` + +GetLabelOk returns a tuple with the Label field if it's non-nil, zero value otherwise +and a boolean to check if the value has been set. + +### SetLabel + +`func (o *OptionalEnumChild) SetLabel(v string)` + +SetLabel sets Label field to given value. + +### HasLabel + +`func (o *OptionalEnumChild) HasLabel() bool` + +HasLabel 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) + + diff --git a/samples/client/others/go/oneof-not-enum/docs/OptionalEnumChildFields.md b/samples/client/others/go/oneof-not-enum/docs/OptionalEnumChildFields.md new file mode 100644 index 000000000000..30c8749e7308 --- /dev/null +++ b/samples/client/others/go/oneof-not-enum/docs/OptionalEnumChildFields.md @@ -0,0 +1,56 @@ +# OptionalEnumChildFields + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Label** | Pointer to **string** | | [optional] + +## Methods + +### NewOptionalEnumChildFields + +`func NewOptionalEnumChildFields() *OptionalEnumChildFields` + +NewOptionalEnumChildFields instantiates a new OptionalEnumChildFields 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 + +### NewOptionalEnumChildFieldsWithDefaults + +`func NewOptionalEnumChildFieldsWithDefaults() *OptionalEnumChildFields` + +NewOptionalEnumChildFieldsWithDefaults instantiates a new OptionalEnumChildFields 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 + +### GetLabel + +`func (o *OptionalEnumChildFields) GetLabel() string` + +GetLabel returns the Label field if non-nil, zero value otherwise. + +### GetLabelOk + +`func (o *OptionalEnumChildFields) GetLabelOk() (*string, bool)` + +GetLabelOk returns a tuple with the Label field if it's non-nil, zero value otherwise +and a boolean to check if the value has been set. + +### SetLabel + +`func (o *OptionalEnumChildFields) SetLabel(v string)` + +SetLabel sets Label field to given value. + +### HasLabel + +`func (o *OptionalEnumChildFields) HasLabel() bool` + +HasLabel 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) + + diff --git a/samples/client/others/go/oneof-not-enum/docs/OptionalEnumOther.md b/samples/client/others/go/oneof-not-enum/docs/OptionalEnumOther.md new file mode 100644 index 000000000000..43d07ac3ccba --- /dev/null +++ b/samples/client/others/go/oneof-not-enum/docs/OptionalEnumOther.md @@ -0,0 +1,56 @@ +# OptionalEnumOther + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Kind** | Pointer to **string** | | [optional] + +## Methods + +### NewOptionalEnumOther + +`func NewOptionalEnumOther() *OptionalEnumOther` + +NewOptionalEnumOther instantiates a new OptionalEnumOther 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 + +### NewOptionalEnumOtherWithDefaults + +`func NewOptionalEnumOtherWithDefaults() *OptionalEnumOther` + +NewOptionalEnumOtherWithDefaults instantiates a new OptionalEnumOther 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 *OptionalEnumOther) GetKind() string` + +GetKind returns the Kind field if non-nil, zero value otherwise. + +### GetKindOk + +`func (o *OptionalEnumOther) 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 *OptionalEnumOther) SetKind(v string)` + +SetKind sets Kind field to given value. + +### HasKind + +`func (o *OptionalEnumOther) 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) + + diff --git a/samples/client/others/go/oneof-not-enum/docs/OptionalEnumParent.md b/samples/client/others/go/oneof-not-enum/docs/OptionalEnumParent.md new file mode 100644 index 000000000000..2bb863daf5a8 --- /dev/null +++ b/samples/client/others/go/oneof-not-enum/docs/OptionalEnumParent.md @@ -0,0 +1,82 @@ +# OptionalEnumParent + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Kind** | Pointer to **string** | | [optional] +**Dash** | Pointer to **string** | | [optional] + +## Methods + +### NewOptionalEnumParent + +`func NewOptionalEnumParent() *OptionalEnumParent` + +NewOptionalEnumParent instantiates a new OptionalEnumParent 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 + +### NewOptionalEnumParentWithDefaults + +`func NewOptionalEnumParentWithDefaults() *OptionalEnumParent` + +NewOptionalEnumParentWithDefaults instantiates a new OptionalEnumParent 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 *OptionalEnumParent) GetKind() string` + +GetKind returns the Kind field if non-nil, zero value otherwise. + +### GetKindOk + +`func (o *OptionalEnumParent) 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 *OptionalEnumParent) SetKind(v string)` + +SetKind sets Kind field to given value. + +### HasKind + +`func (o *OptionalEnumParent) HasKind() bool` + +HasKind returns a boolean if a field has been set. + +### GetDash + +`func (o *OptionalEnumParent) GetDash() string` + +GetDash returns the Dash field if non-nil, zero value otherwise. + +### GetDashOk + +`func (o *OptionalEnumParent) GetDashOk() (*string, bool)` + +GetDashOk returns a tuple with the Dash field if it's non-nil, zero value otherwise +and a boolean to check if the value has been set. + +### SetDash + +`func (o *OptionalEnumParent) SetDash(v string)` + +SetDash sets Dash field to given value. + +### HasDash + +`func (o *OptionalEnumParent) HasDash() bool` + +HasDash 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) + + diff --git a/samples/client/others/go/oneof-not-enum/docs/OptionalEnumUnion.md b/samples/client/others/go/oneof-not-enum/docs/OptionalEnumUnion.md new file mode 100644 index 000000000000..155913d9b355 --- /dev/null +++ b/samples/client/others/go/oneof-not-enum/docs/OptionalEnumUnion.md @@ -0,0 +1,56 @@ +# OptionalEnumUnion + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Kind** | Pointer to **string** | | [optional] + +## Methods + +### NewOptionalEnumUnion + +`func NewOptionalEnumUnion() *OptionalEnumUnion` + +NewOptionalEnumUnion instantiates a new OptionalEnumUnion 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 + +### NewOptionalEnumUnionWithDefaults + +`func NewOptionalEnumUnionWithDefaults() *OptionalEnumUnion` + +NewOptionalEnumUnionWithDefaults instantiates a new OptionalEnumUnion 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 *OptionalEnumUnion) GetKind() string` + +GetKind returns the Kind field if non-nil, zero value otherwise. + +### GetKindOk + +`func (o *OptionalEnumUnion) 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 *OptionalEnumUnion) SetKind(v string)` + +SetKind sets Kind field to given value. + +### HasKind + +`func (o *OptionalEnumUnion) 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) + + diff --git a/samples/client/others/go/oneof-not-enum/docs/OptionalOther.md b/samples/client/others/go/oneof-not-enum/docs/OptionalOther.md new file mode 100644 index 000000000000..ae663ac2f1c9 --- /dev/null +++ b/samples/client/others/go/oneof-not-enum/docs/OptionalOther.md @@ -0,0 +1,82 @@ +# OptionalOther + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Kind** | Pointer to **string** | | [optional] +**Label** | Pointer to **string** | | [optional] + +## Methods + +### NewOptionalOther + +`func NewOptionalOther() *OptionalOther` + +NewOptionalOther instantiates a new OptionalOther 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 + +### NewOptionalOtherWithDefaults + +`func NewOptionalOtherWithDefaults() *OptionalOther` + +NewOptionalOtherWithDefaults instantiates a new OptionalOther 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 *OptionalOther) GetKind() string` + +GetKind returns the Kind field if non-nil, zero value otherwise. + +### GetKindOk + +`func (o *OptionalOther) 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 *OptionalOther) SetKind(v string)` + +SetKind sets Kind field to given value. + +### HasKind + +`func (o *OptionalOther) HasKind() bool` + +HasKind returns a boolean if a field has been set. + +### GetLabel + +`func (o *OptionalOther) GetLabel() string` + +GetLabel returns the Label field if non-nil, zero value otherwise. + +### GetLabelOk + +`func (o *OptionalOther) GetLabelOk() (*string, bool)` + +GetLabelOk returns a tuple with the Label field if it's non-nil, zero value otherwise +and a boolean to check if the value has been set. + +### SetLabel + +`func (o *OptionalOther) SetLabel(v string)` + +SetLabel sets Label field to given value. + +### HasLabel + +`func (o *OptionalOther) HasLabel() bool` + +HasLabel 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) + + diff --git a/samples/client/others/go/oneof-not-enum/docs/OrdinaryEnum.md b/samples/client/others/go/oneof-not-enum/docs/OrdinaryEnum.md new file mode 100644 index 000000000000..d7d9196cad24 --- /dev/null +++ b/samples/client/others/go/oneof-not-enum/docs/OrdinaryEnum.md @@ -0,0 +1,56 @@ +# OrdinaryEnum + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Status** | Pointer to **string** | | [optional] + +## Methods + +### NewOrdinaryEnum + +`func NewOrdinaryEnum() *OrdinaryEnum` + +NewOrdinaryEnum instantiates a new OrdinaryEnum 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 + +### NewOrdinaryEnumWithDefaults + +`func NewOrdinaryEnumWithDefaults() *OrdinaryEnum` + +NewOrdinaryEnumWithDefaults instantiates a new OrdinaryEnum 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 + +### GetStatus + +`func (o *OrdinaryEnum) GetStatus() string` + +GetStatus returns the Status field if non-nil, zero value otherwise. + +### GetStatusOk + +`func (o *OrdinaryEnum) GetStatusOk() (*string, bool)` + +GetStatusOk returns a tuple with the Status field if it's non-nil, zero value otherwise +and a boolean to check if the value has been set. + +### SetStatus + +`func (o *OrdinaryEnum) SetStatus(v string)` + +SetStatus sets Status field to given value. + +### HasStatus + +`func (o *OrdinaryEnum) HasStatus() bool` + +HasStatus 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) + + diff --git a/samples/client/others/go/oneof-not-enum/docs/Other.md b/samples/client/others/go/oneof-not-enum/docs/Other.md new file mode 100644 index 000000000000..848d0b25a351 --- /dev/null +++ b/samples/client/others/go/oneof-not-enum/docs/Other.md @@ -0,0 +1,51 @@ +# Other + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Kind** | **string** | | + +## Methods + +### NewOther + +`func NewOther(kind string, ) *Other` + +NewOther instantiates a new Other 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 + +### NewOtherWithDefaults + +`func NewOtherWithDefaults() *Other` + +NewOtherWithDefaults instantiates a new Other 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 *Other) GetKind() string` + +GetKind returns the Kind field if non-nil, zero value otherwise. + +### GetKindOk + +`func (o *Other) 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 *Other) SetKind(v string)` + +SetKind sets Kind 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) + + diff --git a/samples/client/others/go/oneof-not-enum/docs/TaggedUnion.md b/samples/client/others/go/oneof-not-enum/docs/TaggedUnion.md new file mode 100644 index 000000000000..3bfe6bfd446a --- /dev/null +++ b/samples/client/others/go/oneof-not-enum/docs/TaggedUnion.md @@ -0,0 +1,51 @@ +# TaggedUnion + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Kind** | **string** | | + +## Methods + +### NewTaggedUnion + +`func NewTaggedUnion(kind string, ) *TaggedUnion` + +NewTaggedUnion instantiates a new TaggedUnion 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 + +### NewTaggedUnionWithDefaults + +`func NewTaggedUnionWithDefaults() *TaggedUnion` + +NewTaggedUnionWithDefaults instantiates a new TaggedUnion 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 *TaggedUnion) GetKind() string` + +GetKind returns the Kind field if non-nil, zero value otherwise. + +### GetKindOk + +`func (o *TaggedUnion) 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 *TaggedUnion) SetKind(v string)` + +SetKind sets Kind 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) + + diff --git a/samples/client/others/go/oneof-not-enum/git_push.sh b/samples/client/others/go/oneof-not-enum/git_push.sh new file mode 100644 index 000000000000..a35991cd51a1 --- /dev/null +++ b/samples/client/others/go/oneof-not-enum/git_push.sh @@ -0,0 +1,54 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ -z "${git_host}" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \${git_host} to ${git_host}" +fi + +if [ -z "${git_user_id}" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \${git_user_id} to ${git_user_id}" +fi + +if [ -z "${git_repo_id}" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \${git_repo_id} to ${git_repo_id}" +fi + +if [ -z "${release_note}" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \${release_note} to ${release_note}" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "${release_note}" + +# Sets the new remote +if [ -z "$(git remote)" ]; then # git remote not defined + if [ -z "${GIT_TOKEN:-}" ]; then + echo "[INFO] \${GIT_TOKEN} (environment variable) is not set. Using the git credential in your environment." + git remote add origin "https://${git_host}/${git_user_id}/${git_repo_id}.git" + else + git remote add origin "https://${git_user_id}:${GIT_TOKEN}@${git_host}/${git_user_id}/${git_repo_id}.git" + fi +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' diff --git a/samples/client/others/go/oneof-not-enum/go.mod b/samples/client/others/go/oneof-not-enum/go.mod new file mode 100644 index 000000000000..7b0c0ad16fff --- /dev/null +++ b/samples/client/others/go/oneof-not-enum/go.mod @@ -0,0 +1,7 @@ +module github.com/GIT_USER_ID/GIT_REPO_ID + +go 1.23 + +require ( + gopkg.in/validator.v2 v2.0.1 +) diff --git a/samples/client/others/go/oneof-not-enum/go.sum b/samples/client/others/go/oneof-not-enum/go.sum new file mode 100644 index 000000000000..525afa0f381c --- /dev/null +++ b/samples/client/others/go/oneof-not-enum/go.sum @@ -0,0 +1,13 @@ +cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +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/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= +gopkg.in/validator.v2 v2.0.1 h1:xF0KWyGWXm/LM2G1TrEjqOu4pa6coO9AlWSf3msVfDY= +gopkg.in/validator.v2 v2.0.1/go.mod h1:lIUZBlB3Im4s/eYp39Ry/wkR02yOPhZ9IwIRBjuPuG8= diff --git a/samples/client/others/go/oneof-not-enum/model_any_other.go b/samples/client/others/go/oneof-not-enum/model_any_other.go new file mode 100644 index 000000000000..3ebc3d3a39e6 --- /dev/null +++ b/samples/client/others/go/oneof-not-enum/model_any_other.go @@ -0,0 +1,161 @@ +/* +oneOf not enum test + +No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + +API version: 1.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "encoding/json" + "fmt" +) + +// checks if the AnyOther type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &AnyOther{} + +// AnyOther struct for AnyOther +type AnyOther struct { + Kind interface{} `json:"kind,omitempty"` +} + +func (o *AnyOther) validateStringEnumValues(data []byte) error { + var fields struct { + Kind json.RawMessage `json:"kind,omitempty"` + } + if err := json.Unmarshal(data, &fields); err != nil { + return err + } + if raw := fields.Kind; raw != nil { + var value interface{} + if err := json.Unmarshal(raw, &value); err != nil { + return err + } + if value == "known" { + return fmt.Errorf("excluded value %v for property %s", value, "kind") + } + } + return nil +} + +type _AnyOther AnyOther + +func (o *AnyOther) UnmarshalJSON(data []byte) error { + if err := o.validateStringEnumValues(data); err != nil { + return err + } + value := _AnyOther(*o) + if err := json.Unmarshal(data, &value); err != nil { + return err + } + *o = AnyOther(value) + return nil +} + +// NewAnyOther instantiates a new AnyOther 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 +func NewAnyOther() *AnyOther { + this := AnyOther{} + return &this +} + +// NewAnyOtherWithDefaults instantiates a new AnyOther 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 +func NewAnyOtherWithDefaults() *AnyOther { + this := AnyOther{} + return &this +} + +// GetKind returns the Kind field value if set, zero value otherwise (both if not set or set to explicit null). +func (o *AnyOther) GetKind() interface{} { + if o == nil { + var ret interface{} + return ret + } + return o.Kind +} + +// GetKindOk returns a tuple with the Kind field value if set, nil otherwise +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *AnyOther) GetKindOk() (*interface{}, bool) { + if o == nil || IsNil(o.Kind) { + return nil, false + } + return &o.Kind, true +} + +// HasKind returns a boolean if a field has been set. +func (o *AnyOther) HasKind() bool { + if o != nil && !IsNil(o.Kind) { + return true + } + + return false +} + +// SetKind gets a reference to the given interface{} and assigns it to the Kind field. +func (o *AnyOther) SetKind(v interface{}) { + o.Kind = v +} + +func (o AnyOther) MarshalJSON() ([]byte, error) { + toSerialize,err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o AnyOther) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if o.Kind != nil { + toSerialize["kind"] = o.Kind + } + return toSerialize, nil +} + +type NullableAnyOther struct { + value *AnyOther + isSet bool +} + +func (v NullableAnyOther) Get() *AnyOther { + return v.value +} + +func (v *NullableAnyOther) Set(val *AnyOther) { + v.value = val + v.isSet = true +} + +func (v NullableAnyOther) IsSet() bool { + return v.isSet +} + +func (v *NullableAnyOther) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableAnyOther(val *AnyOther) *NullableAnyOther { + return &NullableAnyOther{value: val, isSet: true} +} + +func (v NullableAnyOther) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableAnyOther) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + + diff --git a/samples/client/others/go/oneof-not-enum/model_enum_null_union.go b/samples/client/others/go/oneof-not-enum/model_enum_null_union.go new file mode 100644 index 000000000000..22c446c2f6f8 --- /dev/null +++ b/samples/client/others/go/oneof-not-enum/model_enum_null_union.go @@ -0,0 +1,175 @@ +/* +oneOf not enum test + +No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + +API version: 1.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "encoding/json" + "fmt" + "gopkg.in/validator.v2" +) + +// EnumNullUnion - struct for EnumNullUnion +type EnumNullUnion struct { + NullableEnum *NullableEnum + NullableExcludedEnum *NullableExcludedEnum +} + +// NullableEnumAsEnumNullUnion is a convenience function that returns NullableEnum wrapped in EnumNullUnion +func NullableEnumAsEnumNullUnion(v *NullableEnum) EnumNullUnion { + return EnumNullUnion{ + NullableEnum: v, + } +} + +// NullableExcludedEnumAsEnumNullUnion is a convenience function that returns NullableExcludedEnum wrapped in EnumNullUnion +func NullableExcludedEnumAsEnumNullUnion(v *NullableExcludedEnum) EnumNullUnion { + return EnumNullUnion{ + NullableExcludedEnum: v, + } +} + + +// Unmarshal JSON data into one of the pointers in the struct +func (dst *EnumNullUnion) UnmarshalJSON(data []byte) error { + var err error + match := 0 + // try to unmarshal data into NullableEnum + err = newStrictDecoder(data).Decode(&dst.NullableEnum) + if err == nil { + jsonNullableEnum, _ := json.Marshal(dst.NullableEnum) + if string(jsonNullableEnum) == "{}" { // empty struct + dst.NullableEnum = nil + } else { + if err = validator.Validate(dst.NullableEnum); err != nil { + dst.NullableEnum = nil + } else { + match++ + } + } + } else { + dst.NullableEnum = nil + } + + // try to unmarshal data into NullableExcludedEnum + err = newStrictDecoder(data).Decode(&dst.NullableExcludedEnum) + if err == nil { + jsonNullableExcludedEnum, _ := json.Marshal(dst.NullableExcludedEnum) + if string(jsonNullableExcludedEnum) == "{}" { // empty struct + dst.NullableExcludedEnum = nil + } else { + if err = validator.Validate(dst.NullableExcludedEnum); err != nil { + dst.NullableExcludedEnum = nil + } else { + match++ + } + } + } else { + dst.NullableExcludedEnum = nil + } + + if match > 1 { // more than 1 match + // reset to nil + dst.NullableEnum = nil + dst.NullableExcludedEnum = nil + + return fmt.Errorf("data matches more than one schema in oneOf(EnumNullUnion)") + } else if match == 1 { + return nil // exactly one match + } else { // no match + if err != nil { + return fmt.Errorf("data failed to match schemas in oneOf(EnumNullUnion): %v", err) + } + + return fmt.Errorf("data failed to match schemas in oneOf(EnumNullUnion)") + } +} + +// Marshal data from the first non-nil pointers in the struct to JSON +func (src EnumNullUnion) MarshalJSON() ([]byte, error) { + if src.NullableEnum != nil { + return json.Marshal(&src.NullableEnum) + } + + if src.NullableExcludedEnum != nil { + return json.Marshal(&src.NullableExcludedEnum) + } + + return nil, nil // no data in oneOf schemas +} + +// Get the actual instance +func (obj *EnumNullUnion) GetActualInstance() (interface{}) { + if obj == nil { + return nil + } + if obj.NullableEnum != nil { + return obj.NullableEnum + } + + if obj.NullableExcludedEnum != nil { + return obj.NullableExcludedEnum + } + + // all schemas are nil + return nil +} + +// Get the actual instance value +func (obj EnumNullUnion) GetActualInstanceValue() (interface{}) { + if obj.NullableEnum != nil { + return *obj.NullableEnum + } + + if obj.NullableExcludedEnum != nil { + return *obj.NullableExcludedEnum + } + + // all schemas are nil + return nil +} + +type NullableEnumNullUnion struct { + value *EnumNullUnion + isSet bool +} + +func (v NullableEnumNullUnion) Get() *EnumNullUnion { + return v.value +} + +func (v *NullableEnumNullUnion) Set(val *EnumNullUnion) { + v.value = val + v.isSet = true +} + +func (v NullableEnumNullUnion) IsSet() bool { + return v.isSet +} + +func (v *NullableEnumNullUnion) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableEnumNullUnion(val *EnumNullUnion) *NullableEnumNullUnion { + return &NullableEnumNullUnion{value: val, isSet: true} +} + +func (v NullableEnumNullUnion) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableEnumNullUnion) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + + diff --git a/samples/client/others/go/oneof-not-enum/model_excluded_kinds.go b/samples/client/others/go/oneof-not-enum/model_excluded_kinds.go new file mode 100644 index 000000000000..d23fb0260266 --- /dev/null +++ b/samples/client/others/go/oneof-not-enum/model_excluded_kinds.go @@ -0,0 +1,111 @@ +/* +oneOf not enum test + +No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + +API version: 1.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "encoding/json" + "fmt" +) + +// ExcludedKinds the model 'ExcludedKinds' +type ExcludedKinds string + +// List of ExcludedKinds +const ( + KNOWN ExcludedKinds = "known" + AB ExcludedKinds = "a\"b" +) + +// All allowed values of ExcludedKinds enum +var AllowedExcludedKindsEnumValues = []ExcludedKinds{ + "known", + "a\"b", +} + +func (v *ExcludedKinds) UnmarshalJSON(src []byte) error { + var value string + err := json.Unmarshal(src, &value) + if err != nil { + return err + } + enumTypeValue := ExcludedKinds(value) + for _, existing := range AllowedExcludedKindsEnumValues { + if existing == enumTypeValue { + *v = enumTypeValue + return nil + } + } + + return fmt.Errorf("%+v is not a valid ExcludedKinds", value) +} + +// NewExcludedKindsFromValue returns a pointer to a valid ExcludedKinds +// for the value passed as argument, or an error if the value passed is not allowed by the enum +func NewExcludedKindsFromValue(v string) (*ExcludedKinds, error) { + ev := ExcludedKinds(v) + if ev.IsValid() { + return &ev, nil + } else { + return nil, fmt.Errorf("invalid value '%v' for ExcludedKinds: valid values are %v", v, AllowedExcludedKindsEnumValues) + } +} + +// IsValid return true if the value is valid for the enum, false otherwise +func (v ExcludedKinds) IsValid() bool { + for _, existing := range AllowedExcludedKindsEnumValues { + if existing == v { + return true + } + } + return false +} + +// Ptr returns reference to ExcludedKinds value +func (v ExcludedKinds) Ptr() *ExcludedKinds { + return &v +} + +type NullableExcludedKinds struct { + value *ExcludedKinds + isSet bool +} + +func (v NullableExcludedKinds) Get() *ExcludedKinds { + return v.value +} + +func (v *NullableExcludedKinds) Set(val *ExcludedKinds) { + v.value = val + v.isSet = true +} + +func (v NullableExcludedKinds) IsSet() bool { + return v.isSet +} + +func (v *NullableExcludedKinds) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableExcludedKinds(val *ExcludedKinds) *NullableExcludedKinds { + return &NullableExcludedKinds{value: val, isSet: true} +} + +func (v NullableExcludedKinds) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableExcludedKinds) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + diff --git a/samples/client/others/go/oneof-not-enum/model_known.go b/samples/client/others/go/oneof-not-enum/model_known.go new file mode 100644 index 000000000000..da2608b581cc --- /dev/null +++ b/samples/client/others/go/oneof-not-enum/model_known.go @@ -0,0 +1,195 @@ +/* +oneOf not enum test + +No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + +API version: 1.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "encoding/json" + "bytes" + "fmt" + "strings" +) + +// checks if the Known type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &Known{} + +// Known struct for Known +type Known struct { + Kind string `json:"kind"` +} + +type _Known Known + +func (o *Known) validateStringEnumValues(data []byte) error { + var fields struct { + Kind json.RawMessage `json:"kind"` + } + if err := json.Unmarshal(data, &fields); err != nil { + return err + } + if raw := fields.Kind; raw != nil { + if string(raw) == "null" { + return fmt.Errorf("invalid null value for property %s", "kind") + } + var value string + if err := json.Unmarshal(raw, &value); err != nil { + return err + } + if value != "known" { + return fmt.Errorf("invalid value %q for property %s", value, "kind") + } + } + return nil +} + +// NewKnown instantiates a new Known 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 +func NewKnown(kind string) *Known { + this := Known{} + this.Kind = kind + return &this +} + +// NewKnownWithDefaults instantiates a new Known 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 +func NewKnownWithDefaults() *Known { + this := Known{} + return &this +} + +// GetKind returns the Kind field value +func (o *Known) GetKind() string { + if o == nil { + var ret string + return ret + } + + return o.Kind +} + +// GetKindOk returns a tuple with the Kind field value +// and a boolean to check if the value has been set. +func (o *Known) GetKindOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Kind, true +} + +// SetKind sets field value +func (o *Known) SetKind(v string) { + o.Kind = v +} + +func (o Known) MarshalJSON() ([]byte, error) { + toSerialize,err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o Known) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + toSerialize["kind"] = o.Kind + return toSerialize, nil +} + +func (o *Known) UnmarshalJSON(data []byte) (err error) { + if err := o.validateStringEnumValues(data); err != nil { + return err + } + // This validates that all required properties are included in the JSON object + // by unmarshalling the object into a generic map with string keys and checking + // that every required field exists as a key in the generic map. + requiredProperties := []string{ + "kind", + } + + allProperties := make(map[string]interface{}) + + err = json.Unmarshal(data, &allProperties) + + if err != nil { + return err; + } + + lookupRequiredProperty := func(requiredProperty string) (interface{}, string, bool) { + if value, exists := allProperties[requiredProperty]; exists { + return value, requiredProperty, true + } + for name, value := range allProperties { + if strings.EqualFold(name, requiredProperty) { + return value, name, true + } + } + return nil, "", false + } + for _, requiredProperty := range(requiredProperties) { + if _, _, exists := lookupRequiredProperty(requiredProperty); !exists { + return fmt.Errorf("no value given for required property %v", requiredProperty) + } + } + + varKnown := _Known{} + + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.DisallowUnknownFields() + err = decoder.Decode(&varKnown) + + if err != nil { + return err + } + + *o = Known(varKnown) + + return err +} + +type NullableKnown struct { + value *Known + isSet bool +} + +func (v NullableKnown) Get() *Known { + return v.value +} + +func (v *NullableKnown) Set(val *Known) { + v.value = val + v.isSet = true +} + +func (v NullableKnown) IsSet() bool { + return v.isSet +} + +func (v *NullableKnown) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableKnown(val *Known) *NullableKnown { + return &NullableKnown{value: val, isSet: true} +} + +func (v NullableKnown) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableKnown) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + + diff --git a/samples/client/others/go/oneof-not-enum/model_nullable_enum.go b/samples/client/others/go/oneof-not-enum/model_nullable_enum.go new file mode 100644 index 000000000000..2366e44d2776 --- /dev/null +++ b/samples/client/others/go/oneof-not-enum/model_nullable_enum.go @@ -0,0 +1,170 @@ +/* +oneOf not enum test + +No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + +API version: 1.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "encoding/json" + "fmt" +) + +// checks if the NullableEnum type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &NullableEnum{} + +// NullableEnum struct for NullableEnum +type NullableEnum struct { + Kind NullableString `json:"kind,omitempty"` +} + +func (o *NullableEnum) validateStringEnumValues(data []byte) error { + var fields struct { + Kind json.RawMessage `json:"kind,omitempty"` + } + if err := json.Unmarshal(data, &fields); err != nil { + return err + } + if raw := fields.Kind; raw != nil { + var value string + if err := json.Unmarshal(raw, &value); err != nil { + return err + } + if string(raw) != "null" && (value != "known") { + return fmt.Errorf("invalid value %q for property %s", value, "kind") + } + } + return nil +} + +type _NullableEnum NullableEnum + +func (o *NullableEnum) UnmarshalJSON(data []byte) error { + if err := o.validateStringEnumValues(data); err != nil { + return err + } + value := _NullableEnum(*o) + if err := json.Unmarshal(data, &value); err != nil { + return err + } + *o = NullableEnum(value) + return nil +} + +// NewNullableEnum instantiates a new NullableEnum 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 +func NewNullableEnum() *NullableEnum { + this := NullableEnum{} + return &this +} + +// NewNullableEnumWithDefaults instantiates a new NullableEnum 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 +func NewNullableEnumWithDefaults() *NullableEnum { + this := NullableEnum{} + return &this +} + +// GetKind returns the Kind field value if set, zero value otherwise (both if not set or set to explicit null). +func (o *NullableEnum) GetKind() string { + if o == nil || IsNil(o.Kind.Get()) { + var ret string + return ret + } + return *o.Kind.Get() +} + +// GetKindOk returns a tuple with the Kind field value if set, nil otherwise +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *NullableEnum) GetKindOk() (*string, bool) { + if o == nil { + return nil, false + } + return o.Kind.Get(), o.Kind.IsSet() +} + +// HasKind returns a boolean if a field has been set. +func (o *NullableEnum) HasKind() bool { + if o != nil && o.Kind.IsSet() { + return true + } + + return false +} + +// SetKind gets a reference to the given NullableString and assigns it to the Kind field. +func (o *NullableEnum) SetKind(v string) { + o.Kind.Set(&v) +} +// SetKindNil sets the value for Kind to be an explicit nil +func (o *NullableEnum) SetKindNil() { + o.Kind.Set(nil) +} + +// UnsetKind ensures that no value is present for Kind, not even an explicit nil +func (o *NullableEnum) UnsetKind() { + o.Kind.Unset() +} + +func (o NullableEnum) MarshalJSON() ([]byte, error) { + toSerialize,err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o NullableEnum) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if o.Kind.IsSet() { + toSerialize["kind"] = o.Kind.Get() + } + return toSerialize, nil +} + +type NullableNullableEnum struct { + value *NullableEnum + isSet bool +} + +func (v NullableNullableEnum) Get() *NullableEnum { + return v.value +} + +func (v *NullableNullableEnum) Set(val *NullableEnum) { + v.value = val + v.isSet = true +} + +func (v NullableNullableEnum) IsSet() bool { + return v.isSet +} + +func (v *NullableNullableEnum) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableNullableEnum(val *NullableEnum) *NullableNullableEnum { + return &NullableNullableEnum{value: val, isSet: true} +} + +func (v NullableNullableEnum) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableNullableEnum) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + + diff --git a/samples/client/others/go/oneof-not-enum/model_nullable_enum_without_null_value.go b/samples/client/others/go/oneof-not-enum/model_nullable_enum_without_null_value.go new file mode 100644 index 000000000000..fdc628e67dec --- /dev/null +++ b/samples/client/others/go/oneof-not-enum/model_nullable_enum_without_null_value.go @@ -0,0 +1,136 @@ +/* +oneOf not enum test + +No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + +API version: 1.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "encoding/json" +) + +// checks if the NullableEnumWithoutNullValue type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &NullableEnumWithoutNullValue{} + +// NullableEnumWithoutNullValue struct for NullableEnumWithoutNullValue +type NullableEnumWithoutNullValue struct { + Kind NullableString `json:"kind,omitempty"` +} + +// NewNullableEnumWithoutNullValue instantiates a new NullableEnumWithoutNullValue 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 +func NewNullableEnumWithoutNullValue() *NullableEnumWithoutNullValue { + this := NullableEnumWithoutNullValue{} + return &this +} + +// NewNullableEnumWithoutNullValueWithDefaults instantiates a new NullableEnumWithoutNullValue 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 +func NewNullableEnumWithoutNullValueWithDefaults() *NullableEnumWithoutNullValue { + this := NullableEnumWithoutNullValue{} + return &this +} + +// GetKind returns the Kind field value if set, zero value otherwise (both if not set or set to explicit null). +func (o *NullableEnumWithoutNullValue) GetKind() string { + if o == nil || IsNil(o.Kind.Get()) { + var ret string + return ret + } + return *o.Kind.Get() +} + +// GetKindOk returns a tuple with the Kind field value if set, nil otherwise +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *NullableEnumWithoutNullValue) GetKindOk() (*string, bool) { + if o == nil { + return nil, false + } + return o.Kind.Get(), o.Kind.IsSet() +} + +// HasKind returns a boolean if a field has been set. +func (o *NullableEnumWithoutNullValue) HasKind() bool { + if o != nil && o.Kind.IsSet() { + return true + } + + return false +} + +// SetKind gets a reference to the given NullableString and assigns it to the Kind field. +func (o *NullableEnumWithoutNullValue) SetKind(v string) { + o.Kind.Set(&v) +} +// SetKindNil sets the value for Kind to be an explicit nil +func (o *NullableEnumWithoutNullValue) SetKindNil() { + o.Kind.Set(nil) +} + +// UnsetKind ensures that no value is present for Kind, not even an explicit nil +func (o *NullableEnumWithoutNullValue) UnsetKind() { + o.Kind.Unset() +} + +func (o NullableEnumWithoutNullValue) MarshalJSON() ([]byte, error) { + toSerialize,err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o NullableEnumWithoutNullValue) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if o.Kind.IsSet() { + toSerialize["kind"] = o.Kind.Get() + } + return toSerialize, nil +} + +type NullableNullableEnumWithoutNullValue struct { + value *NullableEnumWithoutNullValue + isSet bool +} + +func (v NullableNullableEnumWithoutNullValue) Get() *NullableEnumWithoutNullValue { + return v.value +} + +func (v *NullableNullableEnumWithoutNullValue) Set(val *NullableEnumWithoutNullValue) { + v.value = val + v.isSet = true +} + +func (v NullableNullableEnumWithoutNullValue) IsSet() bool { + return v.isSet +} + +func (v *NullableNullableEnumWithoutNullValue) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableNullableEnumWithoutNullValue(val *NullableEnumWithoutNullValue) *NullableNullableEnumWithoutNullValue { + return &NullableNullableEnumWithoutNullValue{value: val, isSet: true} +} + +func (v NullableNullableEnumWithoutNullValue) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableNullableEnumWithoutNullValue) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + + diff --git a/samples/client/others/go/oneof-not-enum/model_nullable_excluded_enum.go b/samples/client/others/go/oneof-not-enum/model_nullable_excluded_enum.go new file mode 100644 index 000000000000..71bfd1a755a1 --- /dev/null +++ b/samples/client/others/go/oneof-not-enum/model_nullable_excluded_enum.go @@ -0,0 +1,170 @@ +/* +oneOf not enum test + +No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + +API version: 1.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "encoding/json" + "fmt" +) + +// checks if the NullableExcludedEnum type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &NullableExcludedEnum{} + +// NullableExcludedEnum struct for NullableExcludedEnum +type NullableExcludedEnum struct { + Kind NullableString `json:"kind,omitempty"` +} + +func (o *NullableExcludedEnum) validateStringEnumValues(data []byte) error { + var fields struct { + Kind json.RawMessage `json:"kind,omitempty"` + } + if err := json.Unmarshal(data, &fields); err != nil { + return err + } + if raw := fields.Kind; raw != nil { + var value interface{} + if err := json.Unmarshal(raw, &value); err != nil { + return err + } + if value == "known" || value == nil { + return fmt.Errorf("excluded value %v for property %s", value, "kind") + } + } + return nil +} + +type _NullableExcludedEnum NullableExcludedEnum + +func (o *NullableExcludedEnum) UnmarshalJSON(data []byte) error { + if err := o.validateStringEnumValues(data); err != nil { + return err + } + value := _NullableExcludedEnum(*o) + if err := json.Unmarshal(data, &value); err != nil { + return err + } + *o = NullableExcludedEnum(value) + return nil +} + +// NewNullableExcludedEnum instantiates a new NullableExcludedEnum 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 +func NewNullableExcludedEnum() *NullableExcludedEnum { + this := NullableExcludedEnum{} + return &this +} + +// NewNullableExcludedEnumWithDefaults instantiates a new NullableExcludedEnum 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 +func NewNullableExcludedEnumWithDefaults() *NullableExcludedEnum { + this := NullableExcludedEnum{} + return &this +} + +// GetKind returns the Kind field value if set, zero value otherwise (both if not set or set to explicit null). +func (o *NullableExcludedEnum) GetKind() string { + if o == nil || IsNil(o.Kind.Get()) { + var ret string + return ret + } + return *o.Kind.Get() +} + +// GetKindOk returns a tuple with the Kind field value if set, nil otherwise +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *NullableExcludedEnum) GetKindOk() (*string, bool) { + if o == nil { + return nil, false + } + return o.Kind.Get(), o.Kind.IsSet() +} + +// HasKind returns a boolean if a field has been set. +func (o *NullableExcludedEnum) HasKind() bool { + if o != nil && o.Kind.IsSet() { + return true + } + + return false +} + +// SetKind gets a reference to the given NullableString and assigns it to the Kind field. +func (o *NullableExcludedEnum) SetKind(v string) { + o.Kind.Set(&v) +} +// SetKindNil sets the value for Kind to be an explicit nil +func (o *NullableExcludedEnum) SetKindNil() { + o.Kind.Set(nil) +} + +// UnsetKind ensures that no value is present for Kind, not even an explicit nil +func (o *NullableExcludedEnum) UnsetKind() { + o.Kind.Unset() +} + +func (o NullableExcludedEnum) MarshalJSON() ([]byte, error) { + toSerialize,err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o NullableExcludedEnum) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if o.Kind.IsSet() { + toSerialize["kind"] = o.Kind.Get() + } + return toSerialize, nil +} + +type NullableNullableExcludedEnum struct { + value *NullableExcludedEnum + isSet bool +} + +func (v NullableNullableExcludedEnum) Get() *NullableExcludedEnum { + return v.value +} + +func (v *NullableNullableExcludedEnum) Set(val *NullableExcludedEnum) { + v.value = val + v.isSet = true +} + +func (v NullableNullableExcludedEnum) IsSet() bool { + return v.isSet +} + +func (v *NullableNullableExcludedEnum) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableNullableExcludedEnum(val *NullableExcludedEnum) *NullableNullableExcludedEnum { + return &NullableNullableExcludedEnum{value: val, isSet: true} +} + +func (v NullableNullableExcludedEnum) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableNullableExcludedEnum) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + + diff --git a/samples/client/others/go/oneof-not-enum/model_optional_enum_child.go b/samples/client/others/go/oneof-not-enum/model_optional_enum_child.go new file mode 100644 index 000000000000..d4b882c7ee3c --- /dev/null +++ b/samples/client/others/go/oneof-not-enum/model_optional_enum_child.go @@ -0,0 +1,176 @@ +/* +oneOf not enum test + +No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + +API version: 1.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "encoding/json" + "fmt" +) + +// checks if the OptionalEnumChild type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &OptionalEnumChild{} + +// OptionalEnumChild struct for OptionalEnumChild +type OptionalEnumChild struct { + OptionalEnumParent + Label *string `json:"label,omitempty"` +} + +func (o *OptionalEnumChild) validateStringEnumValues(data []byte) error { + var fields struct { + Kind json.RawMessage `json:"kind"` + } + if err := json.Unmarshal(data, &fields); err != nil { + return err + } + if raw := fields.Kind; raw != nil { + if string(raw) == "null" { + return fmt.Errorf("invalid null value for property %s", "kind") + } + var value string + if err := json.Unmarshal(raw, &value); err != nil { + return err + } + if value != "allowed" { + return fmt.Errorf("invalid value %q for property %s", value, "kind") + } + } + return nil +} + +type _OptionalEnumChild OptionalEnumChild + +func (o *OptionalEnumChild) UnmarshalJSON(data []byte) error { + if err := o.validateStringEnumValues(data); err != nil { + return err + } + var decoded struct { + Kind *string `json:"kind,omitempty"` + + Dash *string `json:"dash,omitempty"` + + Label *string `json:"label,omitempty"` + } + decoded.Kind = o.Kind + decoded.Dash = o.Dash + decoded.Label = o.Label + if err := json.Unmarshal(data, &decoded); err != nil { + return err + } + *o = OptionalEnumChild{} + o.Kind = decoded.Kind + o.Dash = decoded.Dash + o.Label = decoded.Label + return nil +} + +// NewOptionalEnumChild instantiates a new OptionalEnumChild 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 +func NewOptionalEnumChild() *OptionalEnumChild { + this := OptionalEnumChild{} + return &this +} + +// NewOptionalEnumChildWithDefaults instantiates a new OptionalEnumChild 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 +func NewOptionalEnumChildWithDefaults() *OptionalEnumChild { + this := OptionalEnumChild{} + return &this +} + +// GetLabel returns the Label field value if set, zero value otherwise. +func (o *OptionalEnumChild) GetLabel() string { + if o == nil || IsNil(o.Label) { + var ret string + return ret + } + return *o.Label +} + +// GetLabelOk returns a tuple with the Label field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *OptionalEnumChild) GetLabelOk() (*string, bool) { + if o == nil || IsNil(o.Label) { + return nil, false + } + return o.Label, true +} + +// HasLabel returns a boolean if a field has been set. +func (o *OptionalEnumChild) HasLabel() bool { + if o != nil && !IsNil(o.Label) { + return true + } + + return false +} + +// SetLabel gets a reference to the given string and assigns it to the Label field. +func (o *OptionalEnumChild) SetLabel(v string) { + o.Label = &v +} + +func (o OptionalEnumChild) MarshalJSON() ([]byte, error) { + toSerialize,err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o OptionalEnumChild) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Label) { + toSerialize["label"] = o.Label + } + return toSerialize, nil +} + +type NullableOptionalEnumChild struct { + value *OptionalEnumChild + isSet bool +} + +func (v NullableOptionalEnumChild) Get() *OptionalEnumChild { + return v.value +} + +func (v *NullableOptionalEnumChild) Set(val *OptionalEnumChild) { + v.value = val + v.isSet = true +} + +func (v NullableOptionalEnumChild) IsSet() bool { + return v.isSet +} + +func (v *NullableOptionalEnumChild) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableOptionalEnumChild(val *OptionalEnumChild) *NullableOptionalEnumChild { + return &NullableOptionalEnumChild{value: val, isSet: true} +} + +func (v NullableOptionalEnumChild) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableOptionalEnumChild) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + + diff --git a/samples/client/others/go/oneof-not-enum/model_optional_enum_child_fields.go b/samples/client/others/go/oneof-not-enum/model_optional_enum_child_fields.go new file mode 100644 index 000000000000..b2291b14781e --- /dev/null +++ b/samples/client/others/go/oneof-not-enum/model_optional_enum_child_fields.go @@ -0,0 +1,126 @@ +/* +oneOf not enum test + +No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + +API version: 1.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "encoding/json" +) + +// checks if the OptionalEnumChildFields type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &OptionalEnumChildFields{} + +// OptionalEnumChildFields struct for OptionalEnumChildFields +type OptionalEnumChildFields struct { + Label *string `json:"label,omitempty"` +} + +// NewOptionalEnumChildFields instantiates a new OptionalEnumChildFields 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 +func NewOptionalEnumChildFields() *OptionalEnumChildFields { + this := OptionalEnumChildFields{} + return &this +} + +// NewOptionalEnumChildFieldsWithDefaults instantiates a new OptionalEnumChildFields 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 +func NewOptionalEnumChildFieldsWithDefaults() *OptionalEnumChildFields { + this := OptionalEnumChildFields{} + return &this +} + +// GetLabel returns the Label field value if set, zero value otherwise. +func (o *OptionalEnumChildFields) GetLabel() string { + if o == nil || IsNil(o.Label) { + var ret string + return ret + } + return *o.Label +} + +// GetLabelOk returns a tuple with the Label field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *OptionalEnumChildFields) GetLabelOk() (*string, bool) { + if o == nil || IsNil(o.Label) { + return nil, false + } + return o.Label, true +} + +// HasLabel returns a boolean if a field has been set. +func (o *OptionalEnumChildFields) HasLabel() bool { + if o != nil && !IsNil(o.Label) { + return true + } + + return false +} + +// SetLabel gets a reference to the given string and assigns it to the Label field. +func (o *OptionalEnumChildFields) SetLabel(v string) { + o.Label = &v +} + +func (o OptionalEnumChildFields) MarshalJSON() ([]byte, error) { + toSerialize,err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o OptionalEnumChildFields) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Label) { + toSerialize["label"] = o.Label + } + return toSerialize, nil +} + +type NullableOptionalEnumChildFields struct { + value *OptionalEnumChildFields + isSet bool +} + +func (v NullableOptionalEnumChildFields) Get() *OptionalEnumChildFields { + return v.value +} + +func (v *NullableOptionalEnumChildFields) Set(val *OptionalEnumChildFields) { + v.value = val + v.isSet = true +} + +func (v NullableOptionalEnumChildFields) IsSet() bool { + return v.isSet +} + +func (v *NullableOptionalEnumChildFields) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableOptionalEnumChildFields(val *OptionalEnumChildFields) *NullableOptionalEnumChildFields { + return &NullableOptionalEnumChildFields{value: val, isSet: true} +} + +func (v NullableOptionalEnumChildFields) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableOptionalEnumChildFields) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + + diff --git a/samples/client/others/go/oneof-not-enum/model_optional_enum_other.go b/samples/client/others/go/oneof-not-enum/model_optional_enum_other.go new file mode 100644 index 000000000000..3e231b14fffb --- /dev/null +++ b/samples/client/others/go/oneof-not-enum/model_optional_enum_other.go @@ -0,0 +1,160 @@ +/* +oneOf not enum test + +No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + +API version: 1.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "encoding/json" + "fmt" +) + +// checks if the OptionalEnumOther type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &OptionalEnumOther{} + +// OptionalEnumOther struct for OptionalEnumOther +type OptionalEnumOther struct { + Kind *string `json:"kind,omitempty"` +} + +func (o *OptionalEnumOther) validateStringEnumValues(data []byte) error { + var fields struct { + Kind json.RawMessage `json:"kind,omitempty"` + } + if err := json.Unmarshal(data, &fields); err != nil { + return err + } + if raw := fields.Kind; raw != nil { + var value interface{} + if err := json.Unmarshal(raw, &value); err != nil { + return err + } + if value == "allowed" { + return fmt.Errorf("excluded value %v for property %s", value, "kind") + } + } + return nil +} + +type _OptionalEnumOther OptionalEnumOther + +func (o *OptionalEnumOther) UnmarshalJSON(data []byte) error { + if err := o.validateStringEnumValues(data); err != nil { + return err + } + value := _OptionalEnumOther(*o) + if err := json.Unmarshal(data, &value); err != nil { + return err + } + *o = OptionalEnumOther(value) + return nil +} + +// NewOptionalEnumOther instantiates a new OptionalEnumOther 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 +func NewOptionalEnumOther() *OptionalEnumOther { + this := OptionalEnumOther{} + return &this +} + +// NewOptionalEnumOtherWithDefaults instantiates a new OptionalEnumOther 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 +func NewOptionalEnumOtherWithDefaults() *OptionalEnumOther { + this := OptionalEnumOther{} + return &this +} + +// GetKind returns the Kind field value if set, zero value otherwise. +func (o *OptionalEnumOther) GetKind() string { + if o == nil || IsNil(o.Kind) { + var ret string + return ret + } + return *o.Kind +} + +// GetKindOk returns a tuple with the Kind field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *OptionalEnumOther) GetKindOk() (*string, bool) { + if o == nil || IsNil(o.Kind) { + return nil, false + } + return o.Kind, true +} + +// HasKind returns a boolean if a field has been set. +func (o *OptionalEnumOther) HasKind() bool { + if o != nil && !IsNil(o.Kind) { + return true + } + + return false +} + +// SetKind gets a reference to the given string and assigns it to the Kind field. +func (o *OptionalEnumOther) SetKind(v string) { + o.Kind = &v +} + +func (o OptionalEnumOther) MarshalJSON() ([]byte, error) { + toSerialize,err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o OptionalEnumOther) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Kind) { + toSerialize["kind"] = o.Kind + } + return toSerialize, nil +} + +type NullableOptionalEnumOther struct { + value *OptionalEnumOther + isSet bool +} + +func (v NullableOptionalEnumOther) Get() *OptionalEnumOther { + return v.value +} + +func (v *NullableOptionalEnumOther) Set(val *OptionalEnumOther) { + v.value = val + v.isSet = true +} + +func (v NullableOptionalEnumOther) IsSet() bool { + return v.isSet +} + +func (v *NullableOptionalEnumOther) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableOptionalEnumOther(val *OptionalEnumOther) *NullableOptionalEnumOther { + return &NullableOptionalEnumOther{value: val, isSet: true} +} + +func (v NullableOptionalEnumOther) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableOptionalEnumOther) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + + diff --git a/samples/client/others/go/oneof-not-enum/model_optional_enum_parent.go b/samples/client/others/go/oneof-not-enum/model_optional_enum_parent.go new file mode 100644 index 000000000000..8631e01816a8 --- /dev/null +++ b/samples/client/others/go/oneof-not-enum/model_optional_enum_parent.go @@ -0,0 +1,162 @@ +/* +oneOf not enum test + +No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + +API version: 1.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "encoding/json" +) + +// checks if the OptionalEnumParent type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &OptionalEnumParent{} + +// OptionalEnumParent struct for OptionalEnumParent +type OptionalEnumParent struct { + Kind *string `json:"kind,omitempty"` + Dash *string `json:"dash,omitempty"` +} + +// NewOptionalEnumParent instantiates a new OptionalEnumParent 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 +func NewOptionalEnumParent() *OptionalEnumParent { + this := OptionalEnumParent{} + return &this +} + +// NewOptionalEnumParentWithDefaults instantiates a new OptionalEnumParent 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 +func NewOptionalEnumParentWithDefaults() *OptionalEnumParent { + this := OptionalEnumParent{} + return &this +} + +// GetKind returns the Kind field value if set, zero value otherwise. +func (o *OptionalEnumParent) GetKind() string { + if o == nil || IsNil(o.Kind) { + var ret string + return ret + } + return *o.Kind +} + +// GetKindOk returns a tuple with the Kind field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *OptionalEnumParent) GetKindOk() (*string, bool) { + if o == nil || IsNil(o.Kind) { + return nil, false + } + return o.Kind, true +} + +// HasKind returns a boolean if a field has been set. +func (o *OptionalEnumParent) HasKind() bool { + if o != nil && !IsNil(o.Kind) { + return true + } + + return false +} + +// SetKind gets a reference to the given string and assigns it to the Kind field. +func (o *OptionalEnumParent) SetKind(v string) { + o.Kind = &v +} + +// GetDash returns the Dash field value if set, zero value otherwise. +func (o *OptionalEnumParent) GetDash() string { + if o == nil || IsNil(o.Dash) { + var ret string + return ret + } + return *o.Dash +} + +// GetDashOk returns a tuple with the Dash field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *OptionalEnumParent) GetDashOk() (*string, bool) { + if o == nil || IsNil(o.Dash) { + return nil, false + } + return o.Dash, true +} + +// HasDash returns a boolean if a field has been set. +func (o *OptionalEnumParent) HasDash() bool { + if o != nil && !IsNil(o.Dash) { + return true + } + + return false +} + +// SetDash gets a reference to the given string and assigns it to the Dash field. +func (o *OptionalEnumParent) SetDash(v string) { + o.Dash = &v +} + +func (o OptionalEnumParent) MarshalJSON() ([]byte, error) { + toSerialize,err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o OptionalEnumParent) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Kind) { + toSerialize["kind"] = o.Kind + } + if !IsNil(o.Dash) { + toSerialize["dash"] = o.Dash + } + return toSerialize, nil +} + +type NullableOptionalEnumParent struct { + value *OptionalEnumParent + isSet bool +} + +func (v NullableOptionalEnumParent) Get() *OptionalEnumParent { + return v.value +} + +func (v *NullableOptionalEnumParent) Set(val *OptionalEnumParent) { + v.value = val + v.isSet = true +} + +func (v NullableOptionalEnumParent) IsSet() bool { + return v.isSet +} + +func (v *NullableOptionalEnumParent) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableOptionalEnumParent(val *OptionalEnumParent) *NullableOptionalEnumParent { + return &NullableOptionalEnumParent{value: val, isSet: true} +} + +func (v NullableOptionalEnumParent) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableOptionalEnumParent) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + + diff --git a/samples/client/others/go/oneof-not-enum/model_optional_enum_union.go b/samples/client/others/go/oneof-not-enum/model_optional_enum_union.go new file mode 100644 index 000000000000..980ddb690f4b --- /dev/null +++ b/samples/client/others/go/oneof-not-enum/model_optional_enum_union.go @@ -0,0 +1,175 @@ +/* +oneOf not enum test + +No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + +API version: 1.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "encoding/json" + "fmt" + "gopkg.in/validator.v2" +) + +// OptionalEnumUnion - struct for OptionalEnumUnion +type OptionalEnumUnion struct { + OptionalEnumChild *OptionalEnumChild + OptionalEnumOther *OptionalEnumOther +} + +// OptionalEnumChildAsOptionalEnumUnion is a convenience function that returns OptionalEnumChild wrapped in OptionalEnumUnion +func OptionalEnumChildAsOptionalEnumUnion(v *OptionalEnumChild) OptionalEnumUnion { + return OptionalEnumUnion{ + OptionalEnumChild: v, + } +} + +// OptionalEnumOtherAsOptionalEnumUnion is a convenience function that returns OptionalEnumOther wrapped in OptionalEnumUnion +func OptionalEnumOtherAsOptionalEnumUnion(v *OptionalEnumOther) OptionalEnumUnion { + return OptionalEnumUnion{ + OptionalEnumOther: v, + } +} + + +// Unmarshal JSON data into one of the pointers in the struct +func (dst *OptionalEnumUnion) UnmarshalJSON(data []byte) error { + var err error + match := 0 + // try to unmarshal data into OptionalEnumChild + err = newStrictDecoder(data).Decode(&dst.OptionalEnumChild) + if err == nil { + jsonOptionalEnumChild, _ := json.Marshal(dst.OptionalEnumChild) + if string(jsonOptionalEnumChild) == "{}" { // empty struct + dst.OptionalEnumChild = nil + } else { + if err = validator.Validate(dst.OptionalEnumChild); err != nil { + dst.OptionalEnumChild = nil + } else { + match++ + } + } + } else { + dst.OptionalEnumChild = nil + } + + // try to unmarshal data into OptionalEnumOther + err = newStrictDecoder(data).Decode(&dst.OptionalEnumOther) + if err == nil { + jsonOptionalEnumOther, _ := json.Marshal(dst.OptionalEnumOther) + if string(jsonOptionalEnumOther) == "{}" { // empty struct + dst.OptionalEnumOther = nil + } else { + if err = validator.Validate(dst.OptionalEnumOther); err != nil { + dst.OptionalEnumOther = nil + } else { + match++ + } + } + } else { + dst.OptionalEnumOther = nil + } + + if match > 1 { // more than 1 match + // reset to nil + dst.OptionalEnumChild = nil + dst.OptionalEnumOther = nil + + return fmt.Errorf("data matches more than one schema in oneOf(OptionalEnumUnion)") + } else if match == 1 { + return nil // exactly one match + } else { // no match + if err != nil { + return fmt.Errorf("data failed to match schemas in oneOf(OptionalEnumUnion): %v", err) + } + + return fmt.Errorf("data failed to match schemas in oneOf(OptionalEnumUnion)") + } +} + +// Marshal data from the first non-nil pointers in the struct to JSON +func (src OptionalEnumUnion) MarshalJSON() ([]byte, error) { + if src.OptionalEnumChild != nil { + return json.Marshal(&src.OptionalEnumChild) + } + + if src.OptionalEnumOther != nil { + return json.Marshal(&src.OptionalEnumOther) + } + + return nil, nil // no data in oneOf schemas +} + +// Get the actual instance +func (obj *OptionalEnumUnion) GetActualInstance() (interface{}) { + if obj == nil { + return nil + } + if obj.OptionalEnumChild != nil { + return obj.OptionalEnumChild + } + + if obj.OptionalEnumOther != nil { + return obj.OptionalEnumOther + } + + // all schemas are nil + return nil +} + +// Get the actual instance value +func (obj OptionalEnumUnion) GetActualInstanceValue() (interface{}) { + if obj.OptionalEnumChild != nil { + return *obj.OptionalEnumChild + } + + if obj.OptionalEnumOther != nil { + return *obj.OptionalEnumOther + } + + // all schemas are nil + return nil +} + +type NullableOptionalEnumUnion struct { + value *OptionalEnumUnion + isSet bool +} + +func (v NullableOptionalEnumUnion) Get() *OptionalEnumUnion { + return v.value +} + +func (v *NullableOptionalEnumUnion) Set(val *OptionalEnumUnion) { + v.value = val + v.isSet = true +} + +func (v NullableOptionalEnumUnion) IsSet() bool { + return v.isSet +} + +func (v *NullableOptionalEnumUnion) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableOptionalEnumUnion(val *OptionalEnumUnion) *NullableOptionalEnumUnion { + return &NullableOptionalEnumUnion{value: val, isSet: true} +} + +func (v NullableOptionalEnumUnion) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableOptionalEnumUnion) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + + diff --git a/samples/client/others/go/oneof-not-enum/model_optional_other.go b/samples/client/others/go/oneof-not-enum/model_optional_other.go new file mode 100644 index 000000000000..076121666842 --- /dev/null +++ b/samples/client/others/go/oneof-not-enum/model_optional_other.go @@ -0,0 +1,196 @@ +/* +oneOf not enum test + +No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + +API version: 1.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "encoding/json" + "fmt" +) + +// checks if the OptionalOther type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &OptionalOther{} + +// OptionalOther struct for OptionalOther +type OptionalOther struct { + Kind *string `json:"kind,omitempty"` + Label *string `json:"label,omitempty"` +} + +func (o *OptionalOther) validateStringEnumValues(data []byte) error { + var fields struct { + Kind json.RawMessage `json:"kind,omitempty"` + } + if err := json.Unmarshal(data, &fields); err != nil { + return err + } + if raw := fields.Kind; raw != nil { + var value interface{} + if err := json.Unmarshal(raw, &value); err != nil { + return err + } + if value == "known" || value == "a\"b" { + return fmt.Errorf("excluded value %v for property %s", value, "kind") + } + } + return nil +} + +type _OptionalOther OptionalOther + +func (o *OptionalOther) UnmarshalJSON(data []byte) error { + if err := o.validateStringEnumValues(data); err != nil { + return err + } + value := _OptionalOther(*o) + if err := json.Unmarshal(data, &value); err != nil { + return err + } + *o = OptionalOther(value) + return nil +} + +// NewOptionalOther instantiates a new OptionalOther 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 +func NewOptionalOther() *OptionalOther { + this := OptionalOther{} + return &this +} + +// NewOptionalOtherWithDefaults instantiates a new OptionalOther 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 +func NewOptionalOtherWithDefaults() *OptionalOther { + this := OptionalOther{} + return &this +} + +// GetKind returns the Kind field value if set, zero value otherwise. +func (o *OptionalOther) GetKind() string { + if o == nil || IsNil(o.Kind) { + var ret string + return ret + } + return *o.Kind +} + +// GetKindOk returns a tuple with the Kind field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *OptionalOther) GetKindOk() (*string, bool) { + if o == nil || IsNil(o.Kind) { + return nil, false + } + return o.Kind, true +} + +// HasKind returns a boolean if a field has been set. +func (o *OptionalOther) HasKind() bool { + if o != nil && !IsNil(o.Kind) { + return true + } + + return false +} + +// SetKind gets a reference to the given string and assigns it to the Kind field. +func (o *OptionalOther) SetKind(v string) { + o.Kind = &v +} + +// GetLabel returns the Label field value if set, zero value otherwise. +func (o *OptionalOther) GetLabel() string { + if o == nil || IsNil(o.Label) { + var ret string + return ret + } + return *o.Label +} + +// GetLabelOk returns a tuple with the Label field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *OptionalOther) GetLabelOk() (*string, bool) { + if o == nil || IsNil(o.Label) { + return nil, false + } + return o.Label, true +} + +// HasLabel returns a boolean if a field has been set. +func (o *OptionalOther) HasLabel() bool { + if o != nil && !IsNil(o.Label) { + return true + } + + return false +} + +// SetLabel gets a reference to the given string and assigns it to the Label field. +func (o *OptionalOther) SetLabel(v string) { + o.Label = &v +} + +func (o OptionalOther) MarshalJSON() ([]byte, error) { + toSerialize,err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o OptionalOther) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Kind) { + toSerialize["kind"] = o.Kind + } + if !IsNil(o.Label) { + toSerialize["label"] = o.Label + } + return toSerialize, nil +} + +type NullableOptionalOther struct { + value *OptionalOther + isSet bool +} + +func (v NullableOptionalOther) Get() *OptionalOther { + return v.value +} + +func (v *NullableOptionalOther) Set(val *OptionalOther) { + v.value = val + v.isSet = true +} + +func (v NullableOptionalOther) IsSet() bool { + return v.isSet +} + +func (v *NullableOptionalOther) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableOptionalOther(val *OptionalOther) *NullableOptionalOther { + return &NullableOptionalOther{value: val, isSet: true} +} + +func (v NullableOptionalOther) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableOptionalOther) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + + diff --git a/samples/client/others/go/oneof-not-enum/model_ordinary_enum.go b/samples/client/others/go/oneof-not-enum/model_ordinary_enum.go new file mode 100644 index 000000000000..d2371f09c69b --- /dev/null +++ b/samples/client/others/go/oneof-not-enum/model_ordinary_enum.go @@ -0,0 +1,126 @@ +/* +oneOf not enum test + +No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + +API version: 1.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "encoding/json" +) + +// checks if the OrdinaryEnum type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &OrdinaryEnum{} + +// OrdinaryEnum struct for OrdinaryEnum +type OrdinaryEnum struct { + Status *string `json:"status,omitempty"` +} + +// NewOrdinaryEnum instantiates a new OrdinaryEnum 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 +func NewOrdinaryEnum() *OrdinaryEnum { + this := OrdinaryEnum{} + return &this +} + +// NewOrdinaryEnumWithDefaults instantiates a new OrdinaryEnum 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 +func NewOrdinaryEnumWithDefaults() *OrdinaryEnum { + this := OrdinaryEnum{} + return &this +} + +// GetStatus returns the Status field value if set, zero value otherwise. +func (o *OrdinaryEnum) GetStatus() string { + if o == nil || IsNil(o.Status) { + var ret string + return ret + } + return *o.Status +} + +// GetStatusOk returns a tuple with the Status field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *OrdinaryEnum) GetStatusOk() (*string, bool) { + if o == nil || IsNil(o.Status) { + return nil, false + } + return o.Status, true +} + +// HasStatus returns a boolean if a field has been set. +func (o *OrdinaryEnum) HasStatus() bool { + if o != nil && !IsNil(o.Status) { + return true + } + + return false +} + +// SetStatus gets a reference to the given string and assigns it to the Status field. +func (o *OrdinaryEnum) SetStatus(v string) { + o.Status = &v +} + +func (o OrdinaryEnum) MarshalJSON() ([]byte, error) { + toSerialize,err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o OrdinaryEnum) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Status) { + toSerialize["status"] = o.Status + } + return toSerialize, nil +} + +type NullableOrdinaryEnum struct { + value *OrdinaryEnum + isSet bool +} + +func (v NullableOrdinaryEnum) Get() *OrdinaryEnum { + return v.value +} + +func (v *NullableOrdinaryEnum) Set(val *OrdinaryEnum) { + v.value = val + v.isSet = true +} + +func (v NullableOrdinaryEnum) IsSet() bool { + return v.isSet +} + +func (v *NullableOrdinaryEnum) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableOrdinaryEnum(val *OrdinaryEnum) *NullableOrdinaryEnum { + return &NullableOrdinaryEnum{value: val, isSet: true} +} + +func (v NullableOrdinaryEnum) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableOrdinaryEnum) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + + diff --git a/samples/client/others/go/oneof-not-enum/model_other.go b/samples/client/others/go/oneof-not-enum/model_other.go new file mode 100644 index 000000000000..559e3d908502 --- /dev/null +++ b/samples/client/others/go/oneof-not-enum/model_other.go @@ -0,0 +1,192 @@ +/* +oneOf not enum test + +No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + +API version: 1.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "encoding/json" + "bytes" + "fmt" + "strings" +) + +// checks if the Other type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &Other{} + +// Other struct for Other +type Other struct { + Kind string `json:"kind"` +} + +type _Other Other + +func (o *Other) validateStringEnumValues(data []byte) error { + var fields struct { + Kind json.RawMessage `json:"kind"` + } + if err := json.Unmarshal(data, &fields); err != nil { + return err + } + if raw := fields.Kind; raw != nil { + var value interface{} + if err := json.Unmarshal(raw, &value); err != nil { + return err + } + if value == "known" { + return fmt.Errorf("excluded value %v for property %s", value, "kind") + } + } + return nil +} + +// NewOther instantiates a new Other 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 +func NewOther(kind string) *Other { + this := Other{} + this.Kind = kind + return &this +} + +// NewOtherWithDefaults instantiates a new Other 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 +func NewOtherWithDefaults() *Other { + this := Other{} + return &this +} + +// GetKind returns the Kind field value +func (o *Other) GetKind() string { + if o == nil { + var ret string + return ret + } + + return o.Kind +} + +// GetKindOk returns a tuple with the Kind field value +// and a boolean to check if the value has been set. +func (o *Other) GetKindOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Kind, true +} + +// SetKind sets field value +func (o *Other) SetKind(v string) { + o.Kind = v +} + +func (o Other) MarshalJSON() ([]byte, error) { + toSerialize,err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o Other) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + toSerialize["kind"] = o.Kind + return toSerialize, nil +} + +func (o *Other) UnmarshalJSON(data []byte) (err error) { + if err := o.validateStringEnumValues(data); err != nil { + return err + } + // This validates that all required properties are included in the JSON object + // by unmarshalling the object into a generic map with string keys and checking + // that every required field exists as a key in the generic map. + requiredProperties := []string{ + "kind", + } + + allProperties := make(map[string]interface{}) + + err = json.Unmarshal(data, &allProperties) + + if err != nil { + return err; + } + + lookupRequiredProperty := func(requiredProperty string) (interface{}, string, bool) { + if value, exists := allProperties[requiredProperty]; exists { + return value, requiredProperty, true + } + for name, value := range allProperties { + if strings.EqualFold(name, requiredProperty) { + return value, name, true + } + } + return nil, "", false + } + for _, requiredProperty := range(requiredProperties) { + if _, _, exists := lookupRequiredProperty(requiredProperty); !exists { + return fmt.Errorf("no value given for required property %v", requiredProperty) + } + } + + varOther := _Other{} + + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.DisallowUnknownFields() + err = decoder.Decode(&varOther) + + if err != nil { + return err + } + + *o = Other(varOther) + + return err +} + +type NullableOther struct { + value *Other + isSet bool +} + +func (v NullableOther) Get() *Other { + return v.value +} + +func (v *NullableOther) Set(val *Other) { + v.value = val + v.isSet = true +} + +func (v NullableOther) IsSet() bool { + return v.isSet +} + +func (v *NullableOther) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableOther(val *Other) *NullableOther { + return &NullableOther{value: val, isSet: true} +} + +func (v NullableOther) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableOther) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + + diff --git a/samples/client/others/go/oneof-not-enum/model_tagged_union.go b/samples/client/others/go/oneof-not-enum/model_tagged_union.go new file mode 100644 index 000000000000..45ee31d19a4c --- /dev/null +++ b/samples/client/others/go/oneof-not-enum/model_tagged_union.go @@ -0,0 +1,175 @@ +/* +oneOf not enum test + +No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + +API version: 1.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "encoding/json" + "fmt" + "gopkg.in/validator.v2" +) + +// TaggedUnion - struct for TaggedUnion +type TaggedUnion struct { + Known *Known + Other *Other +} + +// KnownAsTaggedUnion is a convenience function that returns Known wrapped in TaggedUnion +func KnownAsTaggedUnion(v *Known) TaggedUnion { + return TaggedUnion{ + Known: v, + } +} + +// OtherAsTaggedUnion is a convenience function that returns Other wrapped in TaggedUnion +func OtherAsTaggedUnion(v *Other) TaggedUnion { + return TaggedUnion{ + Other: v, + } +} + + +// Unmarshal JSON data into one of the pointers in the struct +func (dst *TaggedUnion) UnmarshalJSON(data []byte) error { + var err error + match := 0 + // try to unmarshal data into Known + err = newStrictDecoder(data).Decode(&dst.Known) + if err == nil { + jsonKnown, _ := json.Marshal(dst.Known) + if string(jsonKnown) == "{}" { // empty struct + dst.Known = nil + } else { + if err = validator.Validate(dst.Known); err != nil { + dst.Known = nil + } else { + match++ + } + } + } else { + dst.Known = nil + } + + // try to unmarshal data into Other + err = newStrictDecoder(data).Decode(&dst.Other) + if err == nil { + jsonOther, _ := json.Marshal(dst.Other) + if string(jsonOther) == "{}" { // empty struct + dst.Other = nil + } else { + if err = validator.Validate(dst.Other); err != nil { + dst.Other = nil + } else { + match++ + } + } + } else { + dst.Other = nil + } + + if match > 1 { // more than 1 match + // reset to nil + dst.Known = nil + dst.Other = nil + + return fmt.Errorf("data matches more than one schema in oneOf(TaggedUnion)") + } else if match == 1 { + return nil // exactly one match + } else { // no match + if err != nil { + return fmt.Errorf("data failed to match schemas in oneOf(TaggedUnion): %v", err) + } + + return fmt.Errorf("data failed to match schemas in oneOf(TaggedUnion)") + } +} + +// Marshal data from the first non-nil pointers in the struct to JSON +func (src TaggedUnion) MarshalJSON() ([]byte, error) { + if src.Known != nil { + return json.Marshal(&src.Known) + } + + if src.Other != nil { + return json.Marshal(&src.Other) + } + + return nil, nil // no data in oneOf schemas +} + +// Get the actual instance +func (obj *TaggedUnion) GetActualInstance() (interface{}) { + if obj == nil { + return nil + } + if obj.Known != nil { + return obj.Known + } + + if obj.Other != nil { + return obj.Other + } + + // all schemas are nil + return nil +} + +// Get the actual instance value +func (obj TaggedUnion) GetActualInstanceValue() (interface{}) { + if obj.Known != nil { + return *obj.Known + } + + if obj.Other != nil { + return *obj.Other + } + + // all schemas are nil + return nil +} + +type NullableTaggedUnion struct { + value *TaggedUnion + isSet bool +} + +func (v NullableTaggedUnion) Get() *TaggedUnion { + return v.value +} + +func (v *NullableTaggedUnion) Set(val *TaggedUnion) { + v.value = val + v.isSet = true +} + +func (v NullableTaggedUnion) IsSet() bool { + return v.isSet +} + +func (v *NullableTaggedUnion) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableTaggedUnion(val *TaggedUnion) *NullableTaggedUnion { + return &NullableTaggedUnion{value: val, isSet: true} +} + +func (v NullableTaggedUnion) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableTaggedUnion) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + + diff --git a/samples/client/others/go/oneof-not-enum/oneof-not-enum_test.go b/samples/client/others/go/oneof-not-enum/oneof-not-enum_test.go new file mode 100644 index 000000000000..12bd8ac2c59f --- /dev/null +++ b/samples/client/others/go/oneof-not-enum/oneof-not-enum_test.go @@ -0,0 +1,40 @@ +package openapi + +import ( + "encoding/json" + "testing" +) + +func TestStringEnumScope(t *testing.T) { + cases := []struct { + name string + model interface{} + payload string + valid bool + }{ + {"Known accepts known", &Known{}, `{"kind":"known"}`, true}, + {"Known rejects other", &Known{}, `{"kind":"other"}`, false}, + {"Other rejects known", &Other{}, `{"kind":"known"}`, false}, + {"Other accepts other", &Other{}, `{"kind":"other"}`, true}, + {"Known accepts KIND", &Known{}, `{"KIND":"known"}`, true}, + {"Other rejects KIND", &Other{}, `{"KIND":"known"}`, false}, + {"ordinary enum accepts unknown", &OrdinaryEnum{}, `{"status":"future"}`, true}, + } + for _, test := range cases { + t.Run(test.name, func(t *testing.T) { + err := json.Unmarshal([]byte(test.payload), test.model) + if (err == nil) != test.valid { + t.Errorf("UnmarshalJSON error = %v, valid = %v", err, test.valid) + } + }) + } + + var known TaggedUnion + if err := json.Unmarshal([]byte(`{"kind":"known"}`), &known); err != nil || known.Known == nil || known.Other != nil { + t.Errorf("known union variant: %+v, error: %v", known, err) + } + var other TaggedUnion + if err := json.Unmarshal([]byte(`{"kind":"other"}`), &other); err != nil || other.Other == nil || other.Known != nil { + t.Errorf("other union variant: %+v, error: %v", other, err) + } +} diff --git a/samples/client/others/go/oneof-not-enum/response.go b/samples/client/others/go/oneof-not-enum/response.go new file mode 100644 index 000000000000..277c29f9cc04 --- /dev/null +++ b/samples/client/others/go/oneof-not-enum/response.go @@ -0,0 +1,47 @@ +/* +oneOf not enum test + +No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + +API version: 1.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "net/http" +) + +// APIResponse stores the API response returned by the server. +type APIResponse struct { + *http.Response `json:"-"` + Message string `json:"message,omitempty"` + // Operation is the name of the OpenAPI operation. + Operation string `json:"operation,omitempty"` + // RequestURL is the request URL. This value is always available, even if the + // embedded *http.Response is nil. + RequestURL string `json:"url,omitempty"` + // Method is the HTTP method used for the request. This value is always + // available, even if the embedded *http.Response is nil. + Method string `json:"method,omitempty"` + // Payload holds the contents of the response body (which may be nil or empty). + // This is provided here as the raw response.Body() reader will have already + // been drained. + Payload []byte `json:"-"` +} + +// NewAPIResponse returns a new APIResponse object. +func NewAPIResponse(r *http.Response) *APIResponse { + + response := &APIResponse{Response: r} + return response +} + +// NewAPIResponseWithError returns a new APIResponse object with the provided error message. +func NewAPIResponseWithError(errorMessage string) *APIResponse { + + response := &APIResponse{Message: errorMessage} + return response +} diff --git a/samples/client/others/go/oneof-not-enum/utils.go b/samples/client/others/go/oneof-not-enum/utils.go new file mode 100644 index 000000000000..10aac5d3f778 --- /dev/null +++ b/samples/client/others/go/oneof-not-enum/utils.go @@ -0,0 +1,361 @@ +/* +oneOf not enum test + +No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + +API version: 1.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "bytes" + "encoding/json" + "fmt" + "reflect" + "time" +) + +// PtrBool is a helper routine that returns a pointer to given boolean value. +func PtrBool(v bool) *bool { return &v } + +// PtrInt is a helper routine that returns a pointer to given integer value. +func PtrInt(v int) *int { return &v } + +// PtrInt32 is a helper routine that returns a pointer to given integer value. +func PtrInt32(v int32) *int32 { return &v } + +// PtrInt64 is a helper routine that returns a pointer to given integer value. +func PtrInt64(v int64) *int64 { return &v } + +// PtrFloat32 is a helper routine that returns a pointer to given float value. +func PtrFloat32(v float32) *float32 { return &v } + +// PtrFloat64 is a helper routine that returns a pointer to given float value. +func PtrFloat64(v float64) *float64 { return &v } + +// PtrString is a helper routine that returns a pointer to given string value. +func PtrString(v string) *string { return &v } + +// PtrTime is helper routine that returns a pointer to given Time value. +func PtrTime(v time.Time) *time.Time { return &v } + +type NullableBool struct { + value *bool + isSet bool +} + +func (v NullableBool) Get() *bool { + return v.value +} + +func (v *NullableBool) Set(val *bool) { + v.value = val + v.isSet = true +} + +func (v NullableBool) IsSet() bool { + return v.isSet +} + +func (v *NullableBool) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableBool(val *bool) *NullableBool { + return &NullableBool{value: val, isSet: true} +} + +func (v NullableBool) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableBool) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + +type NullableInt struct { + value *int + isSet bool +} + +func (v NullableInt) Get() *int { + return v.value +} + +func (v *NullableInt) Set(val *int) { + v.value = val + v.isSet = true +} + +func (v NullableInt) IsSet() bool { + return v.isSet +} + +func (v *NullableInt) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableInt(val *int) *NullableInt { + return &NullableInt{value: val, isSet: true} +} + +func (v NullableInt) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableInt) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + +type NullableInt32 struct { + value *int32 + isSet bool +} + +func (v NullableInt32) Get() *int32 { + return v.value +} + +func (v *NullableInt32) Set(val *int32) { + v.value = val + v.isSet = true +} + +func (v NullableInt32) IsSet() bool { + return v.isSet +} + +func (v *NullableInt32) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableInt32(val *int32) *NullableInt32 { + return &NullableInt32{value: val, isSet: true} +} + +func (v NullableInt32) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableInt32) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + +type NullableInt64 struct { + value *int64 + isSet bool +} + +func (v NullableInt64) Get() *int64 { + return v.value +} + +func (v *NullableInt64) Set(val *int64) { + v.value = val + v.isSet = true +} + +func (v NullableInt64) IsSet() bool { + return v.isSet +} + +func (v *NullableInt64) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableInt64(val *int64) *NullableInt64 { + return &NullableInt64{value: val, isSet: true} +} + +func (v NullableInt64) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableInt64) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + +type NullableFloat32 struct { + value *float32 + isSet bool +} + +func (v NullableFloat32) Get() *float32 { + return v.value +} + +func (v *NullableFloat32) Set(val *float32) { + v.value = val + v.isSet = true +} + +func (v NullableFloat32) IsSet() bool { + return v.isSet +} + +func (v *NullableFloat32) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableFloat32(val *float32) *NullableFloat32 { + return &NullableFloat32{value: val, isSet: true} +} + +func (v NullableFloat32) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableFloat32) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + +type NullableFloat64 struct { + value *float64 + isSet bool +} + +func (v NullableFloat64) Get() *float64 { + return v.value +} + +func (v *NullableFloat64) Set(val *float64) { + v.value = val + v.isSet = true +} + +func (v NullableFloat64) IsSet() bool { + return v.isSet +} + +func (v *NullableFloat64) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableFloat64(val *float64) *NullableFloat64 { + return &NullableFloat64{value: val, isSet: true} +} + +func (v NullableFloat64) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableFloat64) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + +type NullableString struct { + value *string + isSet bool +} + +func (v NullableString) Get() *string { + return v.value +} + +func (v *NullableString) Set(val *string) { + v.value = val + v.isSet = true +} + +func (v NullableString) IsSet() bool { + return v.isSet +} + +func (v *NullableString) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableString(val *string) *NullableString { + return &NullableString{value: val, isSet: true} +} + +func (v NullableString) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableString) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + +type NullableTime struct { + value *time.Time + isSet bool +} + +func (v NullableTime) Get() *time.Time { + return v.value +} + +func (v *NullableTime) Set(val *time.Time) { + v.value = val + v.isSet = true +} + +func (v NullableTime) IsSet() bool { + return v.isSet +} + +func (v *NullableTime) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableTime(val *time.Time) *NullableTime { + return &NullableTime{value: val, isSet: true} +} + +func (v NullableTime) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableTime) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + +// IsNil checks if an input is nil +func IsNil(i interface{}) bool { + if i == nil { + return true + } + switch reflect.TypeOf(i).Kind() { + case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.UnsafePointer, reflect.Interface, reflect.Slice: + return reflect.ValueOf(i).IsNil() + case reflect.Array: + return reflect.ValueOf(i).IsZero() + } + return false +} + +type MappedNullable interface { + ToMap() (map[string]interface{}, error) +} + +// A wrapper for strict JSON decoding +func newStrictDecoder(data []byte) *json.Decoder { + dec := json.NewDecoder(bytes.NewBuffer(data)) + dec.DisallowUnknownFields() + return dec +} + +// Prevent trying to import "fmt" +func reportError(format string, a ...interface{}) error { + return fmt.Errorf(format, a...) +} \ No newline at end of file