From 3346ae885866ab1f44fbc6e2aa9c849a6eafc4af Mon Sep 17 00:00:00 2001 From: David Steele Date: Wed, 30 Jul 2025 14:10:57 +0100 Subject: [PATCH] Fixup dependency on forked serde_xml --- .github/workflows/samples-rust.yaml | 2 +- .../rust-server-deprecated/Cargo.mustache | 3 +- .../rust-server-deprecated/models.mustache | 18 +- .../server-response-body-instance.mustache | 7 +- .../main/resources/rust-server/Cargo.mustache | 4 +- .../resources/rust-server/models.mustache | 17 +- .../server-response-body-instance.mustache | 7 +- .../petstore/c/unit-tests/manual-PetAPI.c | 7 + .../go/go-petstore-aws-signature/.gitignore | 24 + .../.openapi-generator-ignore | 23 + .../.openapi-generator/FILES | 19 + .../.openapi-generator/VERSION | 1 + .../go/go-petstore-aws-signature/.travis.yml | 8 + .../go/go-petstore-aws-signature/README.md | 145 ++++ .../api/openapi.yaml | 151 ++++ .../go/go-petstore-aws-signature/api_pet.go | 134 ++++ .../go/go-petstore-aws-signature/client.go | 710 ++++++++++++++++++ .../configuration.go | 231 ++++++ .../docs/Category.md | 82 ++ .../go/go-petstore-aws-signature/docs/Pet.md | 176 +++++ .../go-petstore-aws-signature/docs/PetAPI.md | 75 ++ .../go/go-petstore-aws-signature/docs/Tag.md | 82 ++ .../go/go-petstore-aws-signature/git_push.sh | 57 ++ .../go/go-petstore-aws-signature/go.mod | 9 + .../go/go-petstore-aws-signature/go.sum | 13 + .../model_category.go | 192 +++++ .../go/go-petstore-aws-signature/model_pet.go | 350 +++++++++ .../go/go-petstore-aws-signature/model_tag.go | 192 +++++ .../go/go-petstore-aws-signature/response.go | 47 ++ .../test/api_pet_test.go | 37 + .../go/go-petstore-aws-signature/utils.go | 361 +++++++++ .../output/openapi-v3/Cargo.toml | 3 +- .../output/openapi-v3/src/models.rs | 42 +- .../output/openapi-v3/src/server/mod.rs | 7 +- .../Cargo.toml | 3 +- .../output/multipart-v3/Cargo.toml | 1 + .../output/no-example-v3/Cargo.toml | 1 + .../rust-server/output/openapi-v3/Cargo.toml | 3 +- .../output/openapi-v3/src/models.rs | 40 +- .../output/openapi-v3/src/server/mod.rs | 7 +- .../rust-server/output/ops-v3/Cargo.toml | 1 + .../Cargo.toml | 3 +- .../output/ping-bearer-auth/Cargo.toml | 1 + .../output/rust-server-test/Cargo.toml | 1 + 44 files changed, 3234 insertions(+), 63 deletions(-) create mode 100644 samples/openapi3/client/petstore/go/go-petstore-aws-signature/.gitignore create mode 100644 samples/openapi3/client/petstore/go/go-petstore-aws-signature/.openapi-generator-ignore create mode 100644 samples/openapi3/client/petstore/go/go-petstore-aws-signature/.openapi-generator/FILES create mode 100644 samples/openapi3/client/petstore/go/go-petstore-aws-signature/.openapi-generator/VERSION create mode 100644 samples/openapi3/client/petstore/go/go-petstore-aws-signature/.travis.yml create mode 100644 samples/openapi3/client/petstore/go/go-petstore-aws-signature/README.md create mode 100644 samples/openapi3/client/petstore/go/go-petstore-aws-signature/api/openapi.yaml create mode 100644 samples/openapi3/client/petstore/go/go-petstore-aws-signature/api_pet.go create mode 100644 samples/openapi3/client/petstore/go/go-petstore-aws-signature/client.go create mode 100644 samples/openapi3/client/petstore/go/go-petstore-aws-signature/configuration.go create mode 100644 samples/openapi3/client/petstore/go/go-petstore-aws-signature/docs/Category.md create mode 100644 samples/openapi3/client/petstore/go/go-petstore-aws-signature/docs/Pet.md create mode 100644 samples/openapi3/client/petstore/go/go-petstore-aws-signature/docs/PetAPI.md create mode 100644 samples/openapi3/client/petstore/go/go-petstore-aws-signature/docs/Tag.md create mode 100644 samples/openapi3/client/petstore/go/go-petstore-aws-signature/git_push.sh create mode 100644 samples/openapi3/client/petstore/go/go-petstore-aws-signature/go.mod create mode 100644 samples/openapi3/client/petstore/go/go-petstore-aws-signature/go.sum create mode 100644 samples/openapi3/client/petstore/go/go-petstore-aws-signature/model_category.go create mode 100644 samples/openapi3/client/petstore/go/go-petstore-aws-signature/model_pet.go create mode 100644 samples/openapi3/client/petstore/go/go-petstore-aws-signature/model_tag.go create mode 100644 samples/openapi3/client/petstore/go/go-petstore-aws-signature/response.go create mode 100644 samples/openapi3/client/petstore/go/go-petstore-aws-signature/test/api_pet_test.go create mode 100644 samples/openapi3/client/petstore/go/go-petstore-aws-signature/utils.go diff --git a/.github/workflows/samples-rust.yaml b/.github/workflows/samples-rust.yaml index b46265ca16a6..5ad9823d5d5b 100644 --- a/.github/workflows/samples-rust.yaml +++ b/.github/workflows/samples-rust.yaml @@ -50,7 +50,7 @@ jobs: working-directory: ${{ matrix.sample }} run: | set -e - # Skip samples/client/petstore/rust/ as it's tests are failing. + # Skip samples/client/petstore/rust/ as its tests are failing. if [[ "${{ matrix.sample }}" == "samples/client/petstore/rust/" ]]; then echo "Skipping tests for samples/client/petstore/rust/" exit 0 diff --git a/modules/openapi-generator/src/main/resources/rust-server-deprecated/Cargo.mustache b/modules/openapi-generator/src/main/resources/rust-server-deprecated/Cargo.mustache index cec9e012796a..da3324863d54 100644 --- a/modules/openapi-generator/src/main/resources/rust-server-deprecated/Cargo.mustache +++ b/modules/openapi-generator/src/main/resources/rust-server-deprecated/Cargo.mustache @@ -101,7 +101,8 @@ validator = { version = "0.16", features = ["derive"] } {{#usesXml}} # TODO: this should be updated to point at the official crate once # https://github.com/RReverser/serde-xml-rs/pull/45 is accepted upstream -serde-xml-rs = {git = "https://github.com/Metaswitch/serde-xml-rs" , branch = "master"} +#serde-xml-rs = {git = "https://github.com/Metaswitch/serde-xml-rs" , branch = "master"} +serde-xml-rs = "0.8" {{/usesXml}} {{#apiUsesMultipart}} mime_0_2 = { package = "mime", version = "0.2.6", optional = true } diff --git a/modules/openapi-generator/src/main/resources/rust-server-deprecated/models.mustache b/modules/openapi-generator/src/main/resources/rust-server-deprecated/models.mustache index 4dfc68f61cb0..540c6d87e74d 100644 --- a/modules/openapi-generator/src/main/resources/rust-server-deprecated/models.mustache +++ b/modules/openapi-generator/src/main/resources/rust-server-deprecated/models.mustache @@ -159,13 +159,19 @@ impl ::std::str::FromStr for {{{classname}}} { {{#arrayModelType}} {{#vendorExtensions}}{{#x-item-xml-name}}// Utility function for wrapping list elements when serializing xml #[allow(non_snake_case)] -fn wrap_in_{{{x-item-xml-name}}}(item: &Vec<{{{arrayModelType}}}>, serializer: S) -> std::result::Result +fn wrap_in_{{{x-item-xml-name}}}(items: &Vec<{{{arrayModelType}}}>, serializer: S) -> std::result::Result where S: serde::ser::Serializer, { - serde_xml_rs::wrap_primitives(item, serializer, "{{{x-item-xml-name}}}") -} + use serde::ser::SerializeMap; + let mut map = serializer.serialize_map(None)?; + for ref item in items { + map.serialize_key("{{{x-item-xml-name}}}")?; + map.serialize_value(item)?; + } + map.end() +} {{/x-item-xml-name}} {{/vendorExtensions}} {{! vec}} @@ -633,10 +639,10 @@ impl {{{classname}}} { #[allow(dead_code)] pub(crate) fn as_xml(&self) -> String { {{#xmlNamespace}} - let mut namespaces = std::collections::BTreeMap::new(); // An empty string is used to indicate a global namespace in xmltree. - namespaces.insert("".to_string(), Self::NAMESPACE.to_string()); - serde_xml_rs::to_string_with_namespaces(&self, namespaces).expect("impossible to fail to serialize") + let config = serde_xml_rs::SerdeXml::new() + .namespace("", Self::NAMESPACE); + config.to_string(&self).expect("impossible to fail to serialize") {{/xmlNamespace}} {{^xmlNamespace}} serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") diff --git a/modules/openapi-generator/src/main/resources/rust-server-deprecated/server-response-body-instance.mustache b/modules/openapi-generator/src/main/resources/rust-server-deprecated/server-response-body-instance.mustache index 9bb648c525f7..710e65b8b5bb 100644 --- a/modules/openapi-generator/src/main/resources/rust-server-deprecated/server-response-body-instance.mustache +++ b/modules/openapi-generator/src/main/resources/rust-server-deprecated/server-response-body-instance.mustache @@ -12,11 +12,10 @@ let body = serde_xml_rs::to_string(&body).expect("impossible to fail to serialize"); {{/x-has-namespace}} {{#x-has-namespace}} - let mut namespaces = std::collections::BTreeMap::new(); - // An empty string is used to indicate a global namespace in xmltree. - namespaces.insert("".to_string(), {{{dataType}}}::NAMESPACE.to_string()); - let body = serde_xml_rs::to_string_with_namespaces(&body, namespaces).expect("impossible to fail to serialize"); + let config = serde_xml_rs::SerdeXml::new() + .namespace("", {{{dataType}}}::NAMESPACE); + let body = config.to_string(&body).expect("impossible to fail to serialize"); {{/x-has-namespace}} {{/x-produces-xml}} {{#x-produces-json}} diff --git a/modules/openapi-generator/src/main/resources/rust-server/Cargo.mustache b/modules/openapi-generator/src/main/resources/rust-server/Cargo.mustache index 12fc2bebcb97..a5e99335111e 100644 --- a/modules/openapi-generator/src/main/resources/rust-server/Cargo.mustache +++ b/modules/openapi-generator/src/main/resources/rust-server/Cargo.mustache @@ -96,8 +96,8 @@ validator = { version = "0.20", features = ["derive"] } {{#usesXml}} # TODO: this should be updated to point at the official crate once # https://github.com/RReverser/serde-xml-rs/pull/45 is accepted upstream -serde-xml-rs = {git = "https://github.com/Metaswitch/serde-xml-rs" , branch = "master"} -{{/usesXml}} +#serde-xml-rs = {git = "https://github.com/Metaswitch/serde-xml-rs" , branch = "master"} +serde-xml-rs = "0.8"{{/usesXml}} {{#apiUsesMultipartFormData}} multipart = { version = "0.18", default-features = false, optional = true } {{/apiUsesMultipartFormData}} diff --git a/modules/openapi-generator/src/main/resources/rust-server/models.mustache b/modules/openapi-generator/src/main/resources/rust-server/models.mustache index 8f2339c2cb6f..b56876d6eb47 100644 --- a/modules/openapi-generator/src/main/resources/rust-server/models.mustache +++ b/modules/openapi-generator/src/main/resources/rust-server/models.mustache @@ -158,11 +158,18 @@ impl ::std::str::FromStr for {{{classname}}} { {{#arrayModelType}} {{#vendorExtensions}}{{#x-item-xml-name}}// Utility function for wrapping list elements when serializing xml #[allow(non_snake_case)] -fn wrap_in_{{{x-item-xml-name}}}(item: &Vec<{{{arrayModelType}}}>, serializer: S) -> std::result::Result +fn wrap_in_{{{x-item-xml-name}}}(items: &Vec<{{{arrayModelType}}}>, serializer: S) -> std::result::Result where S: serde::ser::Serializer, { - serde_xml_rs::wrap_primitives(item, serializer, "{{{x-item-xml-name}}}") + use serde::ser::SerializeMap; + + let mut map = serializer.serialize_map(None)?; + for ref item in items { + map.serialize_key("{{{x-item-xml-name}}}")?; + map.serialize_value(item)?; + } + map.end() } {{/x-item-xml-name}} @@ -632,10 +639,10 @@ impl {{{classname}}} { #[allow(dead_code)] pub(crate) fn as_xml(&self) -> String { {{#xmlNamespace}} - let mut namespaces = std::collections::BTreeMap::new(); // An empty string is used to indicate a global namespace in xmltree. - namespaces.insert("".to_string(), Self::NAMESPACE.to_string()); - serde_xml_rs::to_string_with_namespaces(&self, namespaces).expect("impossible to fail to serialize") + let config = serde_xml_rs::SerdeXml::new() + .namespace("", Self::NAMESPACE); + config.to_string(&self).expect("impossible to fail to serialize") {{/xmlNamespace}} {{^xmlNamespace}} serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") diff --git a/modules/openapi-generator/src/main/resources/rust-server/server-response-body-instance.mustache b/modules/openapi-generator/src/main/resources/rust-server/server-response-body-instance.mustache index b21e7a6db834..27e9f30b1234 100644 --- a/modules/openapi-generator/src/main/resources/rust-server/server-response-body-instance.mustache +++ b/modules/openapi-generator/src/main/resources/rust-server/server-response-body-instance.mustache @@ -12,11 +12,10 @@ let body = serde_xml_rs::to_string(&body).expect("impossible to fail to serialize"); {{/x-has-namespace}} {{#x-has-namespace}} - let mut namespaces = std::collections::BTreeMap::new(); - // An empty string is used to indicate a global namespace in xmltree. - namespaces.insert("".to_string(), {{{dataType}}}::NAMESPACE.to_string()); - let body = serde_xml_rs::to_string_with_namespaces(&body, namespaces).expect("impossible to fail to serialize"); + let config = serde_xml_rs::SerdeXml::new() + .namespace("", {{{dataType}}}::NAMESPACE); + let body = config.to_string(&body).expect("impossible to fail to serialize"); {{/x-has-namespace}} {{/x-produces-xml}} {{#x-produces-json}} diff --git a/samples/client/petstore/c/unit-tests/manual-PetAPI.c b/samples/client/petstore/c/unit-tests/manual-PetAPI.c index b24bd1ced153..a510b79214a5 100644 --- a/samples/client/petstore/c/unit-tests/manual-PetAPI.c +++ b/samples/client/petstore/c/unit-tests/manual-PetAPI.c @@ -2,8 +2,10 @@ #include #include #include + #include #include "../api/PetAPI.h" + void preInvokeFunc(CURL *curl); #define EXAMPLE_CATEGORY_NAME "Example Category" #define EXAMPLE_CATEGORY_ID 5 @@ -16,10 +18,15 @@ #define EXAMPLE_TAG_2_ID 542353 #define EXAMPLE_PET_ID 1234 // Set to 0 to generate a new pet +void preInvokeFunc(CURL *curl) { + curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); + printf("CURL pre-invoke function called - verbose mode enabled\n"); +} int main() { // Add pet test apiClient_t *apiClient = apiClient_create(); + apiClient->curl_pre_invoke_func = preInvokeFunc; char *categoryName = malloc(strlen(EXAMPLE_CATEGORY_NAME) + 1); strcpy(categoryName, EXAMPLE_CATEGORY_NAME); diff --git a/samples/openapi3/client/petstore/go/go-petstore-aws-signature/.gitignore b/samples/openapi3/client/petstore/go/go-petstore-aws-signature/.gitignore new file mode 100644 index 000000000000..daf913b1b347 --- /dev/null +++ b/samples/openapi3/client/petstore/go/go-petstore-aws-signature/.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/openapi3/client/petstore/go/go-petstore-aws-signature/.openapi-generator-ignore b/samples/openapi3/client/petstore/go/go-petstore-aws-signature/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/openapi3/client/petstore/go/go-petstore-aws-signature/.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/openapi3/client/petstore/go/go-petstore-aws-signature/.openapi-generator/FILES b/samples/openapi3/client/petstore/go/go-petstore-aws-signature/.openapi-generator/FILES new file mode 100644 index 000000000000..c6b0a6bd16db --- /dev/null +++ b/samples/openapi3/client/petstore/go/go-petstore-aws-signature/.openapi-generator/FILES @@ -0,0 +1,19 @@ +.gitignore +.travis.yml +README.md +api/openapi.yaml +api_pet.go +client.go +configuration.go +docs/Category.md +docs/Pet.md +docs/PetAPI.md +docs/Tag.md +git_push.sh +go.mod +go.sum +model_category.go +model_pet.go +model_tag.go +response.go +utils.go diff --git a/samples/openapi3/client/petstore/go/go-petstore-aws-signature/.openapi-generator/VERSION b/samples/openapi3/client/petstore/go/go-petstore-aws-signature/.openapi-generator/VERSION new file mode 100644 index 000000000000..fc74d6ceba8e --- /dev/null +++ b/samples/openapi3/client/petstore/go/go-petstore-aws-signature/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.15.0-SNAPSHOT diff --git a/samples/openapi3/client/petstore/go/go-petstore-aws-signature/.travis.yml b/samples/openapi3/client/petstore/go/go-petstore-aws-signature/.travis.yml new file mode 100644 index 000000000000..f5cb2ce9a5aa --- /dev/null +++ b/samples/openapi3/client/petstore/go/go-petstore-aws-signature/.travis.yml @@ -0,0 +1,8 @@ +language: go + +install: + - go get -d -v . + +script: + - go build -v ./ + diff --git a/samples/openapi3/client/petstore/go/go-petstore-aws-signature/README.md b/samples/openapi3/client/petstore/go/go-petstore-aws-signature/README.md new file mode 100644 index 000000000000..30e20544597c --- /dev/null +++ b/samples/openapi3/client/petstore/go/go-petstore-aws-signature/README.md @@ -0,0 +1,145 @@ +# Go API client for petstore + +This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + +## 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.15.0-SNAPSHOT +- Build package: org.openapitools.codegen.languages.GoClientCodegen + +## Installation + +Install the following dependencies: + +```sh +go get github.com/stretchr/testify/assert +go get golang.org/x/oauth2 +go get golang.org/x/net/context +``` + +Put the package under your project folder and add the following in import: + +```go +import petstore "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 `petstore.ContextServerIndex` of type `int`. + +```go +ctx := context.WithValue(context.Background(), petstore.ContextServerIndex, 1) +``` + +### Templated Server URL + +Templated server URL is formatted using default variables from configuration or from context value `petstore.ContextServerVariables` of type `map[string]string`. + +```go +ctx := context.WithValue(context.Background(), petstore.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 `petstore.ContextOperationServerIndices` and `petstore.ContextOperationServerVariables` context maps. + +```go +ctx := context.WithValue(context.Background(), petstore.ContextOperationServerIndices, map[string]int{ + "{classname}Service.{nickname}": 2, +}) +ctx = context.WithValue(context.Background(), petstore.ContextOperationServerVariables, map[string]map[string]string{ + "{classname}Service.{nickname}": { + "port": "8443", + }, +}) +``` + +## Documentation for API Endpoints + +All URIs are relative to *http://petstore.swagger.io/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*PetAPI* | [**AddPet**](docs/PetAPI.md#addpet) | **Post** /pet | Add a new pet to the store + + +## Documentation For Models + + - [Category](docs/Category.md) + - [Pet](docs/Pet.md) + - [Tag](docs/Tag.md) + + +## Documentation For Authorization + + +Authentication schemes defined for the API: +### petstore_auth + + +- **Type**: OAuth +- **Flow**: implicit +- **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog +- **Scopes**: + - **write:pets**: modify pets in your account + - **read:pets**: read your pets + +Example + +```go +auth := context.WithValue(context.Background(), petstore.ContextAccessToken, "ACCESSTOKENSTRING") +r, err := client.Service.Operation(auth, args) +``` + +Or via OAuth2 module to automatically refresh tokens and perform user authentication. + +```go +import "golang.org/x/oauth2" + +/* Perform OAuth2 round trip request and obtain a token */ + +tokenSource := oauth2cfg.TokenSource(createContext(httpClient), &token) +auth := context.WithValue(oauth2.NoContext, petstore.ContextOAuth2, tokenSource) +r, err := client.Service.Operation(auth, args) +``` + + +## Documentation for Utility Methods + +Due to the fact that model structure members are all pointers, this package contains +a number of utility functions to easily obtain pointers to values of basic types. +Each of these functions takes a value of the given basic type and returns a pointer to it: + +* `PtrBool` +* `PtrInt` +* `PtrInt32` +* `PtrInt64` +* `PtrFloat` +* `PtrFloat32` +* `PtrFloat64` +* `PtrString` +* `PtrTime` + +## Author + + + diff --git a/samples/openapi3/client/petstore/go/go-petstore-aws-signature/api/openapi.yaml b/samples/openapi3/client/petstore/go/go-petstore-aws-signature/api/openapi.yaml new file mode 100644 index 000000000000..25e6b6ed012a --- /dev/null +++ b/samples/openapi3/client/petstore/go/go-petstore-aws-signature/api/openapi.yaml @@ -0,0 +1,151 @@ +openapi: 3.0.0 +info: + description: "This is a sample server Petstore server. For this sample, you can\ + \ use the api key `special-key` to test the authorization filters." + license: + name: Apache-2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html + title: OpenAPI Petstore + version: 1.0.0 +externalDocs: + description: Find out more about Swagger + url: http://swagger.io +servers: +- url: http://petstore.swagger.io/v2 +tags: +- description: Everything about your Pets + name: pet +paths: + /pet: + post: + description: "" + operationId: addPet + requestBody: + $ref: "#/components/requestBodies/Pet" + responses: + "200": + content: + application/xml: + schema: + $ref: "#/components/schemas/Pet" + application/json: + schema: + $ref: "#/components/schemas/Pet" + description: successful operation + "405": + description: Invalid input + security: + - petstore_auth: + - write:pets + - read:pets + summary: Add a new pet to the store + tags: + - pet +components: + requestBodies: + Pet: + content: + application/json: + schema: + $ref: "#/components/schemas/Pet" + application/xml: + schema: + $ref: "#/components/schemas/Pet" + description: Pet object that needs to be added to the store + required: true + schemas: + Category: + description: A category for a pet + example: + name: name + id: 6 + properties: + id: + format: int64 + type: integer + name: + pattern: "^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$" + type: string + title: Pet category + type: object + xml: + name: Category + Tag: + description: A tag for a pet + example: + name: name + id: 1 + properties: + id: + format: int64 + type: integer + name: + type: string + title: Pet Tag + type: object + xml: + name: Tag + Pet: + description: A pet for sale in the pet store + example: + photoUrls: + - photoUrls + - photoUrls + name: doggie + id: 0 + category: + name: name + id: 6 + tags: + - name: name + id: 1 + - name: name + id: 1 + status: available + properties: + id: + format: int64 + type: integer + category: + $ref: "#/components/schemas/Category" + name: + example: doggie + type: string + photoUrls: + items: + type: string + type: array + xml: + name: photoUrl + wrapped: true + tags: + items: + $ref: "#/components/schemas/Tag" + type: array + xml: + name: tag + wrapped: true + status: + deprecated: true + description: pet status in the store + enum: + - available + - pending + - sold + type: string + required: + - name + - photoUrls + title: a Pet + type: object + xml: + name: Pet + securitySchemes: + petstore_auth: + flows: + implicit: + authorizationUrl: http://petstore.swagger.io/api/oauth/dialog + scopes: + write:pets: modify pets in your account + read:pets: read your pets + type: oauth2 diff --git a/samples/openapi3/client/petstore/go/go-petstore-aws-signature/api_pet.go b/samples/openapi3/client/petstore/go/go-petstore-aws-signature/api_pet.go new file mode 100644 index 000000000000..b875067e48d3 --- /dev/null +++ b/samples/openapi3/client/petstore/go/go-petstore-aws-signature/api_pet.go @@ -0,0 +1,134 @@ +/* +OpenAPI Petstore + +This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + +API version: 1.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package petstore + +import ( + "bytes" + "context" + "io" + "net/http" + "net/url" +) + + +// PetAPIService PetAPI service +type PetAPIService service + +type ApiAddPetRequest struct { + ctx context.Context + ApiService *PetAPIService + pet *Pet +} + +// Pet object that needs to be added to the store +func (r ApiAddPetRequest) Pet(pet Pet) ApiAddPetRequest { + r.pet = &pet + return r +} + +func (r ApiAddPetRequest) Execute() (*Pet, *http.Response, error) { + return r.ApiService.AddPetExecute(r) +} + +/* +AddPet Add a new pet to the store + + + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @return ApiAddPetRequest +*/ +func (a *PetAPIService) AddPet(ctx context.Context) ApiAddPetRequest { + return ApiAddPetRequest{ + ApiService: a, + ctx: ctx, + } +} + +// Execute executes the request +// @return Pet +func (a *PetAPIService) AddPetExecute(r ApiAddPetRequest) (*Pet, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPost + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *Pet + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "PetAPIService.AddPet") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/pet" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.pet == nil { + return localVarReturnValue, nil, reportError("pet is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json", "application/xml"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/xml", "application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.pet + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} diff --git a/samples/openapi3/client/petstore/go/go-petstore-aws-signature/client.go b/samples/openapi3/client/petstore/go/go-petstore-aws-signature/client.go new file mode 100644 index 000000000000..7d9664e41128 --- /dev/null +++ b/samples/openapi3/client/petstore/go/go-petstore-aws-signature/client.go @@ -0,0 +1,710 @@ +/* +OpenAPI Petstore + +This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + +API version: 1.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package petstore + +import ( + "bytes" + "context" + "encoding/json" + "encoding/xml" + "errors" + "fmt" + "io" + "log" + "mime/multipart" + "net/http" + "net/http/httputil" + "net/url" + "os" + "path/filepath" + "reflect" + "regexp" + "strconv" + "strings" + "time" + "unicode/utf8" + + "golang.org/x/oauth2" + awsv4 "github.com/aws/aws-sdk-go-v2/aws/signer/v4" + awscredentials "github.com/aws/aws-sdk-go-v2/credentials" + "crypto/sha256" + "encoding/hex" +) + +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 OpenAPI Petstore API v1.0.0 +// In most cases there should be only one, shared, APIClient. +type APIClient struct { + cfg *Configuration + common service // Reuse a single struct instead of allocating one for each service on the heap. + + // API Services + + PetAPI *PetAPIService +} + +type service struct { + client *APIClient +} + +// NewAPIClient creates a new API client. Requires a userAgent string describing your application. +// optionally a custom http.Client to allow for advanced features such as caching. +func NewAPIClient(cfg *Configuration) *APIClient { + if cfg.HTTPClient == nil { + cfg.HTTPClient = http.DefaultClient + } + + c := &APIClient{} + c.cfg = cfg + c.common.client = c + + // API Services + c.PetAPI = (*PetAPIService)(&c.common) + + return c +} + +func atoi(in string) (int, error) { + return strconv.Atoi(in) +} + +// selectHeaderContentType select a content type from the available list. +func selectHeaderContentType(contentTypes []string) string { + if len(contentTypes) == 0 { + return "" + } + if contains(contentTypes, "application/json") { + return "application/json" + } + return contentTypes[0] // use the first content type specified in 'consumes' +} + +// selectHeaderAccept join all accept types and return +func selectHeaderAccept(accepts []string) string { + if len(accepts) == 0 { + return "" + } + + if contains(accepts, "application/json") { + return "application/json" + } + + return strings.Join(accepts, ",") +} + +// contains is a case 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. + + // OAuth2 authentication + if tok, ok := ctx.Value(ContextOAuth2).(oauth2.TokenSource); ok { + // We were able to grab an oauth2 token from the context + var latestToken *oauth2.Token + if latestToken, err = tok.Token(); err != nil { + return nil, err + } + + latestToken.SetAuthHeader(localVarRequest) + } + + // AWS Signature v4 Authentication + if auth, ok := ctx.Value(ContextAWSv4).(AWSv4); ok { + credsProvider := awscredentials.NewStaticCredentialsProvider(auth.AccessKey, auth.SecretKey, auth.SessionToken) + creds, err := credsProvider.Retrieve(ctx) + if err != nil { + return nil, err + } + + // Define default values for region and service to maintain backward compatibility + region := auth.Region + if region == "" { + region = "eu-west-2" + } + service := auth.Service + if service == "" { + service = "oapi" + } + + // Compute payload hash from the request body + var payloadHash string + if body == nil { + // Empty body + hash := sha256.Sum256([]byte("")) + payloadHash = hex.EncodeToString(hash[:]) + } else { + // Hash the actual body content + bodyBytes := []byte(body.String()) + hash := sha256.Sum256(bodyBytes) + payloadHash = hex.EncodeToString(hash[:]) + } + + // Sign the request with the computed payload hash + signer := awsv4.NewSigner() + err = signer.SignHTTP(ctx, creds, localVarRequest, payloadHash, service, region, time.Now()) + if err != nil { + return nil, err + } + } + } + + 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 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 + } + err = file.Close() + if err != nil { + return err + } + + 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/openapi3/client/petstore/go/go-petstore-aws-signature/configuration.go b/samples/openapi3/client/petstore/go/go-petstore-aws-signature/configuration.go new file mode 100644 index 000000000000..f45b97a5716e --- /dev/null +++ b/samples/openapi3/client/petstore/go/go-petstore-aws-signature/configuration.go @@ -0,0 +1,231 @@ +/* +OpenAPI Petstore + +This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + +API version: 1.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package petstore + +import ( + "context" + "fmt" + "net/http" + "strings" +) + +// contextKeys are used to identify the type of value in the context. +// Since these are string, it is possible to get a short description of the +// context key for logging and debugging using key.String(). + +type contextKey string + +func (c contextKey) String() string { + return "auth " + string(c) +} + +var ( + // ContextOAuth2 takes an oauth2.TokenSource as authentication for the request. + ContextOAuth2 = contextKey("token") + + // ContextAWSv4 takes an Access Key and a Secret Key for signing AWS Signature v4 + ContextAWSv4 = contextKey("awsv4") + + // 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 +} + +// AWSv4 provides AWS Signature to a request passed via context using ContextAWSv4 +// https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html +type AWSv4 struct { + AccessKey string + SecretKey string + SessionToken string + Region string + Service string +} + +// ServerVariable stores the information about a server variable +type ServerVariable struct { + Description string + DefaultValue string + EnumValues []string +} + +// ServerConfiguration stores the information about a server +type ServerConfiguration struct { + URL string + Description string + Variables map[string]ServerVariable +} + +// ServerConfigurations stores multiple ServerConfiguration items +type ServerConfigurations []ServerConfiguration + +// Configuration stores the configuration of the API client +type Configuration struct { + Host string `json:"host,omitempty"` + Scheme string `json:"scheme,omitempty"` + DefaultHeader map[string]string `json:"defaultHeader,omitempty"` + UserAgent string `json:"userAgent,omitempty"` + Debug bool `json:"debug,omitempty"` + Servers ServerConfigurations + OperationServers map[string]ServerConfigurations + HTTPClient *http.Client +} + +// NewConfiguration returns a new Configuration object +func NewConfiguration() *Configuration { + cfg := &Configuration{ + DefaultHeader: make(map[string]string), + UserAgent: "OpenAPI-Generator/1.0.0/go", + Debug: false, + Servers: ServerConfigurations{ + { + URL: "http://petstore.swagger.io/v2", + Description: "No description provided", + }, + }, + OperationServers: map[string]ServerConfigurations{ + }, + } + return cfg +} + +// AddDefaultHeader adds a new HTTP header to the default header in the request +func (c *Configuration) AddDefaultHeader(key string, value string) { + c.DefaultHeader[key] = value +} + +// URL formats template on a index using given variables +func (sc ServerConfigurations) URL(index int, variables map[string]string) (string, error) { + if index < 0 || len(sc) <= index { + return "", fmt.Errorf("index %v out of range %v", index, len(sc)-1) + } + server := sc[index] + url := server.URL + + // go through variables and replace placeholders + for name, variable := range server.Variables { + if value, ok := variables[name]; ok { + found := bool(len(variable.EnumValues) == 0) + for _, enumValue := range variable.EnumValues { + if value == enumValue { + found = true + } + } + if !found { + return "", fmt.Errorf("the variable %s in the server URL has invalid value %v. Must be %v", name, value, variable.EnumValues) + } + url = strings.Replace(url, "{"+name+"}", value, -1) + } else { + url = strings.Replace(url, "{"+name+"}", variable.DefaultValue, -1) + } + } + return url, nil +} + +// ServerURL returns URL based on server settings +func (c *Configuration) ServerURL(index int, variables map[string]string) (string, error) { + return c.Servers.URL(index, variables) +} + +func getServerIndex(ctx context.Context) (int, error) { + si := ctx.Value(ContextServerIndex) + if si != nil { + if index, ok := si.(int); ok { + return index, nil + } + return 0, reportError("Invalid type %T should be int", si) + } + return 0, nil +} + +func getServerOperationIndex(ctx context.Context, endpoint string) (int, error) { + osi := ctx.Value(ContextOperationServerIndices) + if osi != nil { + if operationIndices, ok := osi.(map[string]int); !ok { + return 0, reportError("Invalid type %T should be map[string]int", osi) + } else { + index, ok := operationIndices[endpoint] + if ok { + return index, nil + } + } + } + return getServerIndex(ctx) +} + +func getServerVariables(ctx context.Context) (map[string]string, error) { + sv := ctx.Value(ContextServerVariables) + if sv != nil { + if variables, ok := sv.(map[string]string); ok { + return variables, nil + } + return nil, reportError("ctx value of ContextServerVariables has invalid type %T should be map[string]string", sv) + } + return nil, nil +} + +func getServerOperationVariables(ctx context.Context, endpoint string) (map[string]string, error) { + osv := ctx.Value(ContextOperationServerVariables) + if osv != nil { + if operationVariables, ok := osv.(map[string]map[string]string); !ok { + return nil, reportError("ctx value of ContextOperationServerVariables has invalid type %T should be map[string]map[string]string", osv) + } else { + variables, ok := operationVariables[endpoint] + if ok { + return variables, nil + } + } + } + return getServerVariables(ctx) +} + +// ServerURLWithContext returns a new server URL given an endpoint +func (c *Configuration) ServerURLWithContext(ctx context.Context, endpoint string) (string, error) { + sc, ok := c.OperationServers[endpoint] + if !ok { + sc = c.Servers + } + + if ctx == nil { + return sc.URL(0, nil) + } + + index, err := getServerOperationIndex(ctx, endpoint) + if err != nil { + return "", err + } + + variables, err := getServerOperationVariables(ctx, endpoint) + if err != nil { + return "", err + } + + return sc.URL(index, variables) +} diff --git a/samples/openapi3/client/petstore/go/go-petstore-aws-signature/docs/Category.md b/samples/openapi3/client/petstore/go/go-petstore-aws-signature/docs/Category.md new file mode 100644 index 000000000000..9bedc96c5340 --- /dev/null +++ b/samples/openapi3/client/petstore/go/go-petstore-aws-signature/docs/Category.md @@ -0,0 +1,82 @@ +# Category + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Id** | Pointer to **int64** | | [optional] +**Name** | Pointer to **string** | | [optional] + +## Methods + +### NewCategory + +`func NewCategory() *Category` + +NewCategory instantiates a new Category object +This constructor will assign default values to properties that have it defined, +and makes sure properties required by API are set, but the set of arguments +will change when the set of required properties is changed + +### NewCategoryWithDefaults + +`func NewCategoryWithDefaults() *Category` + +NewCategoryWithDefaults instantiates a new Category object +This constructor will only assign default values to properties that have it defined, +but it doesn't guarantee that properties required by API are set + +### GetId + +`func (o *Category) GetId() int64` + +GetId returns the Id field if non-nil, zero value otherwise. + +### GetIdOk + +`func (o *Category) GetIdOk() (*int64, bool)` + +GetIdOk returns a tuple with the Id field if it's non-nil, zero value otherwise +and a boolean to check if the value has been set. + +### SetId + +`func (o *Category) SetId(v int64)` + +SetId sets Id field to given value. + +### HasId + +`func (o *Category) HasId() bool` + +HasId returns a boolean if a field has been set. + +### GetName + +`func (o *Category) GetName() string` + +GetName returns the Name field if non-nil, zero value otherwise. + +### GetNameOk + +`func (o *Category) GetNameOk() (*string, bool)` + +GetNameOk returns a tuple with the Name field if it's non-nil, zero value otherwise +and a boolean to check if the value has been set. + +### SetName + +`func (o *Category) SetName(v string)` + +SetName sets Name field to given value. + +### HasName + +`func (o *Category) HasName() bool` + +HasName returns a boolean if a field has been set. + + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/go/go-petstore-aws-signature/docs/Pet.md b/samples/openapi3/client/petstore/go/go-petstore-aws-signature/docs/Pet.md new file mode 100644 index 000000000000..a6eae34657d3 --- /dev/null +++ b/samples/openapi3/client/petstore/go/go-petstore-aws-signature/docs/Pet.md @@ -0,0 +1,176 @@ +# Pet + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Id** | Pointer to **int64** | | [optional] +**Category** | Pointer to [**Category**](Category.md) | | [optional] +**Name** | **string** | | +**PhotoUrls** | **[]string** | | +**Tags** | Pointer to [**[]Tag**](Tag.md) | | [optional] +**Status** | Pointer to **string** | pet status in the store | [optional] + +## Methods + +### NewPet + +`func NewPet(name string, photoUrls []string, ) *Pet` + +NewPet instantiates a new Pet 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 + +### NewPetWithDefaults + +`func NewPetWithDefaults() *Pet` + +NewPetWithDefaults instantiates a new Pet object +This constructor will only assign default values to properties that have it defined, +but it doesn't guarantee that properties required by API are set + +### GetId + +`func (o *Pet) GetId() int64` + +GetId returns the Id field if non-nil, zero value otherwise. + +### GetIdOk + +`func (o *Pet) GetIdOk() (*int64, bool)` + +GetIdOk returns a tuple with the Id field if it's non-nil, zero value otherwise +and a boolean to check if the value has been set. + +### SetId + +`func (o *Pet) SetId(v int64)` + +SetId sets Id field to given value. + +### HasId + +`func (o *Pet) HasId() bool` + +HasId returns a boolean if a field has been set. + +### GetCategory + +`func (o *Pet) GetCategory() Category` + +GetCategory returns the Category field if non-nil, zero value otherwise. + +### GetCategoryOk + +`func (o *Pet) GetCategoryOk() (*Category, bool)` + +GetCategoryOk returns a tuple with the Category field if it's non-nil, zero value otherwise +and a boolean to check if the value has been set. + +### SetCategory + +`func (o *Pet) SetCategory(v Category)` + +SetCategory sets Category field to given value. + +### HasCategory + +`func (o *Pet) HasCategory() bool` + +HasCategory returns a boolean if a field has been set. + +### GetName + +`func (o *Pet) GetName() string` + +GetName returns the Name field if non-nil, zero value otherwise. + +### GetNameOk + +`func (o *Pet) GetNameOk() (*string, bool)` + +GetNameOk returns a tuple with the Name field if it's non-nil, zero value otherwise +and a boolean to check if the value has been set. + +### SetName + +`func (o *Pet) SetName(v string)` + +SetName sets Name field to given value. + + +### GetPhotoUrls + +`func (o *Pet) GetPhotoUrls() []string` + +GetPhotoUrls returns the PhotoUrls field if non-nil, zero value otherwise. + +### GetPhotoUrlsOk + +`func (o *Pet) GetPhotoUrlsOk() (*[]string, bool)` + +GetPhotoUrlsOk returns a tuple with the PhotoUrls field if it's non-nil, zero value otherwise +and a boolean to check if the value has been set. + +### SetPhotoUrls + +`func (o *Pet) SetPhotoUrls(v []string)` + +SetPhotoUrls sets PhotoUrls field to given value. + + +### GetTags + +`func (o *Pet) GetTags() []Tag` + +GetTags returns the Tags field if non-nil, zero value otherwise. + +### GetTagsOk + +`func (o *Pet) GetTagsOk() (*[]Tag, bool)` + +GetTagsOk returns a tuple with the Tags field if it's non-nil, zero value otherwise +and a boolean to check if the value has been set. + +### SetTags + +`func (o *Pet) SetTags(v []Tag)` + +SetTags sets Tags field to given value. + +### HasTags + +`func (o *Pet) HasTags() bool` + +HasTags returns a boolean if a field has been set. + +### GetStatus + +`func (o *Pet) GetStatus() string` + +GetStatus returns the Status field if non-nil, zero value otherwise. + +### GetStatusOk + +`func (o *Pet) 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 *Pet) SetStatus(v string)` + +SetStatus sets Status field to given value. + +### HasStatus + +`func (o *Pet) 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/openapi3/client/petstore/go/go-petstore-aws-signature/docs/PetAPI.md b/samples/openapi3/client/petstore/go/go-petstore-aws-signature/docs/PetAPI.md new file mode 100644 index 000000000000..0881d5fe198f --- /dev/null +++ b/samples/openapi3/client/petstore/go/go-petstore-aws-signature/docs/PetAPI.md @@ -0,0 +1,75 @@ +# \PetAPI + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**AddPet**](PetAPI.md#AddPet) | **Post** /pet | Add a new pet to the store + + + +## AddPet + +> Pet AddPet(ctx).Pet(pet).Execute() + +Add a new pet to the store + + + +### Example + +```go +package main + +import ( + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" +) + +func main() { + pet := *openapiclient.NewPet("doggie", []string{"PhotoUrls_example"}) // Pet | Pet object that needs to be added to the store + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.PetAPI.AddPet(context.Background()).Pet(pet).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `PetAPI.AddPet``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `AddPet`: Pet + fmt.Fprintf(os.Stdout, "Response from `PetAPI.AddPet`: %v\n", resp) +} +``` + +### Path Parameters + + + +### Other Parameters + +Other parameters are passed through a pointer to a apiAddPetRequest struct via the builder pattern + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet** | [**Pet**](Pet.md) | Pet object that needs to be added to the store | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: application/json, application/xml +- **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) +[[Back to Model list]](../README.md#documentation-for-models) +[[Back to README]](../README.md) + diff --git a/samples/openapi3/client/petstore/go/go-petstore-aws-signature/docs/Tag.md b/samples/openapi3/client/petstore/go/go-petstore-aws-signature/docs/Tag.md new file mode 100644 index 000000000000..391be6b49009 --- /dev/null +++ b/samples/openapi3/client/petstore/go/go-petstore-aws-signature/docs/Tag.md @@ -0,0 +1,82 @@ +# Tag + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Id** | Pointer to **int64** | | [optional] +**Name** | Pointer to **string** | | [optional] + +## Methods + +### NewTag + +`func NewTag() *Tag` + +NewTag instantiates a new Tag 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 + +### NewTagWithDefaults + +`func NewTagWithDefaults() *Tag` + +NewTagWithDefaults instantiates a new Tag object +This constructor will only assign default values to properties that have it defined, +but it doesn't guarantee that properties required by API are set + +### GetId + +`func (o *Tag) GetId() int64` + +GetId returns the Id field if non-nil, zero value otherwise. + +### GetIdOk + +`func (o *Tag) GetIdOk() (*int64, bool)` + +GetIdOk returns a tuple with the Id field if it's non-nil, zero value otherwise +and a boolean to check if the value has been set. + +### SetId + +`func (o *Tag) SetId(v int64)` + +SetId sets Id field to given value. + +### HasId + +`func (o *Tag) HasId() bool` + +HasId returns a boolean if a field has been set. + +### GetName + +`func (o *Tag) GetName() string` + +GetName returns the Name field if non-nil, zero value otherwise. + +### GetNameOk + +`func (o *Tag) GetNameOk() (*string, bool)` + +GetNameOk returns a tuple with the Name field if it's non-nil, zero value otherwise +and a boolean to check if the value has been set. + +### SetName + +`func (o *Tag) SetName(v string)` + +SetName sets Name field to given value. + +### HasName + +`func (o *Tag) HasName() bool` + +HasName returns a boolean if a field has been set. + + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/go/go-petstore-aws-signature/git_push.sh b/samples/openapi3/client/petstore/go/go-petstore-aws-signature/git_push.sh new file mode 100644 index 000000000000..f53a75d4fabe --- /dev/null +++ b/samples/openapi3/client/petstore/go/go-petstore-aws-signature/git_push.sh @@ -0,0 +1,57 @@ +#!/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 [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$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 [ "$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 [ "$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 +git_remote=$(git remote) +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$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/openapi3/client/petstore/go/go-petstore-aws-signature/go.mod b/samples/openapi3/client/petstore/go/go-petstore-aws-signature/go.mod new file mode 100644 index 000000000000..f2e3c3060668 --- /dev/null +++ b/samples/openapi3/client/petstore/go/go-petstore-aws-signature/go.mod @@ -0,0 +1,9 @@ +module github.com/GIT_USER_ID/GIT_REPO_ID + +go 1.23 + +require ( + github.com/stretchr/testify v1.10.0 + golang.org/x/oauth2 v0.27.0 + github.com/aws/aws-sdk-go-v2 v1.37.0 +) diff --git a/samples/openapi3/client/petstore/go/go-petstore-aws-signature/go.sum b/samples/openapi3/client/petstore/go/go-petstore-aws-signature/go.sum new file mode 100644 index 000000000000..f1e4cb91bb8a --- /dev/null +++ b/samples/openapi3/client/petstore/go/go-petstore-aws-signature/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/oauth2 v0.27.0 h1:da9Vo7/tDv5RH/7nZDz1eMGS/q1Vv1N/7FCrBhI9I3M= +golang.org/x/oauth2 v0.27.0/go.mod h1:onh5ek6nERTohokkhCD/y2cV4Do3fxFHFuAejCkRWT8= +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= diff --git a/samples/openapi3/client/petstore/go/go-petstore-aws-signature/model_category.go b/samples/openapi3/client/petstore/go/go-petstore-aws-signature/model_category.go new file mode 100644 index 000000000000..74573760b1a1 --- /dev/null +++ b/samples/openapi3/client/petstore/go/go-petstore-aws-signature/model_category.go @@ -0,0 +1,192 @@ +/* +OpenAPI Petstore + +This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + +API version: 1.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package petstore + +import ( + "encoding/json" +) + +// checks if the Category type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &Category{} + +// Category A category for a pet +type Category struct { + Id *int64 `json:"id,omitempty"` + Name *string `json:"name,omitempty" validate:"regexp=^[a-zA-Z0-9]+[a-zA-Z0-9\\\\.\\\\-_]*[a-zA-Z0-9]+$"` + AdditionalProperties map[string]interface{} +} + +type _Category Category + +// NewCategory instantiates a new Category object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewCategory() *Category { + this := Category{} + return &this +} + +// NewCategoryWithDefaults instantiates a new Category object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewCategoryWithDefaults() *Category { + this := Category{} + return &this +} + +// GetId returns the Id field value if set, zero value otherwise. +func (o *Category) GetId() int64 { + if o == nil || IsNil(o.Id) { + var ret int64 + return ret + } + return *o.Id +} + +// GetIdOk returns a tuple with the Id field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Category) GetIdOk() (*int64, bool) { + if o == nil || IsNil(o.Id) { + return nil, false + } + return o.Id, true +} + +// HasId returns a boolean if a field has been set. +func (o *Category) HasId() bool { + if o != nil && !IsNil(o.Id) { + return true + } + + return false +} + +// SetId gets a reference to the given int64 and assigns it to the Id field. +func (o *Category) SetId(v int64) { + o.Id = &v +} + +// GetName returns the Name field value if set, zero value otherwise. +func (o *Category) GetName() string { + if o == nil || IsNil(o.Name) { + var ret string + return ret + } + return *o.Name +} + +// GetNameOk returns a tuple with the Name field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Category) GetNameOk() (*string, bool) { + if o == nil || IsNil(o.Name) { + return nil, false + } + return o.Name, true +} + +// HasName returns a boolean if a field has been set. +func (o *Category) HasName() bool { + if o != nil && !IsNil(o.Name) { + return true + } + + return false +} + +// SetName gets a reference to the given string and assigns it to the Name field. +func (o *Category) SetName(v string) { + o.Name = &v +} + +func (o Category) MarshalJSON() ([]byte, error) { + toSerialize,err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o Category) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Id) { + toSerialize["id"] = o.Id + } + if !IsNil(o.Name) { + toSerialize["name"] = o.Name + } + + for key, value := range o.AdditionalProperties { + toSerialize[key] = value + } + + return toSerialize, nil +} + +func (o *Category) UnmarshalJSON(data []byte) (err error) { + varCategory := _Category{} + + err = json.Unmarshal(data, &varCategory) + + if err != nil { + return err + } + + *o = Category(varCategory) + + additionalProperties := make(map[string]interface{}) + + if err = json.Unmarshal(data, &additionalProperties); err == nil { + delete(additionalProperties, "id") + delete(additionalProperties, "name") + o.AdditionalProperties = additionalProperties + } + + return err +} + +type NullableCategory struct { + value *Category + isSet bool +} + +func (v NullableCategory) Get() *Category { + return v.value +} + +func (v *NullableCategory) Set(val *Category) { + v.value = val + v.isSet = true +} + +func (v NullableCategory) IsSet() bool { + return v.isSet +} + +func (v *NullableCategory) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableCategory(val *Category) *NullableCategory { + return &NullableCategory{value: val, isSet: true} +} + +func (v NullableCategory) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableCategory) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + + diff --git a/samples/openapi3/client/petstore/go/go-petstore-aws-signature/model_pet.go b/samples/openapi3/client/petstore/go/go-petstore-aws-signature/model_pet.go new file mode 100644 index 000000000000..6497a1a1e44e --- /dev/null +++ b/samples/openapi3/client/petstore/go/go-petstore-aws-signature/model_pet.go @@ -0,0 +1,350 @@ +/* +OpenAPI Petstore + +This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + +API version: 1.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package petstore + +import ( + "encoding/json" + "fmt" +) + +// checks if the Pet type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &Pet{} + +// Pet A pet for sale in the pet store +type Pet struct { + Id *int64 `json:"id,omitempty"` + Category *Category `json:"category,omitempty"` + Name string `json:"name"` + PhotoUrls []string `json:"photoUrls"` + Tags []Tag `json:"tags,omitempty"` + // pet status in the store + // Deprecated + Status *string `json:"status,omitempty"` + AdditionalProperties map[string]interface{} +} + +type _Pet Pet + +// NewPet instantiates a new Pet 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 NewPet(name string, photoUrls []string) *Pet { + this := Pet{} + this.Name = name + this.PhotoUrls = photoUrls + return &this +} + +// NewPetWithDefaults instantiates a new Pet 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 NewPetWithDefaults() *Pet { + this := Pet{} + return &this +} + +// GetId returns the Id field value if set, zero value otherwise. +func (o *Pet) GetId() int64 { + if o == nil || IsNil(o.Id) { + var ret int64 + return ret + } + return *o.Id +} + +// GetIdOk returns a tuple with the Id field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Pet) GetIdOk() (*int64, bool) { + if o == nil || IsNil(o.Id) { + return nil, false + } + return o.Id, true +} + +// HasId returns a boolean if a field has been set. +func (o *Pet) HasId() bool { + if o != nil && !IsNil(o.Id) { + return true + } + + return false +} + +// SetId gets a reference to the given int64 and assigns it to the Id field. +func (o *Pet) SetId(v int64) { + o.Id = &v +} + +// GetCategory returns the Category field value if set, zero value otherwise. +func (o *Pet) GetCategory() Category { + if o == nil || IsNil(o.Category) { + var ret Category + return ret + } + return *o.Category +} + +// GetCategoryOk returns a tuple with the Category field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Pet) GetCategoryOk() (*Category, bool) { + if o == nil || IsNil(o.Category) { + return nil, false + } + return o.Category, true +} + +// HasCategory returns a boolean if a field has been set. +func (o *Pet) HasCategory() bool { + if o != nil && !IsNil(o.Category) { + return true + } + + return false +} + +// SetCategory gets a reference to the given Category and assigns it to the Category field. +func (o *Pet) SetCategory(v Category) { + o.Category = &v +} + +// GetName returns the Name field value +func (o *Pet) GetName() string { + if o == nil { + var ret string + return ret + } + + return o.Name +} + +// GetNameOk returns a tuple with the Name field value +// and a boolean to check if the value has been set. +func (o *Pet) GetNameOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Name, true +} + +// SetName sets field value +func (o *Pet) SetName(v string) { + o.Name = v +} + +// GetPhotoUrls returns the PhotoUrls field value +func (o *Pet) GetPhotoUrls() []string { + if o == nil { + var ret []string + return ret + } + + return o.PhotoUrls +} + +// GetPhotoUrlsOk returns a tuple with the PhotoUrls field value +// and a boolean to check if the value has been set. +func (o *Pet) GetPhotoUrlsOk() ([]string, bool) { + if o == nil { + return nil, false + } + return o.PhotoUrls, true +} + +// SetPhotoUrls sets field value +func (o *Pet) SetPhotoUrls(v []string) { + o.PhotoUrls = v +} + +// GetTags returns the Tags field value if set, zero value otherwise. +func (o *Pet) GetTags() []Tag { + if o == nil || IsNil(o.Tags) { + var ret []Tag + return ret + } + return o.Tags +} + +// GetTagsOk returns a tuple with the Tags field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Pet) GetTagsOk() ([]Tag, bool) { + if o == nil || IsNil(o.Tags) { + return nil, false + } + return o.Tags, true +} + +// HasTags returns a boolean if a field has been set. +func (o *Pet) HasTags() bool { + if o != nil && !IsNil(o.Tags) { + return true + } + + return false +} + +// SetTags gets a reference to the given []Tag and assigns it to the Tags field. +func (o *Pet) SetTags(v []Tag) { + o.Tags = v +} + +// GetStatus returns the Status field value if set, zero value otherwise. +// Deprecated +func (o *Pet) 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. +// Deprecated +func (o *Pet) 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 *Pet) 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. +// Deprecated +func (o *Pet) SetStatus(v string) { + o.Status = &v +} + +func (o Pet) MarshalJSON() ([]byte, error) { + toSerialize,err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o Pet) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Id) { + toSerialize["id"] = o.Id + } + if !IsNil(o.Category) { + toSerialize["category"] = o.Category + } + toSerialize["name"] = o.Name + toSerialize["photoUrls"] = o.PhotoUrls + if !IsNil(o.Tags) { + toSerialize["tags"] = o.Tags + } + if !IsNil(o.Status) { + toSerialize["status"] = o.Status + } + + for key, value := range o.AdditionalProperties { + toSerialize[key] = value + } + + return toSerialize, nil +} + +func (o *Pet) UnmarshalJSON(data []byte) (err error) { + // 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{ + "name", + "photoUrls", + } + + allProperties := make(map[string]interface{}) + + err = json.Unmarshal(data, &allProperties) + + if err != nil { + return err; + } + + for _, requiredProperty := range(requiredProperties) { + if _, exists := allProperties[requiredProperty]; !exists { + return fmt.Errorf("no value given for required property %v", requiredProperty) + } + } + + varPet := _Pet{} + + err = json.Unmarshal(data, &varPet) + + if err != nil { + return err + } + + *o = Pet(varPet) + + additionalProperties := make(map[string]interface{}) + + if err = json.Unmarshal(data, &additionalProperties); err == nil { + delete(additionalProperties, "id") + delete(additionalProperties, "category") + delete(additionalProperties, "name") + delete(additionalProperties, "photoUrls") + delete(additionalProperties, "tags") + delete(additionalProperties, "status") + o.AdditionalProperties = additionalProperties + } + + return err +} + +type NullablePet struct { + value *Pet + isSet bool +} + +func (v NullablePet) Get() *Pet { + return v.value +} + +func (v *NullablePet) Set(val *Pet) { + v.value = val + v.isSet = true +} + +func (v NullablePet) IsSet() bool { + return v.isSet +} + +func (v *NullablePet) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullablePet(val *Pet) *NullablePet { + return &NullablePet{value: val, isSet: true} +} + +func (v NullablePet) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullablePet) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + + diff --git a/samples/openapi3/client/petstore/go/go-petstore-aws-signature/model_tag.go b/samples/openapi3/client/petstore/go/go-petstore-aws-signature/model_tag.go new file mode 100644 index 000000000000..431aff683905 --- /dev/null +++ b/samples/openapi3/client/petstore/go/go-petstore-aws-signature/model_tag.go @@ -0,0 +1,192 @@ +/* +OpenAPI Petstore + +This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + +API version: 1.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package petstore + +import ( + "encoding/json" +) + +// checks if the Tag type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &Tag{} + +// Tag A tag for a pet +type Tag struct { + Id *int64 `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + AdditionalProperties map[string]interface{} +} + +type _Tag Tag + +// NewTag instantiates a new Tag 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 NewTag() *Tag { + this := Tag{} + return &this +} + +// NewTagWithDefaults instantiates a new Tag 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 NewTagWithDefaults() *Tag { + this := Tag{} + return &this +} + +// GetId returns the Id field value if set, zero value otherwise. +func (o *Tag) GetId() int64 { + if o == nil || IsNil(o.Id) { + var ret int64 + return ret + } + return *o.Id +} + +// GetIdOk returns a tuple with the Id field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Tag) GetIdOk() (*int64, bool) { + if o == nil || IsNil(o.Id) { + return nil, false + } + return o.Id, true +} + +// HasId returns a boolean if a field has been set. +func (o *Tag) HasId() bool { + if o != nil && !IsNil(o.Id) { + return true + } + + return false +} + +// SetId gets a reference to the given int64 and assigns it to the Id field. +func (o *Tag) SetId(v int64) { + o.Id = &v +} + +// GetName returns the Name field value if set, zero value otherwise. +func (o *Tag) GetName() string { + if o == nil || IsNil(o.Name) { + var ret string + return ret + } + return *o.Name +} + +// GetNameOk returns a tuple with the Name field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Tag) GetNameOk() (*string, bool) { + if o == nil || IsNil(o.Name) { + return nil, false + } + return o.Name, true +} + +// HasName returns a boolean if a field has been set. +func (o *Tag) HasName() bool { + if o != nil && !IsNil(o.Name) { + return true + } + + return false +} + +// SetName gets a reference to the given string and assigns it to the Name field. +func (o *Tag) SetName(v string) { + o.Name = &v +} + +func (o Tag) MarshalJSON() ([]byte, error) { + toSerialize,err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o Tag) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Id) { + toSerialize["id"] = o.Id + } + if !IsNil(o.Name) { + toSerialize["name"] = o.Name + } + + for key, value := range o.AdditionalProperties { + toSerialize[key] = value + } + + return toSerialize, nil +} + +func (o *Tag) UnmarshalJSON(data []byte) (err error) { + varTag := _Tag{} + + err = json.Unmarshal(data, &varTag) + + if err != nil { + return err + } + + *o = Tag(varTag) + + additionalProperties := make(map[string]interface{}) + + if err = json.Unmarshal(data, &additionalProperties); err == nil { + delete(additionalProperties, "id") + delete(additionalProperties, "name") + o.AdditionalProperties = additionalProperties + } + + return err +} + +type NullableTag struct { + value *Tag + isSet bool +} + +func (v NullableTag) Get() *Tag { + return v.value +} + +func (v *NullableTag) Set(val *Tag) { + v.value = val + v.isSet = true +} + +func (v NullableTag) IsSet() bool { + return v.isSet +} + +func (v *NullableTag) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableTag(val *Tag) *NullableTag { + return &NullableTag{value: val, isSet: true} +} + +func (v NullableTag) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableTag) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + + diff --git a/samples/openapi3/client/petstore/go/go-petstore-aws-signature/response.go b/samples/openapi3/client/petstore/go/go-petstore-aws-signature/response.go new file mode 100644 index 000000000000..69c0239d6592 --- /dev/null +++ b/samples/openapi3/client/petstore/go/go-petstore-aws-signature/response.go @@ -0,0 +1,47 @@ +/* +OpenAPI Petstore + +This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + +API version: 1.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package petstore + +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/openapi3/client/petstore/go/go-petstore-aws-signature/test/api_pet_test.go b/samples/openapi3/client/petstore/go/go-petstore-aws-signature/test/api_pet_test.go new file mode 100644 index 000000000000..b27e25dc0bb0 --- /dev/null +++ b/samples/openapi3/client/petstore/go/go-petstore-aws-signature/test/api_pet_test.go @@ -0,0 +1,37 @@ +/* +OpenAPI Petstore + +Testing PetAPIService + +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); + +package petstore + +import ( + "context" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "testing" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" +) + +func Test_petstore_PetAPIService(t *testing.T) { + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + + t.Run("Test PetAPIService AddPet", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.PetAPI.AddPet(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + +} diff --git a/samples/openapi3/client/petstore/go/go-petstore-aws-signature/utils.go b/samples/openapi3/client/petstore/go/go-petstore-aws-signature/utils.go new file mode 100644 index 000000000000..beea36a80819 --- /dev/null +++ b/samples/openapi3/client/petstore/go/go-petstore-aws-signature/utils.go @@ -0,0 +1,361 @@ +/* +OpenAPI Petstore + +This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + +API version: 1.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package petstore + +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 diff --git a/samples/server/petstore/rust-server-deprecated/output/openapi-v3/Cargo.toml b/samples/server/petstore/rust-server-deprecated/output/openapi-v3/Cargo.toml index 4f8d249eb265..b7f4c30067dd 100644 --- a/samples/server/petstore/rust-server-deprecated/output/openapi-v3/Cargo.toml +++ b/samples/server/petstore/rust-server-deprecated/output/openapi-v3/Cargo.toml @@ -47,7 +47,8 @@ validator = { version = "0.16", features = ["derive"] } # Crates included if required by the API definition # TODO: this should be updated to point at the official crate once # https://github.com/RReverser/serde-xml-rs/pull/45 is accepted upstream -serde-xml-rs = {git = "https://github.com/Metaswitch/serde-xml-rs" , branch = "master"} +#serde-xml-rs = {git = "https://github.com/Metaswitch/serde-xml-rs" , branch = "master"} +serde-xml-rs = "0.8" uuid = {version = "1.3.1", features = ["serde", "v4"]} # Common between server and client features diff --git a/samples/server/petstore/rust-server-deprecated/output/openapi-v3/src/models.rs b/samples/server/petstore/rust-server-deprecated/output/openapi-v3/src/models.rs index d93d890a243a..84f8141a3cbc 100644 --- a/samples/server/petstore/rust-server-deprecated/output/openapi-v3/src/models.rs +++ b/samples/server/petstore/rust-server-deprecated/output/openapi-v3/src/models.rs @@ -464,13 +464,19 @@ impl AdditionalPropertiesWithNullable { // Utility function for wrapping list elements when serializing xml #[allow(non_snake_case)] -fn wrap_in_snake_another_xml_inner(item: &Vec, serializer: S) -> std::result::Result +fn wrap_in_snake_another_xml_inner(items: &Vec, serializer: S) -> std::result::Result where S: serde::ser::Serializer, { - serde_xml_rs::wrap_primitives(item, serializer, "snake_another_xml_inner") -} + use serde::ser::SerializeMap; + let mut map = serializer.serialize_map(None)?; + for ref item in items { + map.serialize_key("snake_another_xml_inner")?; + map.serialize_value(item)?; + } + map.end() +} #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] pub struct AnotherXmlArray( @@ -953,10 +959,10 @@ impl AnotherXmlObject { /// Will panic if serialisation fails. #[allow(dead_code)] pub(crate) fn as_xml(&self) -> String { - let mut namespaces = std::collections::BTreeMap::new(); // An empty string is used to indicate a global namespace in xmltree. - namespaces.insert("".to_string(), Self::NAMESPACE.to_string()); - serde_xml_rs::to_string_with_namespaces(&self, namespaces).expect("impossible to fail to serialize") + let config = serde_xml_rs::SerdeXml::new() + .namespace("", Self::NAMESPACE); + config.to_string(&self).expect("impossible to fail to serialize") } } @@ -1854,10 +1860,10 @@ impl DuplicateXmlObject { /// Will panic if serialisation fails. #[allow(dead_code)] pub(crate) fn as_xml(&self) -> String { - let mut namespaces = std::collections::BTreeMap::new(); // An empty string is used to indicate a global namespace in xmltree. - namespaces.insert("".to_string(), Self::NAMESPACE.to_string()); - serde_xml_rs::to_string_with_namespaces(&self, namespaces).expect("impossible to fail to serialize") + let config = serde_xml_rs::SerdeXml::new() + .namespace("", Self::NAMESPACE); + config.to_string(&self).expect("impossible to fail to serialize") } } @@ -5191,13 +5197,19 @@ impl UuidObject { // Utility function for wrapping list elements when serializing xml #[allow(non_snake_case)] -fn wrap_in_camelXmlInner(item: &Vec, serializer: S) -> std::result::Result +fn wrap_in_camelXmlInner(items: &Vec, serializer: S) -> std::result::Result where S: serde::ser::Serializer, { - serde_xml_rs::wrap_primitives(item, serializer, "camelXmlInner") -} + use serde::ser::SerializeMap; + let mut map = serializer.serialize_map(None)?; + for ref item in items { + map.serialize_key("camelXmlInner")?; + map.serialize_value(item)?; + } + map.end() +} #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] pub struct XmlArray( @@ -5695,9 +5707,9 @@ impl XmlObject { /// Will panic if serialisation fails. #[allow(dead_code)] pub(crate) fn as_xml(&self) -> String { - let mut namespaces = std::collections::BTreeMap::new(); // An empty string is used to indicate a global namespace in xmltree. - namespaces.insert("".to_string(), Self::NAMESPACE.to_string()); - serde_xml_rs::to_string_with_namespaces(&self, namespaces).expect("impossible to fail to serialize") + let config = serde_xml_rs::SerdeXml::new() + .namespace("", Self::NAMESPACE); + config.to_string(&self).expect("impossible to fail to serialize") } } diff --git a/samples/server/petstore/rust-server-deprecated/output/openapi-v3/src/server/mod.rs b/samples/server/petstore/rust-server-deprecated/output/openapi-v3/src/server/mod.rs index b61d9c1c07de..db2d5290a1bc 100644 --- a/samples/server/petstore/rust-server-deprecated/output/openapi-v3/src/server/mod.rs +++ b/samples/server/petstore/rust-server-deprecated/output/openapi-v3/src/server/mod.rs @@ -1652,11 +1652,10 @@ impl hyper::service::Service<(Request, C)> for Service where HeaderValue::from_str("text/xml") .expect("Unable to create Content-Type header for text/xml")); // XML Body - let mut namespaces = std::collections::BTreeMap::new(); - // An empty string is used to indicate a global namespace in xmltree. - namespaces.insert("".to_string(), models::AnotherXmlObject::NAMESPACE.to_string()); - let body = serde_xml_rs::to_string_with_namespaces(&body, namespaces).expect("impossible to fail to serialize"); + let config = serde_xml_rs::SerdeXml::new() + .namespace("", models::AnotherXmlObject::NAMESPACE); + let body = config.to_string(&body).expect("impossible to fail to serialize"); *response.body_mut() = Body::from(body); }, XmlOtherPostResponse::BadRequest diff --git a/samples/server/petstore/rust-server-deprecated/output/petstore-with-fake-endpoints-models-for-testing/Cargo.toml b/samples/server/petstore/rust-server-deprecated/output/petstore-with-fake-endpoints-models-for-testing/Cargo.toml index 0c809c91fdd6..8e7a328ea20c 100644 --- a/samples/server/petstore/rust-server-deprecated/output/petstore-with-fake-endpoints-models-for-testing/Cargo.toml +++ b/samples/server/petstore/rust-server-deprecated/output/petstore-with-fake-endpoints-models-for-testing/Cargo.toml @@ -50,7 +50,8 @@ validator = { version = "0.16", features = ["derive"] } # Crates included if required by the API definition # TODO: this should be updated to point at the official crate once # https://github.com/RReverser/serde-xml-rs/pull/45 is accepted upstream -serde-xml-rs = {git = "https://github.com/Metaswitch/serde-xml-rs" , branch = "master"} +#serde-xml-rs = {git = "https://github.com/Metaswitch/serde-xml-rs" , branch = "master"} +serde-xml-rs = "0.8" mime_0_2 = { package = "mime", version = "0.2.6", optional = true } multipart = { version = "0.16", default-features = false, optional = true } uuid = {version = "1.3.1", features = ["serde", "v4"]} diff --git a/samples/server/petstore/rust-server/output/multipart-v3/Cargo.toml b/samples/server/petstore/rust-server/output/multipart-v3/Cargo.toml index 67914ca651ff..2a5c4ff1c283 100644 --- a/samples/server/petstore/rust-server/output/multipart-v3/Cargo.toml +++ b/samples/server/petstore/rust-server/output/multipart-v3/Cargo.toml @@ -47,6 +47,7 @@ serde_json = "1.0" validator = { version = "0.20", features = ["derive"] } # Crates included if required by the API definition + multipart = { version = "0.18", default-features = false, optional = true } # Common between server and client features diff --git a/samples/server/petstore/rust-server/output/no-example-v3/Cargo.toml b/samples/server/petstore/rust-server/output/no-example-v3/Cargo.toml index 1e4463cc6e4c..53f6c71399e1 100644 --- a/samples/server/petstore/rust-server/output/no-example-v3/Cargo.toml +++ b/samples/server/petstore/rust-server/output/no-example-v3/Cargo.toml @@ -44,6 +44,7 @@ validator = { version = "0.20", features = ["derive"] } # Crates included if required by the API definition + # Common between server and client features bytes = "1.10.1" http-body-util = "0.1.3" diff --git a/samples/server/petstore/rust-server/output/openapi-v3/Cargo.toml b/samples/server/petstore/rust-server/output/openapi-v3/Cargo.toml index 931919cbd406..6f8315c692eb 100644 --- a/samples/server/petstore/rust-server/output/openapi-v3/Cargo.toml +++ b/samples/server/petstore/rust-server/output/openapi-v3/Cargo.toml @@ -48,7 +48,8 @@ validator = { version = "0.20", features = ["derive"] } # Crates included if required by the API definition # TODO: this should be updated to point at the official crate once # https://github.com/RReverser/serde-xml-rs/pull/45 is accepted upstream -serde-xml-rs = {git = "https://github.com/Metaswitch/serde-xml-rs" , branch = "master"} +#serde-xml-rs = {git = "https://github.com/Metaswitch/serde-xml-rs" , branch = "master"} +serde-xml-rs = "0.8" uuid = { version = "1.17.0", features = ["serde", "v4"]} # Common between server and client features diff --git a/samples/server/petstore/rust-server/output/openapi-v3/src/models.rs b/samples/server/petstore/rust-server/output/openapi-v3/src/models.rs index de464d40b9c6..c24dfb69f4c5 100644 --- a/samples/server/petstore/rust-server/output/openapi-v3/src/models.rs +++ b/samples/server/petstore/rust-server/output/openapi-v3/src/models.rs @@ -463,11 +463,18 @@ impl AdditionalPropertiesWithNullable { // Utility function for wrapping list elements when serializing xml #[allow(non_snake_case)] -fn wrap_in_snake_another_xml_inner(item: &Vec, serializer: S) -> std::result::Result +fn wrap_in_snake_another_xml_inner(items: &Vec, serializer: S) -> std::result::Result where S: serde::ser::Serializer, { - serde_xml_rs::wrap_primitives(item, serializer, "snake_another_xml_inner") + use serde::ser::SerializeMap; + + let mut map = serializer.serialize_map(None)?; + for ref item in items { + map.serialize_key("snake_another_xml_inner")?; + map.serialize_value(item)?; + } + map.end() } #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] @@ -952,10 +959,10 @@ impl AnotherXmlObject { /// Will panic if serialisation fails. #[allow(dead_code)] pub(crate) fn as_xml(&self) -> String { - let mut namespaces = std::collections::BTreeMap::new(); // An empty string is used to indicate a global namespace in xmltree. - namespaces.insert("".to_string(), Self::NAMESPACE.to_string()); - serde_xml_rs::to_string_with_namespaces(&self, namespaces).expect("impossible to fail to serialize") + let config = serde_xml_rs::SerdeXml::new() + .namespace("", Self::NAMESPACE); + config.to_string(&self).expect("impossible to fail to serialize") } } @@ -1853,10 +1860,10 @@ impl DuplicateXmlObject { /// Will panic if serialisation fails. #[allow(dead_code)] pub(crate) fn as_xml(&self) -> String { - let mut namespaces = std::collections::BTreeMap::new(); // An empty string is used to indicate a global namespace in xmltree. - namespaces.insert("".to_string(), Self::NAMESPACE.to_string()); - serde_xml_rs::to_string_with_namespaces(&self, namespaces).expect("impossible to fail to serialize") + let config = serde_xml_rs::SerdeXml::new() + .namespace("", Self::NAMESPACE); + config.to_string(&self).expect("impossible to fail to serialize") } } @@ -5190,11 +5197,18 @@ impl UuidObject { // Utility function for wrapping list elements when serializing xml #[allow(non_snake_case)] -fn wrap_in_camelXmlInner(item: &Vec, serializer: S) -> std::result::Result +fn wrap_in_camelXmlInner(items: &Vec, serializer: S) -> std::result::Result where S: serde::ser::Serializer, { - serde_xml_rs::wrap_primitives(item, serializer, "camelXmlInner") + use serde::ser::SerializeMap; + + let mut map = serializer.serialize_map(None)?; + for ref item in items { + map.serialize_key("camelXmlInner")?; + map.serialize_value(item)?; + } + map.end() } #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] @@ -5694,9 +5708,9 @@ impl XmlObject { /// Will panic if serialisation fails. #[allow(dead_code)] pub(crate) fn as_xml(&self) -> String { - let mut namespaces = std::collections::BTreeMap::new(); // An empty string is used to indicate a global namespace in xmltree. - namespaces.insert("".to_string(), Self::NAMESPACE.to_string()); - serde_xml_rs::to_string_with_namespaces(&self, namespaces).expect("impossible to fail to serialize") + let config = serde_xml_rs::SerdeXml::new() + .namespace("", Self::NAMESPACE); + config.to_string(&self).expect("impossible to fail to serialize") } } diff --git a/samples/server/petstore/rust-server/output/openapi-v3/src/server/mod.rs b/samples/server/petstore/rust-server/output/openapi-v3/src/server/mod.rs index 5fc291aad0ba..ac28b04a475a 100644 --- a/samples/server/petstore/rust-server/output/openapi-v3/src/server/mod.rs +++ b/samples/server/petstore/rust-server/output/openapi-v3/src/server/mod.rs @@ -1748,11 +1748,10 @@ impl hyper::service::Service<(Request, C)> for Service