From 2cd498a3bc869245f2b4c7ea36adf4199f840d1b Mon Sep 17 00:00:00 2001 From: Marcin Romaszewicz Date: Thu, 26 Feb 2026 18:34:36 -0800 Subject: [PATCH 1/3] chore: refactor all tests by category Replace the organically-grown test directory structure (issue-numbered directories, flat parameter/component tests) with a feature-based taxonomy that makes coverage visible at a glance. New structure: components/{primitives,objects,nullable,recursive} aggregates/{allof,anyof,oneof} parameters/{path/{simple,label,matrix},query/{form,deep_object}, header/simple,cookie/form,content,precedence,encoding} externalref/ (multi-package external $ref qualification) Each directory contains a minimal OpenAPI spec exercising one feature, a config.yaml, a doc.go with go:generate, committed generated code, and round-trip tests that instantiate types and verify JSON marshaling. Key changes: - Absorb issue-specific directories into feature categories - Delete old flat test directories (server/, strict-server/, client/, schemas/, cookies/, compatibility/, filter/, outputoptions/, etc.) - Add comprehensive parameter permutation coverage across all location x style x explode x value-type combinations - Fold issue-2113 (external ref in responses) into externalref/ - Add tools.go to keep oapi-codegen/v2 in go.mod for go:generate (previously kept alive implicitly by old test imports) Co-Authored-By: Claude Opus 4.6 --- .../allof/allof.gen.go} | 26 +- internal/test/aggregates/allof/allof_test.go | 144 + .../allof/config.yaml} | 4 +- .../{any_of/param => aggregates/allof}/doc.go | 2 +- internal/test/aggregates/allof/spec.yaml | 211 + internal/test/aggregates/anyof/anyof.gen.go | 279 ++ internal/test/aggregates/anyof/anyof_test.go | 121 + .../anyof/config.yaml} | 4 +- .../generate.go => aggregates/anyof/doc.go} | 2 +- internal/test/aggregates/anyof/spec.yaml | 100 + .../oneof/config.yaml} | 4 +- .../generate.go => aggregates/oneof/doc.go} | 2 +- internal/test/aggregates/oneof/oneof.gen.go | 833 ++++ internal/test/aggregates/oneof/oneof_test.go | 233 ++ internal/test/aggregates/oneof/spec.yaml | 174 + internal/test/all_of/config1.yaml | 10 - internal/test/all_of/config2.yaml | 8 - internal/test/all_of/doc.go | 4 - internal/test/all_of/openapi.yaml | 53 - internal/test/all_of/v1/openapi.gen.go | 127 - internal/test/all_of/v2/openapi.gen.go | 127 - .../test/any_of/codegen/inline/config.yaml | 6 - internal/test/any_of/codegen/inline/spec.yaml | 81 - .../any_of/codegen/ref_schema/config.yaml | 6 - .../any_of/codegen/ref_schema/generate.go | 3 - .../any_of/codegen/ref_schema/openapi.gen.go | 420 -- .../test/any_of/codegen/ref_schema/spec.yaml | 81 - internal/test/any_of/param/param.gen.go | 421 -- internal/test/any_of/param/param_test.go | 38 - internal/test/any_of/param/spec.yaml | 42 - internal/test/client/client.gen.go | 996 ----- internal/test/client/client.yaml | 102 - internal/test/client/client_test.go | 79 - internal/test/client/doc.go | 3 - .../api.yaml | 24 - .../cfg.yaml | 9 - .../generate.go | 3 - .../spec.gen.go | 97 - .../spec_test.go | 29 - internal/test/components/components.gen.go | 2549 ------------ internal/test/components/components.yaml | 585 --- internal/test/components/components_test.go | 361 -- internal/test/components/doc.go | 3 - .../nullable/config.yaml} | 4 +- .../packageA => components/nullable}/doc.go | 2 +- .../nullable/nullable.gen.go} | 41 +- .../test/components/nullable/nullable_test.go | 206 + .../nullable}/spec.yaml | 66 +- .../objects/config.yaml} | 5 +- .../issue-52 => components/objects}/doc.go | 2 +- .../test/components/objects/objects.gen.go | 368 ++ .../test/components/objects/objects_test.go | 176 + internal/test/components/objects/spec.yaml | 119 + .../test/components/primitives/config.yaml | 5 + internal/test/components/primitives/doc.go | 3 + .../components/primitives/primitives.gen.go | 132 + .../components/primitives/primitives_test.go | 167 + internal/test/components/primitives/spec.yaml | 126 + .../recursive/config.yaml} | 5 +- .../petstore => components/recursive}/doc.go | 2 +- .../recursive/recursive.gen.go} | 23 +- .../components/recursive/recursive_test.go | 135 + internal/test/components/recursive/spec.yaml | 93 + internal/test/cookies/config.yaml | 6 - internal/test/cookies/cookies.gen.go | 215 - internal/test/cookies/generate.go | 3 - internal/test/cookies/spec.yaml | 24 - internal/test/extensions/x-order/config.yaml | 7 - internal/test/extensions/x-order/issue.gen.go | 27 - internal/test/extensions/x-order/spec.yaml | 34 - .../common/spec.yaml | 0 .../config.api.yaml | 4 +- .../config.common.yaml} | 4 +- internal/test/externalref/doc.go | 3 +- .../test/externalref/externalref.cfg.yaml | 12 - internal/test/externalref/externalref.gen.go | 130 - internal/test/externalref/externalref_test.go | 20 + .../gen/api/api.gen.go | 2 +- .../gen/common/common.gen.go | 0 internal/test/externalref/imports_test.go | 32 - internal/test/externalref/object_c.json | 5 - .../test/externalref/packageA/config.yaml | 10 - .../externalref/packageA/externalref.gen.go | 109 - internal/test/externalref/packageA/spec.yaml | 8 - .../test/externalref/packageB/config.yaml | 8 - .../externalref/packageB/externalref.gen.go | 100 - internal/test/externalref/packageB/spec.yaml | 6 - .../test/externalref/petstore/config.yaml | 10 - .../externalref/petstore/externalref.gen.go | 382 -- internal/test/externalref/petstore/spec.yaml | 1 - internal/test/externalref/spec.yaml | 36 +- internal/test/filter/doc.go | 4 - internal/test/filter/operations/server.gen.go | 74 - .../test/filter/operations/server_test.go | 26 - internal/test/filter/server.yaml | 48 - internal/test/filter/tags/server.gen.go | 74 - internal/test/filter/tags/server_test.go | 26 - internal/test/go.mod | 72 +- internal/test/go.sum | 186 +- .../test/issues/issue-1039/client-config.yaml | 5 - internal/test/issues/issue-1039/client.gen.go | 261 -- .../defaultbehaviour/defaultbehaviour_test.go | 54 - .../issue-1039/defaultbehaviour/types.gen.go | 49 - internal/test/issues/issue-1039/doc.go | 6 - internal/test/issues/issue-1039/issue_test.go | 197 - .../test/issues/issue-1039/server-config.yaml | 5 - internal/test/issues/issue-1039/server.gen.go | 170 - .../type-config-defaultbehaviour.yaml | 5 - internal/test/issues/issue-1087/api.gen.go | 452 --- .../test/issues/issue-1087/deps/deps.gen.go | 138 - internal/test/issues/issue-1087/deps/doc.go | 3 - .../test/issues/issue-1087/deps/my-deps.json | 153 - internal/test/issues/issue-1087/doc.go | 3 - .../test/issues/issue-1087/server.config.yaml | 11 - internal/test/issues/issue-1087/spec.yaml | 109 - .../issues/issue-1093/api/child/child.gen.go | 230 -- .../issue-1093/api/parent/parent.gen.go | 229 -- .../test/issues/issue-1093/child.api.yaml | 21 - .../test/issues/issue-1093/child.cfg.yaml | 11 - internal/test/issues/issue-1093/doc.go | 6 - internal/test/issues/issue-1093/issue_test.go | 38 - .../test/issues/issue-1093/parent.api.yaml | 32 - .../test/issues/issue-1093/parent.cfg.yaml | 10 - internal/test/issues/issue-1127/api.gen.go | 18 - internal/test/issues/issue-1127/doc.go | 3 - internal/test/issues/issue-1127/spec.yaml | 42 - internal/test/issues/issue-1168/api.gen.go | 162 - internal/test/issues/issue-1168/doc.go | 3 - internal/test/issues/issue-1168/spec.yaml | 95 - internal/test/issues/issue-1180/config.yaml | 8 - internal/test/issues/issue-1180/doc.go | 3 - internal/test/issues/issue-1180/issue.gen.go | 380 -- internal/test/issues/issue-1180/issue_test.go | 10 - internal/test/issues/issue-1182/pkg1.yaml | 16 - .../test/issues/issue-1182/pkg1/config.yaml | 11 - internal/test/issues/issue-1182/pkg1/doc.go | 3 - .../test/issues/issue-1182/pkg1/pkg1.gen.go | 428 -- internal/test/issues/issue-1182/pkg2.yaml | 12 - internal/test/issues/issue-1182/pkg2/doc.go | 3 - .../test/issues/issue-1182/pkg2/pkg2.gen.go | 275 -- internal/test/issues/issue-1189/config.yaml | 8 - internal/test/issues/issue-1189/doc.go | 3 - .../test/issues/issue-1189/issue1189.gen.go | 586 --- .../test/issues/issue-1189/issue1189.yaml | 36 - .../test/issues/issue-1208-1209/config.yaml | 9 - internal/test/issues/issue-1208-1209/doc.go | 3 - .../issue-1208-1209/issue-multi-json.gen.go | 516 --- .../issue-1208-1209/issue-multi-json.yaml | 35 - .../issue-1208-1209/issue-multi-json_test.go | 114 - internal/test/issues/issue-1212/pkg1.yaml | 8 - .../test/issues/issue-1212/pkg1/config.yaml | 11 - internal/test/issues/issue-1212/pkg1/doc.go | 3 - .../test/issues/issue-1212/pkg1/pkg1.gen.go | 441 --- internal/test/issues/issue-1212/pkg2.yaml | 21 - .../test/issues/issue-1212/pkg2/config.yaml | 11 - internal/test/issues/issue-1212/pkg2/doc.go | 3 - .../test/issues/issue-1212/pkg2/pkg2.gen.go | 280 -- internal/test/issues/issue-1219/config.yaml | 7 - internal/test/issues/issue-1219/doc.go | 3 - internal/test/issues/issue-1219/issue.yaml | 136 - internal/test/issues/issue-1219/issue_test.go | 85 - internal/test/issues/issue-1298/config.yaml | 8 - internal/test/issues/issue-1298/doc.go | 3 - .../test/issues/issue-1298/issue1298.gen.go | 404 -- .../test/issues/issue-1298/issue1298.yaml | 25 - .../test/issues/issue-1298/issue1298_test.go | 44 - internal/test/issues/issue-1378/bionicle.yaml | 43 - .../issue-1378/bionicle/bionicle.gen.go | 369 -- .../issues/issue-1378/bionicle/config.yaml | 10 - .../issues/issue-1378/bionicle/generate.go | 3 - internal/test/issues/issue-1378/common.yaml | 16 - .../issues/issue-1378/common/common.gen.go | 262 -- .../test/issues/issue-1378/common/config.yaml | 10 - .../test/issues/issue-1378/common/generate.go | 3 - .../test/issues/issue-1378/foo-service.yaml | 10 - .../issues/issue-1378/fooservice/config.yaml | 11 - .../issue-1378/fooservice/fooservice.gen.go | 368 -- .../issues/issue-1378/fooservice/generate.go | 3 - internal/test/issues/issue-1397/config.yaml | 8 - internal/test/issues/issue-1397/doc.go | 3 - .../test/issues/issue-1397/issue1397.gen.go | 452 --- internal/test/issues/issue-1397/spec.yaml | 52 - .../test/issues/issue-1529/strict-echo/doc.go | 3 - .../issue-1529/strict-echo/issue1529.gen.go | 471 --- .../issues/issue-1529/strict-echo/spec.yaml | 21 - .../issue-1529/strict-fiber/config.yaml | 9 - .../issues/issue-1529/strict-fiber/doc.go | 3 - .../issue-1529/strict-fiber/issue1529.gen.go | 465 --- .../issues/issue-1529/strict-fiber/spec.yaml | 21 - .../issues/issue-1529/strict-iris/config.yaml | 9 - .../test/issues/issue-1529/strict-iris/doc.go | 3 - .../issue-1529/strict-iris/issue1529.gen.go | 466 --- .../issues/issue-1529/strict-iris/spec.yaml | 21 - internal/test/issues/issue-1530/config.yaml | 4 - internal/test/issues/issue-1530/doc.go | 3 - .../test/issues/issue-1530/issue1530.gen.go | 126 - .../test/issues/issue-1530/issue1530.yaml | 57 - .../test/issues/issue-1530/issue1530_test.go | 51 - internal/test/issues/issue-1676/api.yaml | 17 - internal/test/issues/issue-1676/generate.go | 3 - internal/test/issues/issue-1676/ping.gen.go | 246 -- internal/test/issues/issue-2031/config.yaml | 4 - internal/test/issues/issue-2031/generate.go | 3 - .../test/issues/issue-2031/issue2031.gen.go | 83 - .../test/issues/issue-2031/issue2031_test.go | 18 - internal/test/issues/issue-2031/openapi.yaml | 27 - .../test/issues/issue-2031/prefer/config.yaml | 7 - .../test/issues/issue-2031/prefer/generate.go | 3 - .../issue-2031/prefer/issue2031_test.go | 63 - .../issues/issue-2031/prefer/openapi.yaml | 17 - .../test/issues/issue-2113/config.common.yaml | 7 - internal/test/issues/issue-2113/doc.go | 4 - internal/test/issues/issue-2113/issue_test.go | 22 - internal/test/issues/issue-2113/spec.yaml | 21 - internal/test/issues/issue-2185/config.yaml | 8 - internal/test/issues/issue-2185/generate.go | 3 - .../test/issues/issue-2185/issue2185.gen.go | 13 - .../test/issues/issue-2185/issue2185_test.go | 19 - internal/test/issues/issue-2185/spec.yaml | 15 - internal/test/issues/issue-2190/config.yaml | 9 - internal/test/issues/issue-2190/generate.go | 3 - .../test/issues/issue-2190/issue2190.gen.go | 486 --- .../test/issues/issue-2190/issue2190_test.go | 37 - internal/test/issues/issue-2190/spec.yaml | 30 - internal/test/issues/issue-2232/config.yaml | 5 - internal/test/issues/issue-2232/generate.go | 3 - .../test/issues/issue-2232/issue2232.gen.go | 260 -- .../test/issues/issue-2232/issue2232_test.go | 41 - internal/test/issues/issue-2232/spec.yaml | 46 - internal/test/issues/issue-312/doc.go | 3 - internal/test/issues/issue-312/issue_test.go | 127 - internal/test/issues/issue-52/issue.gen.go | 391 -- internal/test/issues/issue-52/issue_test.go | 31 - internal/test/issues/issue-52/spec.yaml | 37 - internal/test/issues/issue-579/gen.go | 3 - internal/test/issues/issue-579/issue.gen.go | 17 - internal/test/issues/issue-579/issue_test.go | 14 - internal/test/issues/issue-579/spec.yaml | 27 - internal/test/issues/issue-832/config.yaml | 6 - internal/test/issues/issue-832/generate.go | 3 - internal/test/issues/issue-832/issue.gen.go | 137 - internal/test/issues/issue-832/spec.yaml | 43 - internal/test/issues/issue-936/gen.go | 3 - .../test/issues/issue-936/server.config.yaml | 7 - internal/test/issues/issue-936/spec.yaml | 60 - .../issue-grab_import_names/config.yaml | 8 - .../issues/issue-grab_import_names/doc.go | 3 - .../issue-grab_import_names/issue_test.go | 28 - .../issues/issue-grab_import_names/spec.yaml | 30 - .../config.yaml | 8 - .../issue-head-digit-of-httpheader/doc.go | 3 - .../issue.gen.go | 11 - .../issue-head-digit-of-httpheader/spec.yaml | 16 - .../config.yaml | 8 - .../issue-head-digit-of-operation-id/doc.go | 3 - .../issue.gen.go | 4 - .../spec.yaml | 7 - .../issue-illegal_enum_names/config.yaml | 8 - .../issues/issue-illegal_enum_names/doc.go | 3 - .../issue-illegal_enum_names/issue.gen.go | 421 -- .../issue-illegal_enum_names/issue_test.go | 59 - .../issues/issue-illegal_enum_names/spec.yaml | 35 - .../config.base.yaml | 13 - .../config.ext.yaml | 11 - .../issues/issue-removed-external-ref/doc.go | 4 - .../gen/spec_base/.gitempty | 0 .../gen/spec_base/issue.gen.go | 333 -- .../gen/spec_ext/.gitempty | 0 .../gen/spec_ext/issue.gen.go | 195 - .../issue-removed-external-ref/spec-base.yaml | 41 - .../issue-removed-external-ref/spec-ext.yaml | 30 - internal/test/issues/issue1469/config.yaml | 5 - internal/test/issues/issue1469/doc.go | 3 - internal/test/issues/issue1469/main.gen.go | 53 - internal/test/issues/issue1469/main_test.go | 35 - internal/test/issues/issue1469/spec.yaml | 13 - internal/test/issues/issue1561/config.yaml | 8 - internal/test/issues/issue1561/generate.go | 3 - .../test/issues/issue1561/issue1561.gen.go | 21 - .../test/issues/issue1561/issue1561_test.go | 64 - internal/test/issues/issue1561/openapi.yaml | 49 - internal/test/issues/issue1767/config.yaml | 7 - internal/test/issues/issue1767/generate.go | 3 - .../test/issues/issue1767/issue1767.gen.go | 17 - internal/test/issues/issue1767/openapi.yaml | 20 - internal/test/issues/issue1825/config.yaml | 11 - internal/test/issues/issue1825/doc.go | 5 - .../test/issues/issue1825/issue1825.gen.go | 110 - internal/test/issues/issue1825/object_b.json | 5 - internal/test/issues/issue1825/overlay.yaml | 10 - .../test/issues/issue1825/overlay_test.go | 14 - .../issues/issue1825/packageA/config.yaml | 7 - .../test/issues/issue1825/packageA/doc.go | 3 - .../issue1825/packageA/externalref.gen.go | 100 - .../test/issues/issue1825/packageA/spec.yaml | 6 - internal/test/issues/issue1825/spec/spec.yaml | 11 - internal/test/issues/issue193/config.yaml | 6 - internal/test/issues/issue193/generate.go | 3 - internal/test/issues/issue193/issue.gen.go | 113 - internal/test/issues/issue193/spec.yaml | 26 - internal/test/issues/issue1957/config.yaml | 6 - internal/test/issues/issue1957/generate.go | 3 - .../test/issues/issue1957/issue1957.gen.go | 27 - .../test/issues/issue1957/issue1957_test.go | 54 - internal/test/issues/issue1957/openapi.yaml | 55 - internal/test/issues/issue240/api.yaml | 47 - internal/test/issues/issue240/cfg.yaml | 8 - internal/test/issues/issue240/client.gen.go | 355 -- internal/test/issues/issue240/generate.go | 3 - internal/test/issues/issue609/config.yaml | 7 - internal/test/issues/issue609/generate.go | 3 - internal/test/issues/issue609/issue609.gen.go | 9 - internal/test/issues/issue609/openapi.yaml | 11 - .../disabletypealiases/config.yaml | 9 - .../disabletypealiases/spec.yaml | 13 - .../disabletypealiases/types.gen.go | 13 - .../disabletypealiases/types_ext.go | 5 - .../outputoptions/name-normalizer/spec.yaml | 64 - .../config.yaml | 13 - .../generate.go | 3 - .../name_normalizer.gen.go | 590 --- .../name_normalizer_test.go | 24 - .../to-camel-case-with-digits/config.yaml | 11 - .../to-camel-case-with-digits/generate.go | 3 - .../name_normalizer.gen.go | 590 --- .../name_normalizer_test.go | 24 - .../config.yaml | 11 - .../generate.go | 3 - .../name_normalizer.gen.go | 590 --- .../name_normalizer_test.go | 24 - .../name-normalizer/to-camel-case/config.yaml | 11 - .../name-normalizer/to-camel-case/generate.go | 3 - .../to-camel-case/name_normalizer.gen.go | 590 --- .../to-camel-case/name_normalizer_test.go | 24 - .../name-normalizer/unset/config.yaml | 11 - .../name-normalizer/unset/generate.go | 3 - .../unset/name_normalizer.gen.go | 590 --- .../unset/name_normalizer_test.go | 24 - .../test/outputoptions/yaml-tags/config.yaml | 8 - .../test/outputoptions/yaml-tags/generate.go | 3 - .../test/outputoptions/yaml-tags/spec.yaml | 24 - .../test/outputoptions/yaml-tags/yamltags.go | 13 - internal/test/parameters/config.yaml | 8 - .../content}/config.yaml | 5 +- .../test/parameters/content/content.gen.go | 852 ++++ .../test/parameters/content/content_test.go | 202 + .../generate.go => parameters/content/doc.go} | 2 +- internal/test/parameters/content/spec.yaml | 100 + .../test/parameters/cookie/form/config.yaml | 7 + .../cookie/form/cookie_form.gen.go} | 344 +- .../cookie/form/cookie_form_test.go | 144 + internal/test/parameters/cookie/form/doc.go | 3 + .../test/parameters/cookie/form/spec.yaml | 74 + internal/test/parameters/doc.go | 3 - .../encoding}/config.yaml | 5 +- .../packageB => parameters/encoding}/doc.go | 2 +- .../encoding/encoding.gen.go} | 117 +- .../test/parameters/encoding/encoding_test.go | 108 + .../encoding}/spec.yaml | 41 +- .../test/parameters/header/simple/config.yaml | 7 + internal/test/parameters/header/simple/doc.go | 3 + .../header/simple/header_simple.gen.go | 459 +++ .../header/simple/header_simple_test.go | 156 + .../test/parameters/header/simple/spec.yaml | 74 + internal/test/parameters/parameters.gen.go | 3517 ----------------- internal/test/parameters/parameters.yaml | 533 --- internal/test/parameters/parameters_test.go | 733 ---- .../path/label}/config.yaml | 8 +- internal/test/parameters/path/label/doc.go | 3 + .../parameters/path/label/path_label.gen.go | 888 +++++ .../parameters/path/label/path_label_test.go | 211 + internal/test/parameters/path/label/spec.yaml | 113 + .../path/matrix}/config.yaml | 8 +- internal/test/parameters/path/matrix/doc.go | 3 + .../parameters/path/matrix/path_matrix.gen.go | 888 +++++ .../path/matrix/path_matrix_test.go | 202 + .../test/parameters/path/matrix/spec.yaml | 113 + .../path/simple/config.yaml} | 8 +- internal/test/parameters/path/simple/doc.go | 3 + .../parameters/path/simple/path_simple.gen.go | 888 +++++ .../path/simple/path_simple_test.go | 198 + .../test/parameters/path/simple/spec.yaml | 113 + .../precedence}/config.yaml | 6 +- internal/test/parameters/precedence/doc.go | 3 + .../precedence/precedence.gen.go} | 76 +- .../parameters/precedence/precedence_test.go | 15 + .../precedence/spec.yaml} | 20 +- .../query/deep_object}/config.yaml | 10 +- .../test/parameters/query/deep_object/doc.go | 3 + .../deep_object/query_deep_object.gen.go} | 166 +- .../deep_object/query_deep_object_test.go | 100 + .../parameters/query/deep_object/spec.yaml | 53 + .../test/parameters/query/form/config.yaml | 7 + internal/test/parameters/query/form/doc.go | 3 + .../parameters/query/form/query_form.gen.go | 451 +++ .../parameters/query/form/query_form_test.go | 143 + internal/test/parameters/query/form/spec.yaml | 80 + internal/test/schemas/config.yaml | 10 - internal/test/schemas/doc.go | 3 - internal/test/schemas/schemas.gen.go | 1699 -------- internal/test/schemas/schemas.yaml | 250 -- internal/test/server/config.yaml | 6 - internal/test/server/doc.go | 3 - internal/test/server/server.gen.go | 660 ---- internal/test/server/server_test.go | 136 - .../test/strict-server/chi/server.cfg.yaml | 7 - internal/test/strict-server/chi/server.gen.go | 1824 --------- internal/test/strict-server/chi/server.go | 152 - internal/test/strict-server/chi/types.gen.go | 69 - .../test/strict-server/client/client.cfg.yaml | 6 - .../test/strict-server/client/client.gen.go | 1986 ---------- internal/test/strict-server/client/client.go | 3 - .../test/strict-server/echo/server.cfg.yaml | 7 - .../test/strict-server/echo/server.gen.go | 1499 ------- internal/test/strict-server/echo/server.go | 152 - internal/test/strict-server/echo/types.gen.go | 69 - .../strict-server/fiber/fiber_strict_test.go | 229 -- .../test/strict-server/fiber/server.cfg.yaml | 7 - .../test/strict-server/fiber/server.gen.go | 1479 ------- internal/test/strict-server/fiber/server.go | 152 - .../test/strict-server/fiber/types.gen.go | 69 - .../test/strict-server/gin/server.cfg.yaml | 7 - internal/test/strict-server/gin/server.gen.go | 1622 -------- internal/test/strict-server/gin/server.go | 152 - .../test/strict-server/gin/types.cfg.yaml | 5 - internal/test/strict-server/gin/types.gen.go | 69 - .../strict-server/gorilla/server.cfg.yaml | 7 - .../test/strict-server/gorilla/server.gen.go | 1735 -------- internal/test/strict-server/gorilla/server.go | 128 - .../test/strict-server/gorilla/types.cfg.yaml | 5 - .../test/strict-server/gorilla/types.gen.go | 69 - .../test/strict-server/iris/server.cfg.yaml | 7 - .../test/strict-server/iris/server.gen.go | 1553 -------- internal/test/strict-server/iris/server.go | 151 - .../test/strict-server/iris/types.cfg.yaml | 5 - internal/test/strict-server/iris/types.gen.go | 69 - internal/test/strict-server/stdhttp/Makefile | 17 - internal/test/strict-server/stdhttp/go.mod | 42 - internal/test/strict-server/stdhttp/go.sum | 185 - .../strict-server/stdhttp/server.cfg.yaml | 7 - .../test/strict-server/stdhttp/server.gen.go | 1730 -------- internal/test/strict-server/stdhttp/server.go | 154 - .../strict-server/stdhttp/std_strict_test.go | 229 -- .../test/strict-server/stdhttp/tools/tools.go | 8 - .../test/strict-server/stdhttp/types.cfg.yaml | 5 - .../test/strict-server/stdhttp/types.gen.go | 69 - .../test/strict-server/strict-schema.yaml | 363 -- internal/test/strict-server/strict_test.go | 261 -- internal/test/test-schema.yaml | 369 -- internal/test/tools.go | 15 + 450 files changed, 10834 insertions(+), 50913 deletions(-) rename internal/test/{issues/issue-1219/issue.gen.go => aggregates/allof/allof.gen.go} (97%) create mode 100644 internal/test/aggregates/allof/allof_test.go rename internal/test/{strict-server/echo/types.cfg.yaml => aggregates/allof/config.yaml} (72%) rename internal/test/{any_of/param => aggregates/allof}/doc.go (88%) create mode 100644 internal/test/aggregates/allof/spec.yaml create mode 100644 internal/test/aggregates/anyof/anyof.gen.go create mode 100644 internal/test/aggregates/anyof/anyof_test.go rename internal/test/{strict-server/chi/types.cfg.yaml => aggregates/anyof/config.yaml} (72%) rename internal/test/{outputoptions/disabletypealiases/generate.go => aggregates/anyof/doc.go} (88%) create mode 100644 internal/test/aggregates/anyof/spec.yaml rename internal/test/{strict-server/fiber/types.cfg.yaml => aggregates/oneof/config.yaml} (72%) rename internal/test/{any_of/codegen/inline/generate.go => aggregates/oneof/doc.go} (88%) create mode 100644 internal/test/aggregates/oneof/oneof.gen.go create mode 100644 internal/test/aggregates/oneof/oneof_test.go create mode 100644 internal/test/aggregates/oneof/spec.yaml delete mode 100644 internal/test/all_of/config1.yaml delete mode 100644 internal/test/all_of/config2.yaml delete mode 100644 internal/test/all_of/doc.go delete mode 100644 internal/test/all_of/openapi.yaml delete mode 100644 internal/test/all_of/v1/openapi.gen.go delete mode 100644 internal/test/all_of/v2/openapi.gen.go delete mode 100644 internal/test/any_of/codegen/inline/config.yaml delete mode 100644 internal/test/any_of/codegen/inline/spec.yaml delete mode 100644 internal/test/any_of/codegen/ref_schema/config.yaml delete mode 100644 internal/test/any_of/codegen/ref_schema/generate.go delete mode 100644 internal/test/any_of/codegen/ref_schema/openapi.gen.go delete mode 100644 internal/test/any_of/codegen/ref_schema/spec.yaml delete mode 100644 internal/test/any_of/param/param.gen.go delete mode 100644 internal/test/any_of/param/param_test.go delete mode 100644 internal/test/any_of/param/spec.yaml delete mode 100644 internal/test/client/client.gen.go delete mode 100644 internal/test/client/client.yaml delete mode 100644 internal/test/client/client_test.go delete mode 100644 internal/test/client/doc.go delete mode 100644 internal/test/compatibility/preserve-original-operation-id-casing-in-embedded-spec/api.yaml delete mode 100644 internal/test/compatibility/preserve-original-operation-id-casing-in-embedded-spec/cfg.yaml delete mode 100644 internal/test/compatibility/preserve-original-operation-id-casing-in-embedded-spec/generate.go delete mode 100644 internal/test/compatibility/preserve-original-operation-id-casing-in-embedded-spec/spec.gen.go delete mode 100644 internal/test/compatibility/preserve-original-operation-id-casing-in-embedded-spec/spec_test.go delete mode 100644 internal/test/components/components.gen.go delete mode 100644 internal/test/components/components.yaml delete mode 100644 internal/test/components/components_test.go delete mode 100644 internal/test/components/doc.go rename internal/test/{issues/issue-1039/types-config.yaml => components/nullable/config.yaml} (76%) rename internal/test/{externalref/packageA => components/nullable}/doc.go (86%) rename internal/test/{issues/issue-1039/types.gen.go => components/nullable/nullable.gen.go} (87%) create mode 100644 internal/test/components/nullable/nullable_test.go rename internal/test/{issues/issue-1039 => components/nullable}/spec.yaml (53%) rename internal/test/{issues/issue-1127/server.config.yaml => components/objects/config.yaml} (70%) rename internal/test/{issues/issue-52 => components/objects}/doc.go (87%) create mode 100644 internal/test/components/objects/objects.gen.go create mode 100644 internal/test/components/objects/objects_test.go create mode 100644 internal/test/components/objects/spec.yaml create mode 100644 internal/test/components/primitives/config.yaml create mode 100644 internal/test/components/primitives/doc.go create mode 100644 internal/test/components/primitives/primitives.gen.go create mode 100644 internal/test/components/primitives/primitives_test.go create mode 100644 internal/test/components/primitives/spec.yaml rename internal/test/{issues/issue-1168/server.config.yaml => components/recursive/config.yaml} (68%) rename internal/test/{externalref/petstore => components/recursive}/doc.go (85%) rename internal/test/{issues/issue-936/api.gen.go => components/recursive/recursive.gen.go} (95%) create mode 100644 internal/test/components/recursive/recursive_test.go create mode 100644 internal/test/components/recursive/spec.yaml delete mode 100644 internal/test/cookies/config.yaml delete mode 100644 internal/test/cookies/cookies.gen.go delete mode 100644 internal/test/cookies/generate.go delete mode 100644 internal/test/cookies/spec.yaml delete mode 100644 internal/test/extensions/x-order/config.yaml delete mode 100644 internal/test/extensions/x-order/issue.gen.go delete mode 100644 internal/test/extensions/x-order/spec.yaml rename internal/test/{issues/issue-2113 => externalref}/common/spec.yaml (100%) rename internal/test/{issues/issue-2113 => externalref}/config.api.yaml (66%) rename internal/test/{components/config.yaml => externalref/config.common.yaml} (72%) delete mode 100644 internal/test/externalref/externalref.cfg.yaml delete mode 100644 internal/test/externalref/externalref.gen.go create mode 100644 internal/test/externalref/externalref_test.go rename internal/test/{issues/issue-2113 => externalref}/gen/api/api.gen.go (99%) rename internal/test/{issues/issue-2113 => externalref}/gen/common/common.gen.go (100%) delete mode 100644 internal/test/externalref/imports_test.go delete mode 100644 internal/test/externalref/object_c.json delete mode 100644 internal/test/externalref/packageA/config.yaml delete mode 100644 internal/test/externalref/packageA/externalref.gen.go delete mode 100644 internal/test/externalref/packageA/spec.yaml delete mode 100644 internal/test/externalref/packageB/config.yaml delete mode 100644 internal/test/externalref/packageB/externalref.gen.go delete mode 100644 internal/test/externalref/packageB/spec.yaml delete mode 100644 internal/test/externalref/petstore/config.yaml delete mode 100644 internal/test/externalref/petstore/externalref.gen.go delete mode 100644 internal/test/externalref/petstore/spec.yaml delete mode 100644 internal/test/filter/doc.go delete mode 100644 internal/test/filter/operations/server.gen.go delete mode 100644 internal/test/filter/operations/server_test.go delete mode 100644 internal/test/filter/server.yaml delete mode 100644 internal/test/filter/tags/server.gen.go delete mode 100644 internal/test/filter/tags/server_test.go delete mode 100644 internal/test/issues/issue-1039/client-config.yaml delete mode 100644 internal/test/issues/issue-1039/client.gen.go delete mode 100644 internal/test/issues/issue-1039/defaultbehaviour/defaultbehaviour_test.go delete mode 100644 internal/test/issues/issue-1039/defaultbehaviour/types.gen.go delete mode 100644 internal/test/issues/issue-1039/doc.go delete mode 100644 internal/test/issues/issue-1039/issue_test.go delete mode 100644 internal/test/issues/issue-1039/server-config.yaml delete mode 100644 internal/test/issues/issue-1039/server.gen.go delete mode 100644 internal/test/issues/issue-1039/type-config-defaultbehaviour.yaml delete mode 100644 internal/test/issues/issue-1087/api.gen.go delete mode 100644 internal/test/issues/issue-1087/deps/deps.gen.go delete mode 100644 internal/test/issues/issue-1087/deps/doc.go delete mode 100644 internal/test/issues/issue-1087/deps/my-deps.json delete mode 100644 internal/test/issues/issue-1087/doc.go delete mode 100644 internal/test/issues/issue-1087/server.config.yaml delete mode 100644 internal/test/issues/issue-1087/spec.yaml delete mode 100644 internal/test/issues/issue-1093/api/child/child.gen.go delete mode 100644 internal/test/issues/issue-1093/api/parent/parent.gen.go delete mode 100644 internal/test/issues/issue-1093/child.api.yaml delete mode 100644 internal/test/issues/issue-1093/child.cfg.yaml delete mode 100644 internal/test/issues/issue-1093/doc.go delete mode 100644 internal/test/issues/issue-1093/issue_test.go delete mode 100644 internal/test/issues/issue-1093/parent.api.yaml delete mode 100644 internal/test/issues/issue-1093/parent.cfg.yaml delete mode 100644 internal/test/issues/issue-1127/api.gen.go delete mode 100644 internal/test/issues/issue-1127/doc.go delete mode 100644 internal/test/issues/issue-1127/spec.yaml delete mode 100644 internal/test/issues/issue-1168/api.gen.go delete mode 100644 internal/test/issues/issue-1168/doc.go delete mode 100644 internal/test/issues/issue-1168/spec.yaml delete mode 100644 internal/test/issues/issue-1180/config.yaml delete mode 100644 internal/test/issues/issue-1180/doc.go delete mode 100644 internal/test/issues/issue-1180/issue.gen.go delete mode 100644 internal/test/issues/issue-1180/issue_test.go delete mode 100644 internal/test/issues/issue-1182/pkg1.yaml delete mode 100644 internal/test/issues/issue-1182/pkg1/config.yaml delete mode 100644 internal/test/issues/issue-1182/pkg1/doc.go delete mode 100644 internal/test/issues/issue-1182/pkg1/pkg1.gen.go delete mode 100644 internal/test/issues/issue-1182/pkg2.yaml delete mode 100644 internal/test/issues/issue-1182/pkg2/doc.go delete mode 100644 internal/test/issues/issue-1182/pkg2/pkg2.gen.go delete mode 100644 internal/test/issues/issue-1189/config.yaml delete mode 100644 internal/test/issues/issue-1189/doc.go delete mode 100644 internal/test/issues/issue-1189/issue1189.gen.go delete mode 100644 internal/test/issues/issue-1189/issue1189.yaml delete mode 100644 internal/test/issues/issue-1208-1209/config.yaml delete mode 100644 internal/test/issues/issue-1208-1209/doc.go delete mode 100644 internal/test/issues/issue-1208-1209/issue-multi-json.gen.go delete mode 100644 internal/test/issues/issue-1208-1209/issue-multi-json.yaml delete mode 100644 internal/test/issues/issue-1208-1209/issue-multi-json_test.go delete mode 100644 internal/test/issues/issue-1212/pkg1.yaml delete mode 100644 internal/test/issues/issue-1212/pkg1/config.yaml delete mode 100644 internal/test/issues/issue-1212/pkg1/doc.go delete mode 100644 internal/test/issues/issue-1212/pkg1/pkg1.gen.go delete mode 100644 internal/test/issues/issue-1212/pkg2.yaml delete mode 100644 internal/test/issues/issue-1212/pkg2/config.yaml delete mode 100644 internal/test/issues/issue-1212/pkg2/doc.go delete mode 100644 internal/test/issues/issue-1212/pkg2/pkg2.gen.go delete mode 100644 internal/test/issues/issue-1219/config.yaml delete mode 100644 internal/test/issues/issue-1219/doc.go delete mode 100644 internal/test/issues/issue-1219/issue.yaml delete mode 100644 internal/test/issues/issue-1219/issue_test.go delete mode 100644 internal/test/issues/issue-1298/config.yaml delete mode 100644 internal/test/issues/issue-1298/doc.go delete mode 100644 internal/test/issues/issue-1298/issue1298.gen.go delete mode 100644 internal/test/issues/issue-1298/issue1298.yaml delete mode 100644 internal/test/issues/issue-1298/issue1298_test.go delete mode 100644 internal/test/issues/issue-1378/bionicle.yaml delete mode 100644 internal/test/issues/issue-1378/bionicle/bionicle.gen.go delete mode 100644 internal/test/issues/issue-1378/bionicle/config.yaml delete mode 100644 internal/test/issues/issue-1378/bionicle/generate.go delete mode 100644 internal/test/issues/issue-1378/common.yaml delete mode 100644 internal/test/issues/issue-1378/common/common.gen.go delete mode 100644 internal/test/issues/issue-1378/common/config.yaml delete mode 100644 internal/test/issues/issue-1378/common/generate.go delete mode 100644 internal/test/issues/issue-1378/foo-service.yaml delete mode 100644 internal/test/issues/issue-1378/fooservice/config.yaml delete mode 100644 internal/test/issues/issue-1378/fooservice/fooservice.gen.go delete mode 100644 internal/test/issues/issue-1378/fooservice/generate.go delete mode 100644 internal/test/issues/issue-1397/config.yaml delete mode 100644 internal/test/issues/issue-1397/doc.go delete mode 100644 internal/test/issues/issue-1397/issue1397.gen.go delete mode 100644 internal/test/issues/issue-1397/spec.yaml delete mode 100644 internal/test/issues/issue-1529/strict-echo/doc.go delete mode 100644 internal/test/issues/issue-1529/strict-echo/issue1529.gen.go delete mode 100644 internal/test/issues/issue-1529/strict-echo/spec.yaml delete mode 100644 internal/test/issues/issue-1529/strict-fiber/config.yaml delete mode 100644 internal/test/issues/issue-1529/strict-fiber/doc.go delete mode 100644 internal/test/issues/issue-1529/strict-fiber/issue1529.gen.go delete mode 100644 internal/test/issues/issue-1529/strict-fiber/spec.yaml delete mode 100644 internal/test/issues/issue-1529/strict-iris/config.yaml delete mode 100644 internal/test/issues/issue-1529/strict-iris/doc.go delete mode 100644 internal/test/issues/issue-1529/strict-iris/issue1529.gen.go delete mode 100644 internal/test/issues/issue-1529/strict-iris/spec.yaml delete mode 100644 internal/test/issues/issue-1530/config.yaml delete mode 100644 internal/test/issues/issue-1530/doc.go delete mode 100644 internal/test/issues/issue-1530/issue1530.gen.go delete mode 100644 internal/test/issues/issue-1530/issue1530.yaml delete mode 100644 internal/test/issues/issue-1530/issue1530_test.go delete mode 100644 internal/test/issues/issue-1676/api.yaml delete mode 100644 internal/test/issues/issue-1676/generate.go delete mode 100644 internal/test/issues/issue-1676/ping.gen.go delete mode 100644 internal/test/issues/issue-2031/config.yaml delete mode 100644 internal/test/issues/issue-2031/generate.go delete mode 100644 internal/test/issues/issue-2031/issue2031.gen.go delete mode 100644 internal/test/issues/issue-2031/issue2031_test.go delete mode 100644 internal/test/issues/issue-2031/openapi.yaml delete mode 100644 internal/test/issues/issue-2031/prefer/config.yaml delete mode 100644 internal/test/issues/issue-2031/prefer/generate.go delete mode 100644 internal/test/issues/issue-2031/prefer/issue2031_test.go delete mode 100644 internal/test/issues/issue-2031/prefer/openapi.yaml delete mode 100644 internal/test/issues/issue-2113/config.common.yaml delete mode 100644 internal/test/issues/issue-2113/doc.go delete mode 100644 internal/test/issues/issue-2113/issue_test.go delete mode 100644 internal/test/issues/issue-2113/spec.yaml delete mode 100644 internal/test/issues/issue-2185/config.yaml delete mode 100644 internal/test/issues/issue-2185/generate.go delete mode 100644 internal/test/issues/issue-2185/issue2185.gen.go delete mode 100644 internal/test/issues/issue-2185/issue2185_test.go delete mode 100644 internal/test/issues/issue-2185/spec.yaml delete mode 100644 internal/test/issues/issue-2190/config.yaml delete mode 100644 internal/test/issues/issue-2190/generate.go delete mode 100644 internal/test/issues/issue-2190/issue2190.gen.go delete mode 100644 internal/test/issues/issue-2190/issue2190_test.go delete mode 100644 internal/test/issues/issue-2190/spec.yaml delete mode 100644 internal/test/issues/issue-2232/config.yaml delete mode 100644 internal/test/issues/issue-2232/generate.go delete mode 100644 internal/test/issues/issue-2232/issue2232.gen.go delete mode 100644 internal/test/issues/issue-2232/issue2232_test.go delete mode 100644 internal/test/issues/issue-2232/spec.yaml delete mode 100644 internal/test/issues/issue-312/doc.go delete mode 100644 internal/test/issues/issue-312/issue_test.go delete mode 100644 internal/test/issues/issue-52/issue.gen.go delete mode 100644 internal/test/issues/issue-52/issue_test.go delete mode 100644 internal/test/issues/issue-52/spec.yaml delete mode 100644 internal/test/issues/issue-579/gen.go delete mode 100644 internal/test/issues/issue-579/issue.gen.go delete mode 100644 internal/test/issues/issue-579/issue_test.go delete mode 100644 internal/test/issues/issue-579/spec.yaml delete mode 100644 internal/test/issues/issue-832/config.yaml delete mode 100644 internal/test/issues/issue-832/generate.go delete mode 100644 internal/test/issues/issue-832/issue.gen.go delete mode 100644 internal/test/issues/issue-832/spec.yaml delete mode 100644 internal/test/issues/issue-936/gen.go delete mode 100644 internal/test/issues/issue-936/server.config.yaml delete mode 100644 internal/test/issues/issue-936/spec.yaml delete mode 100644 internal/test/issues/issue-grab_import_names/config.yaml delete mode 100644 internal/test/issues/issue-grab_import_names/doc.go delete mode 100644 internal/test/issues/issue-grab_import_names/issue_test.go delete mode 100644 internal/test/issues/issue-grab_import_names/spec.yaml delete mode 100644 internal/test/issues/issue-head-digit-of-httpheader/config.yaml delete mode 100644 internal/test/issues/issue-head-digit-of-httpheader/doc.go delete mode 100644 internal/test/issues/issue-head-digit-of-httpheader/issue.gen.go delete mode 100644 internal/test/issues/issue-head-digit-of-httpheader/spec.yaml delete mode 100644 internal/test/issues/issue-head-digit-of-operation-id/config.yaml delete mode 100644 internal/test/issues/issue-head-digit-of-operation-id/doc.go delete mode 100644 internal/test/issues/issue-head-digit-of-operation-id/issue.gen.go delete mode 100644 internal/test/issues/issue-head-digit-of-operation-id/spec.yaml delete mode 100644 internal/test/issues/issue-illegal_enum_names/config.yaml delete mode 100644 internal/test/issues/issue-illegal_enum_names/doc.go delete mode 100644 internal/test/issues/issue-illegal_enum_names/issue.gen.go delete mode 100644 internal/test/issues/issue-illegal_enum_names/issue_test.go delete mode 100644 internal/test/issues/issue-illegal_enum_names/spec.yaml delete mode 100644 internal/test/issues/issue-removed-external-ref/config.base.yaml delete mode 100644 internal/test/issues/issue-removed-external-ref/config.ext.yaml delete mode 100644 internal/test/issues/issue-removed-external-ref/doc.go delete mode 100644 internal/test/issues/issue-removed-external-ref/gen/spec_base/.gitempty delete mode 100644 internal/test/issues/issue-removed-external-ref/gen/spec_base/issue.gen.go delete mode 100644 internal/test/issues/issue-removed-external-ref/gen/spec_ext/.gitempty delete mode 100644 internal/test/issues/issue-removed-external-ref/gen/spec_ext/issue.gen.go delete mode 100644 internal/test/issues/issue-removed-external-ref/spec-base.yaml delete mode 100644 internal/test/issues/issue-removed-external-ref/spec-ext.yaml delete mode 100644 internal/test/issues/issue1469/config.yaml delete mode 100644 internal/test/issues/issue1469/doc.go delete mode 100644 internal/test/issues/issue1469/main.gen.go delete mode 100644 internal/test/issues/issue1469/main_test.go delete mode 100644 internal/test/issues/issue1469/spec.yaml delete mode 100644 internal/test/issues/issue1561/config.yaml delete mode 100644 internal/test/issues/issue1561/generate.go delete mode 100644 internal/test/issues/issue1561/issue1561.gen.go delete mode 100644 internal/test/issues/issue1561/issue1561_test.go delete mode 100644 internal/test/issues/issue1561/openapi.yaml delete mode 100644 internal/test/issues/issue1767/config.yaml delete mode 100644 internal/test/issues/issue1767/generate.go delete mode 100644 internal/test/issues/issue1767/issue1767.gen.go delete mode 100644 internal/test/issues/issue1767/openapi.yaml delete mode 100644 internal/test/issues/issue1825/config.yaml delete mode 100644 internal/test/issues/issue1825/doc.go delete mode 100644 internal/test/issues/issue1825/issue1825.gen.go delete mode 100644 internal/test/issues/issue1825/object_b.json delete mode 100644 internal/test/issues/issue1825/overlay.yaml delete mode 100644 internal/test/issues/issue1825/overlay_test.go delete mode 100644 internal/test/issues/issue1825/packageA/config.yaml delete mode 100644 internal/test/issues/issue1825/packageA/doc.go delete mode 100644 internal/test/issues/issue1825/packageA/externalref.gen.go delete mode 100644 internal/test/issues/issue1825/packageA/spec.yaml delete mode 100644 internal/test/issues/issue1825/spec/spec.yaml delete mode 100644 internal/test/issues/issue193/config.yaml delete mode 100644 internal/test/issues/issue193/generate.go delete mode 100644 internal/test/issues/issue193/issue.gen.go delete mode 100644 internal/test/issues/issue193/spec.yaml delete mode 100644 internal/test/issues/issue1957/config.yaml delete mode 100644 internal/test/issues/issue1957/generate.go delete mode 100644 internal/test/issues/issue1957/issue1957.gen.go delete mode 100644 internal/test/issues/issue1957/issue1957_test.go delete mode 100644 internal/test/issues/issue1957/openapi.yaml delete mode 100644 internal/test/issues/issue240/api.yaml delete mode 100644 internal/test/issues/issue240/cfg.yaml delete mode 100644 internal/test/issues/issue240/client.gen.go delete mode 100644 internal/test/issues/issue240/generate.go delete mode 100644 internal/test/issues/issue609/config.yaml delete mode 100644 internal/test/issues/issue609/generate.go delete mode 100644 internal/test/issues/issue609/issue609.gen.go delete mode 100644 internal/test/issues/issue609/openapi.yaml delete mode 100644 internal/test/outputoptions/disabletypealiases/config.yaml delete mode 100644 internal/test/outputoptions/disabletypealiases/spec.yaml delete mode 100644 internal/test/outputoptions/disabletypealiases/types.gen.go delete mode 100644 internal/test/outputoptions/disabletypealiases/types_ext.go delete mode 100644 internal/test/outputoptions/name-normalizer/spec.yaml delete mode 100644 internal/test/outputoptions/name-normalizer/to-camel-case-with-additional-initialisms/config.yaml delete mode 100644 internal/test/outputoptions/name-normalizer/to-camel-case-with-additional-initialisms/generate.go delete mode 100644 internal/test/outputoptions/name-normalizer/to-camel-case-with-additional-initialisms/name_normalizer.gen.go delete mode 100644 internal/test/outputoptions/name-normalizer/to-camel-case-with-additional-initialisms/name_normalizer_test.go delete mode 100644 internal/test/outputoptions/name-normalizer/to-camel-case-with-digits/config.yaml delete mode 100644 internal/test/outputoptions/name-normalizer/to-camel-case-with-digits/generate.go delete mode 100644 internal/test/outputoptions/name-normalizer/to-camel-case-with-digits/name_normalizer.gen.go delete mode 100644 internal/test/outputoptions/name-normalizer/to-camel-case-with-digits/name_normalizer_test.go delete mode 100644 internal/test/outputoptions/name-normalizer/to-camel-case-with-initialisms/config.yaml delete mode 100644 internal/test/outputoptions/name-normalizer/to-camel-case-with-initialisms/generate.go delete mode 100644 internal/test/outputoptions/name-normalizer/to-camel-case-with-initialisms/name_normalizer.gen.go delete mode 100644 internal/test/outputoptions/name-normalizer/to-camel-case-with-initialisms/name_normalizer_test.go delete mode 100644 internal/test/outputoptions/name-normalizer/to-camel-case/config.yaml delete mode 100644 internal/test/outputoptions/name-normalizer/to-camel-case/generate.go delete mode 100644 internal/test/outputoptions/name-normalizer/to-camel-case/name_normalizer.gen.go delete mode 100644 internal/test/outputoptions/name-normalizer/to-camel-case/name_normalizer_test.go delete mode 100644 internal/test/outputoptions/name-normalizer/unset/config.yaml delete mode 100644 internal/test/outputoptions/name-normalizer/unset/generate.go delete mode 100644 internal/test/outputoptions/name-normalizer/unset/name_normalizer.gen.go delete mode 100644 internal/test/outputoptions/name-normalizer/unset/name_normalizer_test.go delete mode 100644 internal/test/outputoptions/yaml-tags/config.yaml delete mode 100644 internal/test/outputoptions/yaml-tags/generate.go delete mode 100644 internal/test/outputoptions/yaml-tags/spec.yaml delete mode 100644 internal/test/outputoptions/yaml-tags/yamltags.go delete mode 100644 internal/test/parameters/config.yaml rename internal/test/{issues/issue-52 => parameters/content}/config.yaml (68%) create mode 100644 internal/test/parameters/content/content.gen.go create mode 100644 internal/test/parameters/content/content_test.go rename internal/test/{extensions/x-order/generate.go => parameters/content/doc.go} (87%) create mode 100644 internal/test/parameters/content/spec.yaml create mode 100644 internal/test/parameters/cookie/form/config.yaml rename internal/test/{issues/issue-grab_import_names/issue.gen.go => parameters/cookie/form/cookie_form.gen.go} (50%) create mode 100644 internal/test/parameters/cookie/form/cookie_form_test.go create mode 100644 internal/test/parameters/cookie/form/doc.go create mode 100644 internal/test/parameters/cookie/form/spec.yaml delete mode 100644 internal/test/parameters/doc.go rename internal/test/{issues/issue-312 => parameters/encoding}/config.yaml (68%) rename internal/test/{externalref/packageB => parameters/encoding}/doc.go (86%) rename internal/test/{issues/issue-312/issue.gen.go => parameters/encoding/encoding.gen.go} (79%) create mode 100644 internal/test/parameters/encoding/encoding_test.go rename internal/test/{issues/issue-312 => parameters/encoding}/spec.yaml (52%) create mode 100644 internal/test/parameters/header/simple/config.yaml create mode 100644 internal/test/parameters/header/simple/doc.go create mode 100644 internal/test/parameters/header/simple/header_simple.gen.go create mode 100644 internal/test/parameters/header/simple/header_simple_test.go create mode 100644 internal/test/parameters/header/simple/spec.yaml delete mode 100644 internal/test/parameters/parameters.gen.go delete mode 100644 internal/test/parameters/parameters.yaml delete mode 100644 internal/test/parameters/parameters_test.go rename internal/test/{issues/issue-1529/strict-echo => parameters/path/label}/config.yaml (60%) create mode 100644 internal/test/parameters/path/label/doc.go create mode 100644 internal/test/parameters/path/label/path_label.gen.go create mode 100644 internal/test/parameters/path/label/path_label_test.go create mode 100644 internal/test/parameters/path/label/spec.yaml rename internal/test/{issues/issue-1182/pkg2 => parameters/path/matrix}/config.yaml (54%) create mode 100644 internal/test/parameters/path/matrix/doc.go create mode 100644 internal/test/parameters/path/matrix/path_matrix.gen.go create mode 100644 internal/test/parameters/path/matrix/path_matrix_test.go create mode 100644 internal/test/parameters/path/matrix/spec.yaml rename internal/test/{issues/issue-1676/cfg.yaml => parameters/path/simple/config.yaml} (53%) create mode 100644 internal/test/parameters/path/simple/doc.go create mode 100644 internal/test/parameters/path/simple/path_simple.gen.go create mode 100644 internal/test/parameters/path/simple/path_simple_test.go create mode 100644 internal/test/parameters/path/simple/spec.yaml rename internal/test/{any_of/param => parameters/precedence}/config.yaml (70%) create mode 100644 internal/test/parameters/precedence/doc.go rename internal/test/{issues/issue-2031/prefer/issue2031.gen.go => parameters/precedence/precedence.gen.go} (70%) create mode 100644 internal/test/parameters/precedence/precedence_test.go rename internal/test/{issues/issue-1180/issue.yaml => parameters/precedence/spec.yaml} (55%) rename internal/test/{issues/issue-1087/deps => parameters/query/deep_object}/config.yaml (51%) create mode 100644 internal/test/parameters/query/deep_object/doc.go rename internal/test/{any_of/codegen/inline/openapi.gen.go => parameters/query/deep_object/query_deep_object.gen.go} (61%) create mode 100644 internal/test/parameters/query/deep_object/query_deep_object_test.go create mode 100644 internal/test/parameters/query/deep_object/spec.yaml create mode 100644 internal/test/parameters/query/form/config.yaml create mode 100644 internal/test/parameters/query/form/doc.go create mode 100644 internal/test/parameters/query/form/query_form.gen.go create mode 100644 internal/test/parameters/query/form/query_form_test.go create mode 100644 internal/test/parameters/query/form/spec.yaml delete mode 100644 internal/test/schemas/config.yaml delete mode 100644 internal/test/schemas/doc.go delete mode 100644 internal/test/schemas/schemas.gen.go delete mode 100644 internal/test/schemas/schemas.yaml delete mode 100644 internal/test/server/config.yaml delete mode 100644 internal/test/server/doc.go delete mode 100644 internal/test/server/server.gen.go delete mode 100644 internal/test/server/server_test.go delete mode 100644 internal/test/strict-server/chi/server.cfg.yaml delete mode 100644 internal/test/strict-server/chi/server.gen.go delete mode 100644 internal/test/strict-server/chi/server.go delete mode 100644 internal/test/strict-server/chi/types.gen.go delete mode 100644 internal/test/strict-server/client/client.cfg.yaml delete mode 100644 internal/test/strict-server/client/client.gen.go delete mode 100644 internal/test/strict-server/client/client.go delete mode 100644 internal/test/strict-server/echo/server.cfg.yaml delete mode 100644 internal/test/strict-server/echo/server.gen.go delete mode 100644 internal/test/strict-server/echo/server.go delete mode 100644 internal/test/strict-server/echo/types.gen.go delete mode 100644 internal/test/strict-server/fiber/fiber_strict_test.go delete mode 100644 internal/test/strict-server/fiber/server.cfg.yaml delete mode 100644 internal/test/strict-server/fiber/server.gen.go delete mode 100644 internal/test/strict-server/fiber/server.go delete mode 100644 internal/test/strict-server/fiber/types.gen.go delete mode 100644 internal/test/strict-server/gin/server.cfg.yaml delete mode 100644 internal/test/strict-server/gin/server.gen.go delete mode 100644 internal/test/strict-server/gin/server.go delete mode 100644 internal/test/strict-server/gin/types.cfg.yaml delete mode 100644 internal/test/strict-server/gin/types.gen.go delete mode 100644 internal/test/strict-server/gorilla/server.cfg.yaml delete mode 100644 internal/test/strict-server/gorilla/server.gen.go delete mode 100644 internal/test/strict-server/gorilla/server.go delete mode 100644 internal/test/strict-server/gorilla/types.cfg.yaml delete mode 100644 internal/test/strict-server/gorilla/types.gen.go delete mode 100644 internal/test/strict-server/iris/server.cfg.yaml delete mode 100644 internal/test/strict-server/iris/server.gen.go delete mode 100644 internal/test/strict-server/iris/server.go delete mode 100644 internal/test/strict-server/iris/types.cfg.yaml delete mode 100644 internal/test/strict-server/iris/types.gen.go delete mode 100644 internal/test/strict-server/stdhttp/Makefile delete mode 100644 internal/test/strict-server/stdhttp/go.mod delete mode 100644 internal/test/strict-server/stdhttp/go.sum delete mode 100644 internal/test/strict-server/stdhttp/server.cfg.yaml delete mode 100644 internal/test/strict-server/stdhttp/server.gen.go delete mode 100644 internal/test/strict-server/stdhttp/server.go delete mode 100644 internal/test/strict-server/stdhttp/std_strict_test.go delete mode 100644 internal/test/strict-server/stdhttp/tools/tools.go delete mode 100644 internal/test/strict-server/stdhttp/types.cfg.yaml delete mode 100644 internal/test/strict-server/stdhttp/types.gen.go delete mode 100644 internal/test/strict-server/strict-schema.yaml delete mode 100644 internal/test/strict-server/strict_test.go delete mode 100644 internal/test/test-schema.yaml create mode 100644 internal/test/tools.go diff --git a/internal/test/issues/issue-1219/issue.gen.go b/internal/test/aggregates/allof/allof.gen.go similarity index 97% rename from internal/test/issues/issue-1219/issue.gen.go rename to internal/test/aggregates/allof/allof.gen.go index 2beeedc59c..99ac7e24a2 100644 --- a/internal/test/issues/issue-1219/issue.gen.go +++ b/internal/test/aggregates/allof/allof.gen.go @@ -1,7 +1,7 @@ -// Package issue1219 provides primitives to interact with the openapi HTTP API. +// Package allof provides primitives to interact with the openapi HTTP API. // // Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package issue1219 +package allof import ( "encoding/json" @@ -147,6 +147,28 @@ type MergeWithoutWithout struct { FieldB *string `json:"fieldB,omitempty"` } +// Person defines model for Person. +type Person struct { + FirstName string `json:"FirstName"` + GovernmentIDNumber *int64 `json:"GovernmentIDNumber,omitempty"` + LastName string `json:"LastName"` +} + +// PersonProperties defines model for PersonProperties. +type PersonProperties struct { + FirstName *string `json:"FirstName,omitempty"` + GovernmentIDNumber *int64 `json:"GovernmentIDNumber,omitempty"` + LastName *string `json:"LastName,omitempty"` +} + +// PersonWithID defines model for PersonWithID. +type PersonWithID struct { + FirstName string `json:"FirstName"` + GovernmentIDNumber *int64 `json:"GovernmentIDNumber,omitempty"` + ID int64 `json:"ID"` + LastName string `json:"LastName"` +} + // WithAnyAdditional1 defines model for WithAnyAdditional1. type WithAnyAdditional1 struct { Field1 *int `json:"field1,omitempty"` diff --git a/internal/test/aggregates/allof/allof_test.go b/internal/test/aggregates/allof/allof_test.go new file mode 100644 index 0000000000..61ec719f4d --- /dev/null +++ b/internal/test/aggregates/allof/allof_test.go @@ -0,0 +1,144 @@ +package allof + +import ( + "encoding/json" + "reflect" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// Tests allOf composition: PersonProperties → Person → PersonWithID. +func TestAllOfCompositionHierarchy(t *testing.T) { + t.Run("PersonProperties has all fields optional", func(t *testing.T) { + pp := PersonProperties{} + assert.Nil(t, pp.FirstName) + assert.Nil(t, pp.LastName) + assert.Nil(t, pp.GovernmentIDNumber) + }) + + t.Run("Person has required FirstName and LastName", func(t *testing.T) { + p := Person{ + FirstName: "Alex", + LastName: "Smith", + } + assert.Equal(t, "Alex", p.FirstName) + assert.Equal(t, "Smith", p.LastName) + assert.Nil(t, p.GovernmentIDNumber) + }) + + t.Run("PersonWithID adds required ID", func(t *testing.T) { + p := PersonWithID{ + FirstName: "Alex", + LastName: "Smith", + ID: 12345, + } + assert.Equal(t, "Alex", p.FirstName) + assert.Equal(t, int64(12345), p.ID) + }) +} + +func TestAllOfCompositionJSONRoundTrip(t *testing.T) { + govID := int64(999) + p := PersonWithID{ + FirstName: "Alex", + LastName: "Smith", + ID: 42, + GovernmentIDNumber: &govID, + } + + data, err := json.Marshal(p) + require.NoError(t, err) + + var roundTripped PersonWithID + err = json.Unmarshal(data, &roundTripped) + require.NoError(t, err) + assert.Equal(t, p.FirstName, roundTripped.FirstName) + assert.Equal(t, p.LastName, roundTripped.LastName) + assert.Equal(t, p.ID, roundTripped.ID) + assert.Equal(t, *p.GovernmentIDNumber, *roundTripped.GovernmentIDNumber) +} + +// From issue-1219: exhaustive additionalProperties merge matrix. +func TestAdditionalPropertiesMerge(t *testing.T) { + t.Run("both any: result has any additionalProperties", func(t *testing.T) { + assert.IsType(t, map[string]interface{}{}, MergeWithAnyWithAny{}.AdditionalProperties) + }) + + t.Run("any+string: result has typed additionalProperties", func(t *testing.T) { + assert.IsType(t, map[string]string{}, MergeWithAnyWithString{}.AdditionalProperties) + }) + + t.Run("string+any: result has typed additionalProperties", func(t *testing.T) { + assert.IsType(t, map[string]string{}, MergeWithStringWithAny{}.AdditionalProperties) + }) + + t.Run("any+default: result has any additionalProperties", func(t *testing.T) { + assert.IsType(t, map[string]interface{}{}, MergeWithAnyDefault{}.AdditionalProperties) + }) + + t.Run("default+any: result has any additionalProperties", func(t *testing.T) { + assert.IsType(t, map[string]interface{}{}, MergeDefaultWithAny{}.AdditionalProperties) + }) + + t.Run("any+false: no additionalProperties field", func(t *testing.T) { + _, exist := reflect.TypeOf(MergeWithAnyWithout{}).FieldByName("AdditionalProperties") + assert.False(t, exist) + }) + + t.Run("false+any: no additionalProperties field", func(t *testing.T) { + _, exist := reflect.TypeOf(MergeWithoutWithAny{}).FieldByName("AdditionalProperties") + assert.False(t, exist) + }) + + t.Run("string+default: result has typed additionalProperties", func(t *testing.T) { + assert.IsType(t, map[string]string{}, MergeWithStringDefault{}.AdditionalProperties) + }) + + t.Run("default+string: result has typed additionalProperties", func(t *testing.T) { + assert.IsType(t, map[string]string{}, MergeDefaultWithString{}.AdditionalProperties) + }) + + t.Run("string+false: no additionalProperties field", func(t *testing.T) { + _, exist := reflect.TypeOf(MergeWithStringWithout{}).FieldByName("AdditionalProperties") + assert.False(t, exist) + }) + + t.Run("false+string: no additionalProperties field", func(t *testing.T) { + _, exist := reflect.TypeOf(MergeWithoutWithString{}).FieldByName("AdditionalProperties") + assert.False(t, exist) + }) + + t.Run("default+default: no additionalProperties field (compat)", func(t *testing.T) { + _, exist := reflect.TypeOf(MergeDefaultDefault{}).FieldByName("AdditionalProperties") + assert.False(t, exist) + }) + + t.Run("default+false: no additionalProperties field", func(t *testing.T) { + _, exist := reflect.TypeOf(MergeDefaultWithout{}).FieldByName("AdditionalProperties") + assert.False(t, exist) + }) + + t.Run("false+default: no additionalProperties field", func(t *testing.T) { + _, exist := reflect.TypeOf(MergeWithoutDefault{}).FieldByName("AdditionalProperties") + assert.False(t, exist) + }) + + t.Run("false+false: no additionalProperties field", func(t *testing.T) { + _, exist := reflect.TypeOf(MergeWithoutWithout{}).FieldByName("AdditionalProperties") + assert.False(t, exist) + }) +} + +// Verify merged structs contain fields from both source schemas. +func TestAllOfMergedFields(t *testing.T) { + m := MergeWithAnyWithAny{} + typ := reflect.TypeOf(m) + + _, hasField1 := typ.FieldByName("Field1") + assert.True(t, hasField1, "merged struct should have Field1 from first schema") + + _, hasFieldA := typ.FieldByName("FieldA") + assert.True(t, hasFieldA, "merged struct should have FieldA from second schema") +} diff --git a/internal/test/strict-server/echo/types.cfg.yaml b/internal/test/aggregates/allof/config.yaml similarity index 72% rename from internal/test/strict-server/echo/types.cfg.yaml rename to internal/test/aggregates/allof/config.yaml index 2ed9740ea7..af44872a00 100644 --- a/internal/test/strict-server/echo/types.cfg.yaml +++ b/internal/test/aggregates/allof/config.yaml @@ -1,5 +1,5 @@ # yaml-language-server: $schema=../../../../configuration-schema.json -package: api +package: allof generate: models: true -output: types.gen.go +output: allof.gen.go diff --git a/internal/test/any_of/param/doc.go b/internal/test/aggregates/allof/doc.go similarity index 88% rename from internal/test/any_of/param/doc.go rename to internal/test/aggregates/allof/doc.go index 657385e03f..f7d9559019 100644 --- a/internal/test/any_of/param/doc.go +++ b/internal/test/aggregates/allof/doc.go @@ -1,3 +1,3 @@ -package param +package allof //go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml spec.yaml diff --git a/internal/test/aggregates/allof/spec.yaml b/internal/test/aggregates/allof/spec.yaml new file mode 100644 index 0000000000..d54e4227e6 --- /dev/null +++ b/internal/test/aggregates/allof/spec.yaml @@ -0,0 +1,211 @@ +openapi: "3.0.1" +info: + version: 1.0.0 + title: AllOf Composition + description: Tests allOf composition and additionalProperties merging +paths: + /person: + get: + operationId: getPerson + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: "#/components/schemas/PersonWithID" + /merge: + get: + operationId: getMerge + responses: + "200": + description: OK + content: + application/json: + schema: + type: object + properties: + mergeWithAnyWithAny: + $ref: "#/components/schemas/MergeWithAnyWithAny" + mergeWithAnyWithString: + $ref: "#/components/schemas/MergeWithAnyWithString" + mergeWithStringWithAny: + $ref: "#/components/schemas/MergeWithStringWithAny" + mergeWithAnyDefault: + $ref: "#/components/schemas/MergeWithAnyDefault" + mergeDefaultWithAny: + $ref: "#/components/schemas/MergeDefaultWithAny" + mergeWithAnyWithout: + $ref: "#/components/schemas/MergeWithAnyWithout" + mergeWithoutWithAny: + $ref: "#/components/schemas/MergeWithoutWithAny" + mergeWithStringDefault: + $ref: "#/components/schemas/MergeWithStringDefault" + mergeDefaultWithString: + $ref: "#/components/schemas/MergeDefaultWithString" + mergeWithStringWithout: + $ref: "#/components/schemas/MergeWithStringWithout" + mergeWithoutWithString: + $ref: "#/components/schemas/MergeWithoutWithString" + mergeDefaultDefault: + $ref: "#/components/schemas/MergeDefaultDefault" + mergeDefaultWithout: + $ref: "#/components/schemas/MergeDefaultWithout" + mergeWithoutDefault: + $ref: "#/components/schemas/MergeWithoutDefault" + mergeWithoutWithout: + $ref: "#/components/schemas/MergeWithoutWithout" +components: + schemas: + # allOf composition hierarchy from existing all_of/ tests + PersonProperties: + type: object + properties: + FirstName: + type: string + LastName: + type: string + GovernmentIDNumber: + type: integer + format: int64 + Person: + type: object + allOf: + - $ref: "#/components/schemas/PersonProperties" + - required: [FirstName, LastName] + PersonWithID: + type: object + allOf: + - $ref: "#/components/schemas/Person" + - properties: + ID: + type: integer + format: int64 + required: [ID] + + # additionalProperties merge matrix from issue-1219 + WithAnyAdditional1: + type: object + properties: + field1: + type: integer + field2: + type: string + additionalProperties: true + WithAnyAdditional2: + type: object + properties: + fieldA: + type: integer + fieldB: + type: string + additionalProperties: true + WithStringAdditional1: + type: object + properties: + field1: + type: integer + field2: + type: string + additionalProperties: + type: string + WithStringAdditional2: + type: object + properties: + fieldA: + type: integer + fieldB: + type: string + additionalProperties: + type: string + WithoutAdditional1: + type: object + properties: + field1: + type: integer + field2: + type: string + additionalProperties: false + WithoutAdditional2: + type: object + properties: + fieldA: + type: integer + fieldB: + type: string + additionalProperties: false + DefaultAdditional1: + type: object + properties: + field1: + type: integer + field2: + type: string + DefaultAdditional2: + type: object + properties: + fieldA: + type: integer + fieldB: + type: string + + MergeWithAnyWithAny: + allOf: + - $ref: "#/components/schemas/WithAnyAdditional1" + - $ref: "#/components/schemas/WithAnyAdditional2" + MergeWithAnyWithString: + allOf: + - $ref: "#/components/schemas/WithAnyAdditional1" + - $ref: "#/components/schemas/WithStringAdditional2" + MergeWithStringWithAny: + allOf: + - $ref: "#/components/schemas/WithStringAdditional1" + - $ref: "#/components/schemas/WithAnyAdditional2" + MergeWithAnyDefault: + allOf: + - $ref: "#/components/schemas/WithAnyAdditional1" + - $ref: "#/components/schemas/DefaultAdditional2" + MergeDefaultWithAny: + allOf: + - $ref: "#/components/schemas/DefaultAdditional1" + - $ref: "#/components/schemas/WithAnyAdditional2" + MergeWithAnyWithout: + allOf: + - $ref: "#/components/schemas/WithAnyAdditional1" + - $ref: "#/components/schemas/WithoutAdditional2" + MergeWithoutWithAny: + allOf: + - $ref: "#/components/schemas/WithoutAdditional1" + - $ref: "#/components/schemas/WithAnyAdditional2" + MergeWithStringDefault: + allOf: + - $ref: "#/components/schemas/WithStringAdditional1" + - $ref: "#/components/schemas/DefaultAdditional2" + MergeDefaultWithString: + allOf: + - $ref: "#/components/schemas/DefaultAdditional1" + - $ref: "#/components/schemas/WithStringAdditional2" + MergeWithStringWithout: + allOf: + - $ref: "#/components/schemas/WithStringAdditional1" + - $ref: "#/components/schemas/WithoutAdditional2" + MergeWithoutWithString: + allOf: + - $ref: "#/components/schemas/WithoutAdditional1" + - $ref: "#/components/schemas/WithStringAdditional2" + MergeDefaultDefault: + allOf: + - $ref: "#/components/schemas/DefaultAdditional1" + - $ref: "#/components/schemas/DefaultAdditional2" + MergeDefaultWithout: + allOf: + - $ref: "#/components/schemas/DefaultAdditional1" + - $ref: "#/components/schemas/WithoutAdditional2" + MergeWithoutDefault: + allOf: + - $ref: "#/components/schemas/WithoutAdditional1" + - $ref: "#/components/schemas/DefaultAdditional2" + MergeWithoutWithout: + allOf: + - $ref: "#/components/schemas/WithoutAdditional1" + - $ref: "#/components/schemas/WithoutAdditional2" diff --git a/internal/test/aggregates/anyof/anyof.gen.go b/internal/test/aggregates/anyof/anyof.gen.go new file mode 100644 index 0000000000..b4d43f12f8 --- /dev/null +++ b/internal/test/aggregates/anyof/anyof.gen.go @@ -0,0 +1,279 @@ +// Package anyof provides primitives to interact with the openapi HTTP API. +// +// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. +package anyof + +import ( + "encoding/json" + + "github.com/oapi-codegen/runtime" +) + +// Defines values for DuplicateAnyOf1. +const ( + Alpha DuplicateAnyOf1 = "alpha" + Beta DuplicateAnyOf1 = "beta" + Gamma DuplicateAnyOf1 = "gamma" +) + +// Valid indicates whether the value is a known member of the DuplicateAnyOf1 enum. +func (e DuplicateAnyOf1) Valid() bool { + switch e { + case Alpha: + return true + case Beta: + return true + case Gamma: + return true + default: + return false + } +} + +// AnyOfAnimal anyOf with discriminator +type AnyOfAnimal struct { + union json.RawMessage +} + +// Cat defines model for Cat. +type Cat struct { + Indoor *bool `json:"indoor,omitempty"` + Name string `json:"name"` + Type string `json:"type"` +} + +// Dog defines model for Dog. +type Dog struct { + Breed *string `json:"breed,omitempty"` + Name string `json:"name"` + Type string `json:"type"` +} + +// DuplicateAnyOf anyOf with overlapping string schemas +type DuplicateAnyOf struct { + union json.RawMessage +} + +// DuplicateAnyOf0 defines model for . +type DuplicateAnyOf0 = string + +// DuplicateAnyOf1 defines model for DuplicateAnyOf.1. +type DuplicateAnyOf1 string + +// IdFilter defines model for IdFilter. +type IdFilter struct { + Id int `json:"id"` +} + +// NameFilter defines model for NameFilter. +type NameFilter struct { + Name string `json:"name"` +} + +// SimpleAnyOf Simple anyOf without discriminator +type SimpleAnyOf struct { + union json.RawMessage +} + +// SimpleAnyOf0 defines model for . +type SimpleAnyOf0 struct { + Name *string `json:"name,omitempty"` +} + +// SimpleAnyOf1 defines model for . +type SimpleAnyOf1 struct { + Id *int `json:"id,omitempty"` +} + +// SearchParams defines parameters for Search. +type SearchParams struct { + Filter *struct { + union json.RawMessage + } `form:"filter,omitempty" json:"filter,omitempty"` +} + +// AsCat returns the union data inside the AnyOfAnimal as a Cat +func (t AnyOfAnimal) AsCat() (Cat, error) { + var body Cat + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromCat overwrites any union data inside the AnyOfAnimal as the provided Cat +func (t *AnyOfAnimal) FromCat(v Cat) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeCat performs a merge with any union data inside the AnyOfAnimal, using the provided Cat +func (t *AnyOfAnimal) MergeCat(v Cat) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsDog returns the union data inside the AnyOfAnimal as a Dog +func (t AnyOfAnimal) AsDog() (Dog, error) { + var body Dog + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromDog overwrites any union data inside the AnyOfAnimal as the provided Dog +func (t *AnyOfAnimal) FromDog(v Dog) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeDog performs a merge with any union data inside the AnyOfAnimal, using the provided Dog +func (t *AnyOfAnimal) MergeDog(v Dog) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t AnyOfAnimal) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *AnyOfAnimal) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsDuplicateAnyOf0 returns the union data inside the DuplicateAnyOf as a DuplicateAnyOf0 +func (t DuplicateAnyOf) AsDuplicateAnyOf0() (DuplicateAnyOf0, error) { + var body DuplicateAnyOf0 + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromDuplicateAnyOf0 overwrites any union data inside the DuplicateAnyOf as the provided DuplicateAnyOf0 +func (t *DuplicateAnyOf) FromDuplicateAnyOf0(v DuplicateAnyOf0) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeDuplicateAnyOf0 performs a merge with any union data inside the DuplicateAnyOf, using the provided DuplicateAnyOf0 +func (t *DuplicateAnyOf) MergeDuplicateAnyOf0(v DuplicateAnyOf0) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsDuplicateAnyOf1 returns the union data inside the DuplicateAnyOf as a DuplicateAnyOf1 +func (t DuplicateAnyOf) AsDuplicateAnyOf1() (DuplicateAnyOf1, error) { + var body DuplicateAnyOf1 + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromDuplicateAnyOf1 overwrites any union data inside the DuplicateAnyOf as the provided DuplicateAnyOf1 +func (t *DuplicateAnyOf) FromDuplicateAnyOf1(v DuplicateAnyOf1) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeDuplicateAnyOf1 performs a merge with any union data inside the DuplicateAnyOf, using the provided DuplicateAnyOf1 +func (t *DuplicateAnyOf) MergeDuplicateAnyOf1(v DuplicateAnyOf1) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t DuplicateAnyOf) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *DuplicateAnyOf) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsSimpleAnyOf0 returns the union data inside the SimpleAnyOf as a SimpleAnyOf0 +func (t SimpleAnyOf) AsSimpleAnyOf0() (SimpleAnyOf0, error) { + var body SimpleAnyOf0 + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromSimpleAnyOf0 overwrites any union data inside the SimpleAnyOf as the provided SimpleAnyOf0 +func (t *SimpleAnyOf) FromSimpleAnyOf0(v SimpleAnyOf0) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeSimpleAnyOf0 performs a merge with any union data inside the SimpleAnyOf, using the provided SimpleAnyOf0 +func (t *SimpleAnyOf) MergeSimpleAnyOf0(v SimpleAnyOf0) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsSimpleAnyOf1 returns the union data inside the SimpleAnyOf as a SimpleAnyOf1 +func (t SimpleAnyOf) AsSimpleAnyOf1() (SimpleAnyOf1, error) { + var body SimpleAnyOf1 + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromSimpleAnyOf1 overwrites any union data inside the SimpleAnyOf as the provided SimpleAnyOf1 +func (t *SimpleAnyOf) FromSimpleAnyOf1(v SimpleAnyOf1) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeSimpleAnyOf1 performs a merge with any union data inside the SimpleAnyOf, using the provided SimpleAnyOf1 +func (t *SimpleAnyOf) MergeSimpleAnyOf1(v SimpleAnyOf1) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t SimpleAnyOf) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *SimpleAnyOf) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} diff --git a/internal/test/aggregates/anyof/anyof_test.go b/internal/test/aggregates/anyof/anyof_test.go new file mode 100644 index 0000000000..f1966498c4 --- /dev/null +++ b/internal/test/aggregates/anyof/anyof_test.go @@ -0,0 +1,121 @@ +package anyof + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestAnyOfAnimalFromCat(t *testing.T) { + cat := Cat{Type: "cat", Name: "Whiskers", Indoor: boolPtr(true)} + + var animal AnyOfAnimal + err := animal.FromCat(cat) + require.NoError(t, err) + + data, err := json.Marshal(animal) + require.NoError(t, err) + + var roundTripped AnyOfAnimal + err = json.Unmarshal(data, &roundTripped) + require.NoError(t, err) + + gotCat, err := roundTripped.AsCat() + require.NoError(t, err) + assert.Equal(t, "Whiskers", gotCat.Name) + assert.Equal(t, "cat", gotCat.Type) + assert.True(t, *gotCat.Indoor) +} + +func TestAnyOfAnimalFromDog(t *testing.T) { + breed := "Golden Retriever" + dog := Dog{Type: "dog", Name: "Buddy", Breed: &breed} + + var animal AnyOfAnimal + err := animal.FromDog(dog) + require.NoError(t, err) + + data, err := json.Marshal(animal) + require.NoError(t, err) + + var roundTripped AnyOfAnimal + err = json.Unmarshal(data, &roundTripped) + require.NoError(t, err) + + gotDog, err := roundTripped.AsDog() + require.NoError(t, err) + assert.Equal(t, "Buddy", gotDog.Name) + assert.Equal(t, "Golden Retriever", *gotDog.Breed) +} + +func TestSimpleAnyOfWithObjectVariant(t *testing.T) { + name := "test" + obj := SimpleAnyOf0{Name: &name} + + var sa SimpleAnyOf + err := sa.FromSimpleAnyOf0(obj) + require.NoError(t, err) + + data, err := json.Marshal(sa) + require.NoError(t, err) + + var roundTripped SimpleAnyOf + err = json.Unmarshal(data, &roundTripped) + require.NoError(t, err) + + got, err := roundTripped.AsSimpleAnyOf0() + require.NoError(t, err) + assert.Equal(t, "test", *got.Name) +} + +func TestSimpleAnyOfWithIdVariant(t *testing.T) { + id := 42 + obj := SimpleAnyOf1{Id: &id} + + var sa SimpleAnyOf + err := sa.FromSimpleAnyOf1(obj) + require.NoError(t, err) + + data, err := json.Marshal(sa) + require.NoError(t, err) + + var roundTripped SimpleAnyOf + err = json.Unmarshal(data, &roundTripped) + require.NoError(t, err) + + got, err := roundTripped.AsSimpleAnyOf1() + require.NoError(t, err) + assert.Equal(t, 42, *got.Id) +} + +// From issue-1189: anyOf with duplicate/overlapping schema types. +func TestDuplicateAnyOfWithPlainString(t *testing.T) { + var da DuplicateAnyOf + err := da.FromDuplicateAnyOf0("hello") + require.NoError(t, err) + + data, err := json.Marshal(da) + require.NoError(t, err) + assert.Equal(t, `"hello"`, string(data)) +} + +func TestDuplicateAnyOfWithEnumString(t *testing.T) { + var da DuplicateAnyOf + err := da.FromDuplicateAnyOf1(Alpha) + require.NoError(t, err) + + data, err := json.Marshal(da) + require.NoError(t, err) + assert.Equal(t, `"alpha"`, string(data)) + + // The enum value should be valid. + assert.True(t, Alpha.Valid()) + assert.True(t, Beta.Valid()) + assert.True(t, Gamma.Valid()) +} + +func boolPtr(b bool) *bool { + return &b +} diff --git a/internal/test/strict-server/chi/types.cfg.yaml b/internal/test/aggregates/anyof/config.yaml similarity index 72% rename from internal/test/strict-server/chi/types.cfg.yaml rename to internal/test/aggregates/anyof/config.yaml index 2ed9740ea7..ba19706918 100644 --- a/internal/test/strict-server/chi/types.cfg.yaml +++ b/internal/test/aggregates/anyof/config.yaml @@ -1,5 +1,5 @@ # yaml-language-server: $schema=../../../../configuration-schema.json -package: api +package: anyof generate: models: true -output: types.gen.go +output: anyof.gen.go diff --git a/internal/test/outputoptions/disabletypealiases/generate.go b/internal/test/aggregates/anyof/doc.go similarity index 88% rename from internal/test/outputoptions/disabletypealiases/generate.go rename to internal/test/aggregates/anyof/doc.go index 8f0dd5b3e3..ebf0c122b4 100644 --- a/internal/test/outputoptions/disabletypealiases/generate.go +++ b/internal/test/aggregates/anyof/doc.go @@ -1,3 +1,3 @@ -package types +package anyof //go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml spec.yaml diff --git a/internal/test/aggregates/anyof/spec.yaml b/internal/test/aggregates/anyof/spec.yaml new file mode 100644 index 0000000000..d077b889b3 --- /dev/null +++ b/internal/test/aggregates/anyof/spec.yaml @@ -0,0 +1,100 @@ +openapi: "3.0.1" +info: + version: 1.0.0 + title: AnyOf Types + description: Tests anyOf with discriminators, inline/ref schemas, and parameter-level anyOf +paths: + /animal: + get: + operationId: getAnimal + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: "#/components/schemas/AnyOfAnimal" + /search: + get: + operationId: search + parameters: + - name: filter + in: query + required: false + schema: + anyOf: + - $ref: "#/components/schemas/NameFilter" + - $ref: "#/components/schemas/IdFilter" + responses: + "200": + description: OK + content: + application/json: + schema: + type: object + properties: + simple: + $ref: "#/components/schemas/SimpleAnyOf" + duplicate: + $ref: "#/components/schemas/DuplicateAnyOf" +components: + schemas: + Cat: + type: object + properties: + type: + type: string + name: + type: string + indoor: + type: boolean + required: [type, name] + Dog: + type: object + properties: + type: + type: string + name: + type: string + breed: + type: string + required: [type, name] + + AnyOfAnimal: + description: anyOf with discriminator + anyOf: + - $ref: "#/components/schemas/Cat" + - $ref: "#/components/schemas/Dog" + + SimpleAnyOf: + description: Simple anyOf without discriminator + anyOf: + - type: object + properties: + name: + type: string + - type: object + properties: + id: + type: integer + + # From issue-1189: anyOf with duplicate schema types + DuplicateAnyOf: + description: anyOf with overlapping string schemas + anyOf: + - type: string + - type: string + enum: [alpha, beta, gamma] + + NameFilter: + type: object + properties: + name: + type: string + required: [name] + IdFilter: + type: object + properties: + id: + type: integer + required: [id] diff --git a/internal/test/strict-server/fiber/types.cfg.yaml b/internal/test/aggregates/oneof/config.yaml similarity index 72% rename from internal/test/strict-server/fiber/types.cfg.yaml rename to internal/test/aggregates/oneof/config.yaml index 2ed9740ea7..823a90e34e 100644 --- a/internal/test/strict-server/fiber/types.cfg.yaml +++ b/internal/test/aggregates/oneof/config.yaml @@ -1,5 +1,5 @@ # yaml-language-server: $schema=../../../../configuration-schema.json -package: api +package: oneof generate: models: true -output: types.gen.go +output: oneof.gen.go diff --git a/internal/test/any_of/codegen/inline/generate.go b/internal/test/aggregates/oneof/doc.go similarity index 88% rename from internal/test/any_of/codegen/inline/generate.go rename to internal/test/aggregates/oneof/doc.go index 020b7dc9d8..ec4e696c76 100644 --- a/internal/test/any_of/codegen/inline/generate.go +++ b/internal/test/aggregates/oneof/doc.go @@ -1,3 +1,3 @@ -package inline +package oneof //go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml spec.yaml diff --git a/internal/test/aggregates/oneof/oneof.gen.go b/internal/test/aggregates/oneof/oneof.gen.go new file mode 100644 index 0000000000..561159ad6f --- /dev/null +++ b/internal/test/aggregates/oneof/oneof.gen.go @@ -0,0 +1,833 @@ +// Package oneof provides primitives to interact with the openapi HTTP API. +// +// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. +package oneof + +import ( + "encoding/json" + "errors" + "fmt" + + "github.com/oapi-codegen/runtime" +) + +// ArrayOfOneOf defines model for ArrayOfOneOf. +type ArrayOfOneOf = []ArrayOfOneOf_Item + +// ArrayOfOneOf_Item defines model for ArrayOfOneOf.Item. +type ArrayOfOneOf_Item struct { + union json.RawMessage +} + +// BasicOneOf oneOf with references, no discriminator +type BasicOneOf struct { + union json.RawMessage +} + +// ConfigHttp defines model for ConfigHttp. +type ConfigHttp struct { + ConfigType string `json:"config_type"` + Url string `json:"url"` +} + +// ConfigSsh defines model for ConfigSsh. +type ConfigSsh struct { + ConfigType string `json:"config_type"` + Host string `json:"host"` +} + +// DiscriminatedVariantA defines model for DiscriminatedVariantA. +type DiscriminatedVariantA struct { + Discriminator string `json:"discriminator"` + Name string `json:"name"` +} + +// DiscriminatedVariantB defines model for DiscriminatedVariantB. +type DiscriminatedVariantB struct { + Discriminator string `json:"discriminator"` + Id int `json:"id"` +} + +// FixedPropVariant defines model for FixedPropVariant. +type FixedPropVariant struct { + Values Variant2 `json:"values"` +} + +// InlineOneOf oneOf with inline elements +type InlineOneOf struct { + union json.RawMessage +} + +// InlineOneOf0 defines model for . +type InlineOneOf0 struct { + Label *string `json:"label,omitempty"` +} + +// InlineOneOf1 defines model for . +type InlineOneOf1 = []float32 + +// InlineOneOf2 defines model for . +type InlineOneOf2 = bool + +// OneOfMultiMapping defines model for OneOfMultiMapping. +type OneOfMultiMapping struct { + union json.RawMessage +} + +// OneOfWithDiscriminator defines model for OneOfWithDiscriminator. +type OneOfWithDiscriminator struct { + union json.RawMessage +} + +// OneOfWithFixedDiscriminator defines model for OneOfWithFixedDiscriminator. +type OneOfWithFixedDiscriminator struct { + Type string `json:"type"` + union json.RawMessage +} + +// OneOfWithFixedProps defines model for OneOfWithFixedProps. +type OneOfWithFixedProps struct { + Fixed *string `json:"fixed,omitempty"` + union json.RawMessage +} + +// OneOfWithMapping defines model for OneOfWithMapping. +type OneOfWithMapping struct { + union json.RawMessage +} + +// Variant1 defines model for Variant1. +type Variant1 struct { + Name string `json:"name"` +} + +// Variant2 defines model for Variant2. +type Variant2 = []int + +// Variant3 defines model for Variant3. +type Variant3 = bool + +// AsVariant1 returns the union data inside the ArrayOfOneOf_Item as a Variant1 +func (t ArrayOfOneOf_Item) AsVariant1() (Variant1, error) { + var body Variant1 + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromVariant1 overwrites any union data inside the ArrayOfOneOf_Item as the provided Variant1 +func (t *ArrayOfOneOf_Item) FromVariant1(v Variant1) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeVariant1 performs a merge with any union data inside the ArrayOfOneOf_Item, using the provided Variant1 +func (t *ArrayOfOneOf_Item) MergeVariant1(v Variant1) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsVariant2 returns the union data inside the ArrayOfOneOf_Item as a Variant2 +func (t ArrayOfOneOf_Item) AsVariant2() (Variant2, error) { + var body Variant2 + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromVariant2 overwrites any union data inside the ArrayOfOneOf_Item as the provided Variant2 +func (t *ArrayOfOneOf_Item) FromVariant2(v Variant2) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeVariant2 performs a merge with any union data inside the ArrayOfOneOf_Item, using the provided Variant2 +func (t *ArrayOfOneOf_Item) MergeVariant2(v Variant2) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t ArrayOfOneOf_Item) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *ArrayOfOneOf_Item) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsVariant1 returns the union data inside the BasicOneOf as a Variant1 +func (t BasicOneOf) AsVariant1() (Variant1, error) { + var body Variant1 + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromVariant1 overwrites any union data inside the BasicOneOf as the provided Variant1 +func (t *BasicOneOf) FromVariant1(v Variant1) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeVariant1 performs a merge with any union data inside the BasicOneOf, using the provided Variant1 +func (t *BasicOneOf) MergeVariant1(v Variant1) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsVariant2 returns the union data inside the BasicOneOf as a Variant2 +func (t BasicOneOf) AsVariant2() (Variant2, error) { + var body Variant2 + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromVariant2 overwrites any union data inside the BasicOneOf as the provided Variant2 +func (t *BasicOneOf) FromVariant2(v Variant2) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeVariant2 performs a merge with any union data inside the BasicOneOf, using the provided Variant2 +func (t *BasicOneOf) MergeVariant2(v Variant2) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsVariant3 returns the union data inside the BasicOneOf as a Variant3 +func (t BasicOneOf) AsVariant3() (Variant3, error) { + var body Variant3 + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromVariant3 overwrites any union data inside the BasicOneOf as the provided Variant3 +func (t *BasicOneOf) FromVariant3(v Variant3) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeVariant3 performs a merge with any union data inside the BasicOneOf, using the provided Variant3 +func (t *BasicOneOf) MergeVariant3(v Variant3) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t BasicOneOf) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *BasicOneOf) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsInlineOneOf0 returns the union data inside the InlineOneOf as a InlineOneOf0 +func (t InlineOneOf) AsInlineOneOf0() (InlineOneOf0, error) { + var body InlineOneOf0 + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromInlineOneOf0 overwrites any union data inside the InlineOneOf as the provided InlineOneOf0 +func (t *InlineOneOf) FromInlineOneOf0(v InlineOneOf0) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeInlineOneOf0 performs a merge with any union data inside the InlineOneOf, using the provided InlineOneOf0 +func (t *InlineOneOf) MergeInlineOneOf0(v InlineOneOf0) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsInlineOneOf1 returns the union data inside the InlineOneOf as a InlineOneOf1 +func (t InlineOneOf) AsInlineOneOf1() (InlineOneOf1, error) { + var body InlineOneOf1 + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromInlineOneOf1 overwrites any union data inside the InlineOneOf as the provided InlineOneOf1 +func (t *InlineOneOf) FromInlineOneOf1(v InlineOneOf1) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeInlineOneOf1 performs a merge with any union data inside the InlineOneOf, using the provided InlineOneOf1 +func (t *InlineOneOf) MergeInlineOneOf1(v InlineOneOf1) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsInlineOneOf2 returns the union data inside the InlineOneOf as a InlineOneOf2 +func (t InlineOneOf) AsInlineOneOf2() (InlineOneOf2, error) { + var body InlineOneOf2 + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromInlineOneOf2 overwrites any union data inside the InlineOneOf as the provided InlineOneOf2 +func (t *InlineOneOf) FromInlineOneOf2(v InlineOneOf2) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeInlineOneOf2 performs a merge with any union data inside the InlineOneOf, using the provided InlineOneOf2 +func (t *InlineOneOf) MergeInlineOneOf2(v InlineOneOf2) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t InlineOneOf) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *InlineOneOf) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsConfigHttp returns the union data inside the OneOfMultiMapping as a ConfigHttp +func (t OneOfMultiMapping) AsConfigHttp() (ConfigHttp, error) { + var body ConfigHttp + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromConfigHttp overwrites any union data inside the OneOfMultiMapping as the provided ConfigHttp +func (t *OneOfMultiMapping) FromConfigHttp(v ConfigHttp) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeConfigHttp performs a merge with any union data inside the OneOfMultiMapping, using the provided ConfigHttp +func (t *OneOfMultiMapping) MergeConfigHttp(v ConfigHttp) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsConfigSsh returns the union data inside the OneOfMultiMapping as a ConfigSsh +func (t OneOfMultiMapping) AsConfigSsh() (ConfigSsh, error) { + var body ConfigSsh + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromConfigSsh overwrites any union data inside the OneOfMultiMapping as the provided ConfigSsh +func (t *OneOfMultiMapping) FromConfigSsh(v ConfigSsh) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeConfigSsh performs a merge with any union data inside the OneOfMultiMapping, using the provided ConfigSsh +func (t *OneOfMultiMapping) MergeConfigSsh(v ConfigSsh) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t OneOfMultiMapping) Discriminator() (string, error) { + var discriminator struct { + Discriminator string `json:"config_type"` + } + err := json.Unmarshal(t.union, &discriminator) + return discriminator.Discriminator, err +} + +func (t OneOfMultiMapping) ValueByDiscriminator() (interface{}, error) { + discriminator, err := t.Discriminator() + if err != nil { + return nil, err + } + switch discriminator { + case "apache_server": + return t.AsConfigHttp() + case "ssh_server": + return t.AsConfigSsh() + case "web_server": + return t.AsConfigHttp() + default: + return nil, errors.New("unknown discriminator value: " + discriminator) + } +} + +func (t OneOfMultiMapping) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *OneOfMultiMapping) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsDiscriminatedVariantA returns the union data inside the OneOfWithDiscriminator as a DiscriminatedVariantA +func (t OneOfWithDiscriminator) AsDiscriminatedVariantA() (DiscriminatedVariantA, error) { + var body DiscriminatedVariantA + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromDiscriminatedVariantA overwrites any union data inside the OneOfWithDiscriminator as the provided DiscriminatedVariantA +func (t *OneOfWithDiscriminator) FromDiscriminatedVariantA(v DiscriminatedVariantA) error { + v.Discriminator = "DiscriminatedVariantA" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeDiscriminatedVariantA performs a merge with any union data inside the OneOfWithDiscriminator, using the provided DiscriminatedVariantA +func (t *OneOfWithDiscriminator) MergeDiscriminatedVariantA(v DiscriminatedVariantA) error { + v.Discriminator = "DiscriminatedVariantA" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsDiscriminatedVariantB returns the union data inside the OneOfWithDiscriminator as a DiscriminatedVariantB +func (t OneOfWithDiscriminator) AsDiscriminatedVariantB() (DiscriminatedVariantB, error) { + var body DiscriminatedVariantB + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromDiscriminatedVariantB overwrites any union data inside the OneOfWithDiscriminator as the provided DiscriminatedVariantB +func (t *OneOfWithDiscriminator) FromDiscriminatedVariantB(v DiscriminatedVariantB) error { + v.Discriminator = "DiscriminatedVariantB" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeDiscriminatedVariantB performs a merge with any union data inside the OneOfWithDiscriminator, using the provided DiscriminatedVariantB +func (t *OneOfWithDiscriminator) MergeDiscriminatedVariantB(v DiscriminatedVariantB) error { + v.Discriminator = "DiscriminatedVariantB" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t OneOfWithDiscriminator) Discriminator() (string, error) { + var discriminator struct { + Discriminator string `json:"discriminator"` + } + err := json.Unmarshal(t.union, &discriminator) + return discriminator.Discriminator, err +} + +func (t OneOfWithDiscriminator) ValueByDiscriminator() (interface{}, error) { + discriminator, err := t.Discriminator() + if err != nil { + return nil, err + } + switch discriminator { + case "DiscriminatedVariantA": + return t.AsDiscriminatedVariantA() + case "DiscriminatedVariantB": + return t.AsDiscriminatedVariantB() + default: + return nil, errors.New("unknown discriminator value: " + discriminator) + } +} + +func (t OneOfWithDiscriminator) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *OneOfWithDiscriminator) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsVariant1 returns the union data inside the OneOfWithFixedDiscriminator as a Variant1 +func (t OneOfWithFixedDiscriminator) AsVariant1() (Variant1, error) { + var body Variant1 + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromVariant1 overwrites any union data inside the OneOfWithFixedDiscriminator as the provided Variant1 +func (t *OneOfWithFixedDiscriminator) FromVariant1(v Variant1) error { + t.Type = "v1" + + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeVariant1 performs a merge with any union data inside the OneOfWithFixedDiscriminator, using the provided Variant1 +func (t *OneOfWithFixedDiscriminator) MergeVariant1(v Variant1) error { + t.Type = "v1" + + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsFixedPropVariant returns the union data inside the OneOfWithFixedDiscriminator as a FixedPropVariant +func (t OneOfWithFixedDiscriminator) AsFixedPropVariant() (FixedPropVariant, error) { + var body FixedPropVariant + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromFixedPropVariant overwrites any union data inside the OneOfWithFixedDiscriminator as the provided FixedPropVariant +func (t *OneOfWithFixedDiscriminator) FromFixedPropVariant(v FixedPropVariant) error { + t.Type = "v_fixed" + + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeFixedPropVariant performs a merge with any union data inside the OneOfWithFixedDiscriminator, using the provided FixedPropVariant +func (t *OneOfWithFixedDiscriminator) MergeFixedPropVariant(v FixedPropVariant) error { + t.Type = "v_fixed" + + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t OneOfWithFixedDiscriminator) Discriminator() (string, error) { + var discriminator struct { + Discriminator string `json:"type"` + } + err := json.Unmarshal(t.union, &discriminator) + return discriminator.Discriminator, err +} + +func (t OneOfWithFixedDiscriminator) ValueByDiscriminator() (interface{}, error) { + discriminator, err := t.Discriminator() + if err != nil { + return nil, err + } + switch discriminator { + case "v1": + return t.AsVariant1() + case "v_fixed": + return t.AsFixedPropVariant() + default: + return nil, errors.New("unknown discriminator value: " + discriminator) + } +} + +func (t OneOfWithFixedDiscriminator) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + if err != nil { + return nil, err + } + object := make(map[string]json.RawMessage) + if t.union != nil { + err = json.Unmarshal(b, &object) + if err != nil { + return nil, err + } + } + + object["type"], err = json.Marshal(t.Type) + if err != nil { + return nil, fmt.Errorf("error marshaling 'type': %w", err) + } + + b, err = json.Marshal(object) + return b, err +} + +func (t *OneOfWithFixedDiscriminator) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + if err != nil { + return err + } + object := make(map[string]json.RawMessage) + err = json.Unmarshal(b, &object) + if err != nil { + return err + } + + if raw, found := object["type"]; found { + err = json.Unmarshal(raw, &t.Type) + if err != nil { + return fmt.Errorf("error reading 'type': %w", err) + } + } + + return err +} + +// AsVariant1 returns the union data inside the OneOfWithFixedProps as a Variant1 +func (t OneOfWithFixedProps) AsVariant1() (Variant1, error) { + var body Variant1 + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromVariant1 overwrites any union data inside the OneOfWithFixedProps as the provided Variant1 +func (t *OneOfWithFixedProps) FromVariant1(v Variant1) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeVariant1 performs a merge with any union data inside the OneOfWithFixedProps, using the provided Variant1 +func (t *OneOfWithFixedProps) MergeVariant1(v Variant1) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsVariant2 returns the union data inside the OneOfWithFixedProps as a Variant2 +func (t OneOfWithFixedProps) AsVariant2() (Variant2, error) { + var body Variant2 + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromVariant2 overwrites any union data inside the OneOfWithFixedProps as the provided Variant2 +func (t *OneOfWithFixedProps) FromVariant2(v Variant2) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeVariant2 performs a merge with any union data inside the OneOfWithFixedProps, using the provided Variant2 +func (t *OneOfWithFixedProps) MergeVariant2(v Variant2) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t OneOfWithFixedProps) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + if err != nil { + return nil, err + } + object := make(map[string]json.RawMessage) + if t.union != nil { + err = json.Unmarshal(b, &object) + if err != nil { + return nil, err + } + } + + if t.Fixed != nil { + object["fixed"], err = json.Marshal(t.Fixed) + if err != nil { + return nil, fmt.Errorf("error marshaling 'fixed': %w", err) + } + } + b, err = json.Marshal(object) + return b, err +} + +func (t *OneOfWithFixedProps) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + if err != nil { + return err + } + object := make(map[string]json.RawMessage) + err = json.Unmarshal(b, &object) + if err != nil { + return err + } + + if raw, found := object["fixed"]; found { + err = json.Unmarshal(raw, &t.Fixed) + if err != nil { + return fmt.Errorf("error reading 'fixed': %w", err) + } + } + + return err +} + +// AsDiscriminatedVariantA returns the union data inside the OneOfWithMapping as a DiscriminatedVariantA +func (t OneOfWithMapping) AsDiscriminatedVariantA() (DiscriminatedVariantA, error) { + var body DiscriminatedVariantA + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromDiscriminatedVariantA overwrites any union data inside the OneOfWithMapping as the provided DiscriminatedVariantA +func (t *OneOfWithMapping) FromDiscriminatedVariantA(v DiscriminatedVariantA) error { + v.Discriminator = "va" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeDiscriminatedVariantA performs a merge with any union data inside the OneOfWithMapping, using the provided DiscriminatedVariantA +func (t *OneOfWithMapping) MergeDiscriminatedVariantA(v DiscriminatedVariantA) error { + v.Discriminator = "va" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsDiscriminatedVariantB returns the union data inside the OneOfWithMapping as a DiscriminatedVariantB +func (t OneOfWithMapping) AsDiscriminatedVariantB() (DiscriminatedVariantB, error) { + var body DiscriminatedVariantB + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromDiscriminatedVariantB overwrites any union data inside the OneOfWithMapping as the provided DiscriminatedVariantB +func (t *OneOfWithMapping) FromDiscriminatedVariantB(v DiscriminatedVariantB) error { + v.Discriminator = "vb" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeDiscriminatedVariantB performs a merge with any union data inside the OneOfWithMapping, using the provided DiscriminatedVariantB +func (t *OneOfWithMapping) MergeDiscriminatedVariantB(v DiscriminatedVariantB) error { + v.Discriminator = "vb" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t OneOfWithMapping) Discriminator() (string, error) { + var discriminator struct { + Discriminator string `json:"discriminator"` + } + err := json.Unmarshal(t.union, &discriminator) + return discriminator.Discriminator, err +} + +func (t OneOfWithMapping) ValueByDiscriminator() (interface{}, error) { + discriminator, err := t.Discriminator() + if err != nil { + return nil, err + } + switch discriminator { + case "va": + return t.AsDiscriminatedVariantA() + case "vb": + return t.AsDiscriminatedVariantB() + default: + return nil, errors.New("unknown discriminator value: " + discriminator) + } +} + +func (t OneOfWithMapping) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *OneOfWithMapping) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} diff --git a/internal/test/aggregates/oneof/oneof_test.go b/internal/test/aggregates/oneof/oneof_test.go new file mode 100644 index 0000000000..6f555265e4 --- /dev/null +++ b/internal/test/aggregates/oneof/oneof_test.go @@ -0,0 +1,233 @@ +package oneof + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestBasicOneOfWithObject(t *testing.T) { + v := Variant1{Name: "test"} + + var o BasicOneOf + err := o.FromVariant1(v) + require.NoError(t, err) + + data, err := json.Marshal(o) + require.NoError(t, err) + + var roundTripped BasicOneOf + err = json.Unmarshal(data, &roundTripped) + require.NoError(t, err) + + got, err := roundTripped.AsVariant1() + require.NoError(t, err) + assert.Equal(t, "test", got.Name) +} + +func TestBasicOneOfWithArray(t *testing.T) { + var o BasicOneOf + err := o.FromVariant2(Variant2{1, 2, 3}) + require.NoError(t, err) + + data, err := json.Marshal(o) + require.NoError(t, err) + + var roundTripped BasicOneOf + err = json.Unmarshal(data, &roundTripped) + require.NoError(t, err) + + got, err := roundTripped.AsVariant2() + require.NoError(t, err) + assert.Equal(t, Variant2{1, 2, 3}, got) +} + +func TestBasicOneOfWithBoolean(t *testing.T) { + var o BasicOneOf + err := o.FromVariant3(true) + require.NoError(t, err) + + data, err := json.Marshal(o) + require.NoError(t, err) + assert.Equal(t, `true`, string(data)) +} + +func TestInlineOneOfWithObject(t *testing.T) { + label := "hello" + var o InlineOneOf + err := o.FromInlineOneOf0(InlineOneOf0{Label: &label}) + require.NoError(t, err) + + data, err := json.Marshal(o) + require.NoError(t, err) + + var roundTripped InlineOneOf + err = json.Unmarshal(data, &roundTripped) + require.NoError(t, err) + + got, err := roundTripped.AsInlineOneOf0() + require.NoError(t, err) + assert.Equal(t, "hello", *got.Label) +} + +func TestOneOfWithDiscriminator(t *testing.T) { + va := DiscriminatedVariantA{Discriminator: "DiscriminatedVariantA", Name: "test-a"} + var o OneOfWithDiscriminator + err := o.FromDiscriminatedVariantA(va) + require.NoError(t, err) + + disc, err := o.Discriminator() + require.NoError(t, err) + assert.Equal(t, "DiscriminatedVariantA", disc) + + val, err := o.ValueByDiscriminator() + require.NoError(t, err) + got, ok := val.(DiscriminatedVariantA) + require.True(t, ok) + assert.Equal(t, "test-a", got.Name) +} + +func TestOneOfWithDiscriminatorVariantB(t *testing.T) { + vb := DiscriminatedVariantB{Discriminator: "DiscriminatedVariantB", Id: 42} + var o OneOfWithDiscriminator + err := o.FromDiscriminatedVariantB(vb) + require.NoError(t, err) + + disc, err := o.Discriminator() + require.NoError(t, err) + assert.Equal(t, "DiscriminatedVariantB", disc) + + val, err := o.ValueByDiscriminator() + require.NoError(t, err) + got, ok := val.(DiscriminatedVariantB) + require.True(t, ok) + assert.Equal(t, 42, got.Id) +} + +func TestOneOfWithMapping(t *testing.T) { + va := DiscriminatedVariantA{Discriminator: "va", Name: "mapped-a"} + var o OneOfWithMapping + err := o.FromDiscriminatedVariantA(va) + require.NoError(t, err) + + disc, err := o.Discriminator() + require.NoError(t, err) + assert.Equal(t, "va", disc) + + val, err := o.ValueByDiscriminator() + require.NoError(t, err) + got, ok := val.(DiscriminatedVariantA) + require.True(t, ok) + assert.Equal(t, "mapped-a", got.Name) +} + +func TestOneOfWithFixedProps(t *testing.T) { + var o OneOfWithFixedProps + err := o.FromVariant1(Variant1{Name: "test"}) + require.NoError(t, err) + + data, err := json.Marshal(o) + require.NoError(t, err) + + var roundTripped OneOfWithFixedProps + err = json.Unmarshal(data, &roundTripped) + require.NoError(t, err) + + got, err := roundTripped.AsVariant1() + require.NoError(t, err) + assert.Equal(t, "test", got.Name) +} + +func TestOneOfWithFixedDiscriminator(t *testing.T) { + v := Variant1{Name: "named"} + var o OneOfWithFixedDiscriminator + err := o.FromVariant1(v) + require.NoError(t, err) + + data, err := json.Marshal(o) + require.NoError(t, err) + + var roundTripped OneOfWithFixedDiscriminator + err = json.Unmarshal(data, &roundTripped) + require.NoError(t, err) + + got, err := roundTripped.AsVariant1() + require.NoError(t, err) + assert.Equal(t, "named", got.Name) +} + +func TestArrayOfOneOf(t *testing.T) { + var item1 ArrayOfOneOf_Item + err := item1.FromVariant1(Variant1{Name: "first"}) + require.NoError(t, err) + + var item2 ArrayOfOneOf_Item + err = item2.FromVariant2(Variant2{10, 20}) + require.NoError(t, err) + + arr := ArrayOfOneOf{item1, item2} + data, err := json.Marshal(arr) + require.NoError(t, err) + + var roundTripped ArrayOfOneOf + err = json.Unmarshal(data, &roundTripped) + require.NoError(t, err) + require.Len(t, roundTripped, 2) + + got1, err := roundTripped[0].AsVariant1() + require.NoError(t, err) + assert.Equal(t, "first", got1.Name) + + got2, err := roundTripped[1].AsVariant2() + require.NoError(t, err) + assert.Equal(t, Variant2{10, 20}, got2) +} + +// From issue-1530: multiple discriminator values mapping to the same type. +func TestOneOfMultiMappingHttpVariants(t *testing.T) { + testCases := []string{"apache_server", "web_server"} + for _, configType := range testCases { + t.Run(configType, func(t *testing.T) { + http := ConfigHttp{ConfigType: configType, Url: "http://example.com"} + var o OneOfMultiMapping + err := o.FromConfigHttp(http) + require.NoError(t, err) + + disc, err := o.Discriminator() + require.NoError(t, err) + assert.Equal(t, configType, disc) + + val, err := o.ValueByDiscriminator() + require.NoError(t, err) + gotHttp, ok := val.(ConfigHttp) + require.True(t, ok) + assert.Equal(t, "http://example.com", gotHttp.Url) + }) + } +} + +func TestOneOfMultiMappingSsh(t *testing.T) { + ssh := ConfigSsh{ConfigType: "ssh_server", Host: "server.example.com"} + var o OneOfMultiMapping + err := o.FromConfigSsh(ssh) + require.NoError(t, err) + + disc, err := o.Discriminator() + require.NoError(t, err) + assert.Equal(t, "ssh_server", disc) + + val, err := o.ValueByDiscriminator() + require.NoError(t, err) + gotSsh, ok := val.(ConfigSsh) + require.True(t, ok) + assert.Equal(t, "server.example.com", gotSsh.Host) +} + +func TestOneOfMarshalWithNoValueSet(t *testing.T) { + var o BasicOneOf + data, err := json.Marshal(o) + require.NoError(t, err) + assert.Equal(t, "null", string(data)) +} diff --git a/internal/test/aggregates/oneof/spec.yaml b/internal/test/aggregates/oneof/spec.yaml new file mode 100644 index 0000000000..50f9e1fead --- /dev/null +++ b/internal/test/aggregates/oneof/spec.yaml @@ -0,0 +1,174 @@ +openapi: "3.0.1" +info: + version: 1.0.0 + title: OneOf Types + description: Tests oneOf with discriminators, mappings, fixed properties +paths: + /ensure-everything-is-referenced: + get: + operationId: ensureEverythingIsReferenced + responses: + "200": + description: placeholder + content: + application/json: + schema: + type: object + properties: + basic: + $ref: "#/components/schemas/BasicOneOf" + inline: + $ref: "#/components/schemas/InlineOneOf" + withDiscriminator: + $ref: "#/components/schemas/OneOfWithDiscriminator" + withMapping: + $ref: "#/components/schemas/OneOfWithMapping" + fixedProps: + $ref: "#/components/schemas/OneOfWithFixedProps" + fixedDiscriminator: + $ref: "#/components/schemas/OneOfWithFixedDiscriminator" + arrayOfOneOf: + $ref: "#/components/schemas/ArrayOfOneOf" + multiMapping: + $ref: "#/components/schemas/OneOfMultiMapping" +components: + schemas: + # Variants + Variant1: + type: object + properties: + name: + type: string + required: [name] + Variant2: + type: array + items: + type: integer + Variant3: + type: boolean + + DiscriminatedVariantA: + type: object + properties: + discriminator: + type: string + name: + type: string + required: [discriminator, name] + DiscriminatedVariantB: + type: object + properties: + discriminator: + type: string + id: + type: integer + required: [discriminator, id] + + FixedPropVariant: + type: object + properties: + values: + $ref: "#/components/schemas/Variant2" + required: [values] + + # oneOf without discriminator + BasicOneOf: + description: oneOf with references, no discriminator + oneOf: + - $ref: "#/components/schemas/Variant1" + - $ref: "#/components/schemas/Variant2" + - $ref: "#/components/schemas/Variant3" + + # oneOf with inline elements + InlineOneOf: + description: oneOf with inline elements + oneOf: + - type: object + properties: + label: + type: string + - type: array + items: + type: number + - type: boolean + + # oneOf with discriminator but no mapping + OneOfWithDiscriminator: + oneOf: + - $ref: "#/components/schemas/DiscriminatedVariantA" + - $ref: "#/components/schemas/DiscriminatedVariantB" + discriminator: + propertyName: discriminator + + # oneOf with discriminator and mapping + OneOfWithMapping: + oneOf: + - $ref: "#/components/schemas/DiscriminatedVariantA" + - $ref: "#/components/schemas/DiscriminatedVariantB" + discriminator: + propertyName: discriminator + mapping: + va: "#/components/schemas/DiscriminatedVariantA" + vb: "#/components/schemas/DiscriminatedVariantB" + + # oneOf with fixed properties + OneOfWithFixedProps: + type: object + properties: + fixed: + type: string + oneOf: + - $ref: "#/components/schemas/Variant1" + - $ref: "#/components/schemas/Variant2" + + # oneOf with fixed discriminator + OneOfWithFixedDiscriminator: + type: object + properties: + type: + type: string + oneOf: + - $ref: "#/components/schemas/Variant1" + - $ref: "#/components/schemas/FixedPropVariant" + discriminator: + propertyName: type + mapping: + v1: "#/components/schemas/Variant1" + v_fixed: "#/components/schemas/FixedPropVariant" + required: [type] + + # Array of oneOf + ArrayOfOneOf: + type: array + items: + oneOf: + - $ref: "#/components/schemas/Variant1" + - $ref: "#/components/schemas/Variant2" + + # From issue-1530: multiple discriminator values mapping to same type + ConfigHttp: + type: object + properties: + config_type: + type: string + url: + type: string + required: [config_type, url] + ConfigSsh: + type: object + properties: + config_type: + type: string + host: + type: string + required: [config_type, host] + OneOfMultiMapping: + oneOf: + - $ref: "#/components/schemas/ConfigHttp" + - $ref: "#/components/schemas/ConfigSsh" + discriminator: + propertyName: config_type + mapping: + ssh_server: "#/components/schemas/ConfigSsh" + apache_server: "#/components/schemas/ConfigHttp" + web_server: "#/components/schemas/ConfigHttp" diff --git a/internal/test/all_of/config1.yaml b/internal/test/all_of/config1.yaml deleted file mode 100644 index 1cc8fe87c7..0000000000 --- a/internal/test/all_of/config1.yaml +++ /dev/null @@ -1,10 +0,0 @@ -# yaml-language-server: $schema=../../../configuration-schema.json -package: v1 -generate: - models: true - embedded-spec: true -compatibility: - old-merge-schemas: true -output-options: - skip-prune: true -output: v1/openapi.gen.go diff --git a/internal/test/all_of/config2.yaml b/internal/test/all_of/config2.yaml deleted file mode 100644 index b5b9d64be7..0000000000 --- a/internal/test/all_of/config2.yaml +++ /dev/null @@ -1,8 +0,0 @@ -# yaml-language-server: $schema=../../../configuration-schema.json -package: v2 -generate: - models: true - embedded-spec: true -output-options: - skip-prune: true -output: v2/openapi.gen.go diff --git a/internal/test/all_of/doc.go b/internal/test/all_of/doc.go deleted file mode 100644 index b154cb2245..0000000000 --- a/internal/test/all_of/doc.go +++ /dev/null @@ -1,4 +0,0 @@ -package allof - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config1.yaml openapi.yaml -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config2.yaml openapi.yaml diff --git a/internal/test/all_of/openapi.yaml b/internal/test/all_of/openapi.yaml deleted file mode 100644 index f73a8e5f1b..0000000000 --- a/internal/test/all_of/openapi.yaml +++ /dev/null @@ -1,53 +0,0 @@ -openapi: "3.0.1" -info: - version: 1.0.0 - title: Tests AllOf composition -paths: - /placeholder: - get: - operationId: placeholder - description: | - Validators want at least one path, so this makes them happy. - responses: - default: - description: placeholder - content: - application/json: - schema: - $ref: "#/components/schemas/PersonWithID" -components: - schemas: - PersonProperties: - type: object - description: | - These are fields that specify a person. They are all optional, and - would be used by an `Edit` style API endpoint, where each is optional. - properties: - FirstName: - type: string - LastName: - type: string - GovernmentIDNumber: - type: integer - format: int64 - Person: - type: object - description: | - This is a person, with mandatory first and last name, but optional ID - number. This would be returned by a `Get` style API. We merge the person - properties with another Schema which only provides required fields. - allOf: - - $ref: "#/components/schemas/PersonProperties" - - required: [ FirstName, LastName ] - PersonWithID: - type: object - description: | - This is a person record as returned from a Create endpoint. It contains - all the fields of a Person, with an additional resource UUID. - allOf: - - $ref: "#/components/schemas/Person" - - properties: - ID: - type: integer - format: int64 - required: [ ID ] diff --git a/internal/test/all_of/v1/openapi.gen.go b/internal/test/all_of/v1/openapi.gen.go deleted file mode 100644 index db5fd302cd..0000000000 --- a/internal/test/all_of/v1/openapi.gen.go +++ /dev/null @@ -1,127 +0,0 @@ -// Package v1 provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package v1 - -import ( - "bytes" - "compress/gzip" - "encoding/base64" - "fmt" - "net/url" - "path" - "strings" - - "github.com/getkin/kin-openapi/openapi3" -) - -// Person defines model for Person. -type Person struct { - // Embedded struct due to allOf(#/components/schemas/PersonProperties) - PersonProperties `yaml:",inline"` - // Embedded fields due to inline allOf schema -} - -// PersonProperties These are fields that specify a person. They are all optional, and -// would be used by an `Edit` style API endpoint, where each is optional. -type PersonProperties struct { - FirstName *string `json:"FirstName,omitempty"` - GovernmentIDNumber *int64 `json:"GovernmentIDNumber,omitempty"` - LastName *string `json:"LastName,omitempty"` -} - -// PersonWithID defines model for PersonWithID. -type PersonWithID struct { - // Embedded struct due to allOf(#/components/schemas/Person) - Person `yaml:",inline"` - // Embedded fields due to inline allOf schema - ID int64 `json:"ID"` -} - -// Base64 encoded, gzipped, json marshaled Swagger object -var swaggerSpec = []string{ - - "H4sIAAAAAAAC/5SUT2/bOBDFv8qAu0dBTrCLPegWrNtAQJEaaNIc4gAZSyOLKTVkyVEMwfB3L0jJ/+AW", - "aX0awOTjvDe/0VZVtnOWiSWoYqtC1VKHqVyQD5ZjhcZ8blTxtFV/e2pUof6aHW/Npiuz8fzCW0deNAW1", - "y7bK0/dee6pV8aQ+ah/kDjtSmfqEU/m8e85UTaHy2omO76n7VgfQARBcksxgo6WFDrlGsX6AJgoBcg0G", - "gwBjRxmsegGbJNBAOV8y992KfA5JbmN7U8OKwJP0nqmG1QAIL7ckLxBkMAQ3izKHR4KO/JpAWpqeX7I7", - "eBo7QbbSkocvyTlsWl21YNkM4Lx90zUF2PuGRpOpQ75klSkZHKlC2dUrVaJ2mbqIrNheZEGBAD1NQiAt", - "CgRHlW6GQ0LRJA3pGBpziCGLGS354L0Pk2+Glw+1PnUOxLWzmiWDTUuegLBq4xD2WqMDd9bqcaDFdm8u", - "iNe8juZu7Rt57oilnN+lWcRjjfUdiiqUZvnv32MomoXW5OPFAxuXqrtfhviopS3nf0prYvTc1Cjybpu7", - "7Iztcv47JIOnyvoaMBw5bLztAOF/Tyh0GEMOpUBlWVBzWHKcaiRygsA2gLA4XQ5kwLrWE/6egu19RfDw", - "UM5/yl7sX3NjU8ZaTPzvnoIEuInxQUosJD2VqTfyYXR0nV/lVzF164jRaVWof/Kr/DqygdKmBGfOYEWt", - "NfU48jXJJdhf0ei0zgE2yAIoYChus2WCKJVBsCAxwA6/UQSfOmjRuWE0FGeGUaysVaEWJ0/GyQRnOewX", - "qsHepBZioMSpROeMrpLA7HX6zo1sxOp9cibeUpDnzk7d79LvRwAAAP//lzc18GUFAAA=", -} - -// GetSwagger returns the content of the embedded swagger specification file -// or error if failed to decode -func decodeSpec() ([]byte, error) { - zipped, err := base64.StdEncoding.DecodeString(strings.Join(swaggerSpec, "")) - if err != nil { - return nil, fmt.Errorf("error base64 decoding spec: %w", err) - } - zr, err := gzip.NewReader(bytes.NewReader(zipped)) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - var buf bytes.Buffer - _, err = buf.ReadFrom(zr) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - - return buf.Bytes(), nil -} - -var rawSpec = decodeSpecCached() - -// a naive cached of a decoded swagger spec -func decodeSpecCached() func() ([]byte, error) { - data, err := decodeSpec() - return func() ([]byte, error) { - return data, err - } -} - -// Constructs a synthetic filesystem for resolving external references when loading openapi specifications. -func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { - res := make(map[string]func() ([]byte, error)) - if len(pathToFile) > 0 { - res[pathToFile] = rawSpec - } - - return res -} - -// GetSwagger returns the Swagger specification corresponding to the generated code -// in this file. The external references of Swagger specification are resolved. -// The logic of resolving external references is tightly connected to "import-mapping" feature. -// Externally referenced files must be embedded in the corresponding golang packages. -// Urls can be supported but this task was out of the scope. -func GetSwagger() (swagger *openapi3.T, err error) { - resolvePath := PathToRawSpec("") - - loader := openapi3.NewLoader() - loader.IsExternalRefsAllowed = true - loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() - pathToFile = path.Clean(pathToFile) - getSpec, ok := resolvePath[pathToFile] - if !ok { - err1 := fmt.Errorf("path not found: %s", pathToFile) - return nil, err1 - } - return getSpec() - } - var specData []byte - specData, err = rawSpec() - if err != nil { - return - } - swagger, err = loader.LoadFromData(specData) - if err != nil { - return - } - return -} diff --git a/internal/test/all_of/v2/openapi.gen.go b/internal/test/all_of/v2/openapi.gen.go deleted file mode 100644 index ab430340d6..0000000000 --- a/internal/test/all_of/v2/openapi.gen.go +++ /dev/null @@ -1,127 +0,0 @@ -// Package v2 provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package v2 - -import ( - "bytes" - "compress/gzip" - "encoding/base64" - "fmt" - "net/url" - "path" - "strings" - - "github.com/getkin/kin-openapi/openapi3" -) - -// Person defines model for Person. -type Person struct { - FirstName string `json:"FirstName"` - GovernmentIDNumber *int64 `json:"GovernmentIDNumber,omitempty"` - LastName string `json:"LastName"` -} - -// PersonProperties These are fields that specify a person. They are all optional, and -// would be used by an `Edit` style API endpoint, where each is optional. -type PersonProperties struct { - FirstName *string `json:"FirstName,omitempty"` - GovernmentIDNumber *int64 `json:"GovernmentIDNumber,omitempty"` - LastName *string `json:"LastName,omitempty"` -} - -// PersonWithID defines model for PersonWithID. -type PersonWithID struct { - FirstName string `json:"FirstName"` - GovernmentIDNumber *int64 `json:"GovernmentIDNumber,omitempty"` - ID int64 `json:"ID"` - LastName string `json:"LastName"` -} - -// Base64 encoded, gzipped, json marshaled Swagger object -var swaggerSpec = []string{ - - "H4sIAAAAAAAC/5SUT2/bOBDFv8qAu0dBTrCLPegWrNtAQJEaaNIc4gAZSyOLKTVkyVEMwfB3L0jJ/+AW", - "aX0awOTjvDe/0VZVtnOWiSWoYqtC1VKHqVyQD5ZjhcZ8blTxtFV/e2pUof6aHW/Npiuz8fzCW0deNAW1", - "y7bK0/dee6pV8aQ+ah/kDjtSmfqEU/m8e85UTaHy2omO76n7VgfQARBcksxgo6WFDrlGsX6AJgoBcg0G", - "gwBjRxmsegGbJNBAOV8y992KfA5JbmN7U8OKwJP0nqmG1QAIL7ckLxBkMAQ3izKHR4KO/JpAWpqeX7I7", - "eBo7QbbSkocvyTlsWl21YNkM4Lx90zUF2PuGRpOpQ75klSkZHKlC2dUrVaJ2mbqIrNheZEGBAD1NQiAt", - "CgRHlW6GQ0LRJA3pGBpziCGLGS354L0Pk2+Glw+1PnUOxLWzmiWDTUuegLBq4xD2WqMDd9bqcaDFdm8u", - "iNe8juZu7Rt57oilnN+lWcRjjfUdiiqUZvnv32MomoXW5OPFAxuXqrtfhviopS3nf0prYvTc1Cjybpu7", - "7Iztcv47JIOnyvoaMBw5bLztAOF/Tyh0GEMOpUBlWVBzWHKcaiRygsA2gLA4XQ5kwLrWE/6egu19RfDw", - "UM5/yl7sX3NjU8ZaTPzvnoIEuInxQUosJD2VqTfyYXR0nV/lVzF164jRaVWof/Kr/DqygdKmBGfOYEWt", - "NfU48jXJJdhf0ei0zgE2yAIoYChus2WCKJVBsCAxwA6/UQSfOmjRuWE0FGeGUaysVaEWJ0/GyQRnOewX", - "qsHepBZioMSpROeMrpLA7HX6zo1sxOp9cibeUpDnzk7d79LvRwAAAP//lzc18GUFAAA=", -} - -// GetSwagger returns the content of the embedded swagger specification file -// or error if failed to decode -func decodeSpec() ([]byte, error) { - zipped, err := base64.StdEncoding.DecodeString(strings.Join(swaggerSpec, "")) - if err != nil { - return nil, fmt.Errorf("error base64 decoding spec: %w", err) - } - zr, err := gzip.NewReader(bytes.NewReader(zipped)) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - var buf bytes.Buffer - _, err = buf.ReadFrom(zr) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - - return buf.Bytes(), nil -} - -var rawSpec = decodeSpecCached() - -// a naive cached of a decoded swagger spec -func decodeSpecCached() func() ([]byte, error) { - data, err := decodeSpec() - return func() ([]byte, error) { - return data, err - } -} - -// Constructs a synthetic filesystem for resolving external references when loading openapi specifications. -func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { - res := make(map[string]func() ([]byte, error)) - if len(pathToFile) > 0 { - res[pathToFile] = rawSpec - } - - return res -} - -// GetSwagger returns the Swagger specification corresponding to the generated code -// in this file. The external references of Swagger specification are resolved. -// The logic of resolving external references is tightly connected to "import-mapping" feature. -// Externally referenced files must be embedded in the corresponding golang packages. -// Urls can be supported but this task was out of the scope. -func GetSwagger() (swagger *openapi3.T, err error) { - resolvePath := PathToRawSpec("") - - loader := openapi3.NewLoader() - loader.IsExternalRefsAllowed = true - loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() - pathToFile = path.Clean(pathToFile) - getSpec, ok := resolvePath[pathToFile] - if !ok { - err1 := fmt.Errorf("path not found: %s", pathToFile) - return nil, err1 - } - return getSpec() - } - var specData []byte - specData, err = rawSpec() - if err != nil { - return - } - swagger, err = loader.LoadFromData(specData) - if err != nil { - return - } - return -} diff --git a/internal/test/any_of/codegen/inline/config.yaml b/internal/test/any_of/codegen/inline/config.yaml deleted file mode 100644 index 9066c3fa38..0000000000 --- a/internal/test/any_of/codegen/inline/config.yaml +++ /dev/null @@ -1,6 +0,0 @@ -package: inline -generate: - models: true - client: true - echo-server: true -output: openapi.gen.go diff --git a/internal/test/any_of/codegen/inline/spec.yaml b/internal/test/any_of/codegen/inline/spec.yaml deleted file mode 100644 index bb0e44448c..0000000000 --- a/internal/test/any_of/codegen/inline/spec.yaml +++ /dev/null @@ -1,81 +0,0 @@ -openapi: 3.0.0 -info: - version: 1.0.0 - title: Cats, Dogs and Rats API - description: This API allows the client to receive information about cats, dogs and rats. -servers: - - url: https://example.com/api -security: - - ApiKeyAuth: [] -paths: - /pets: - get: - summary: Get a list of pets - description: This endpoint returns a list of pets. Each pet can be either a cat, dog or a rat. - operationId: getPets - responses: - '200': - description: Successful response - content: - application/json: - schema: - type: object - properties: - data: - type: array - items: - anyOf: - - $ref: '#/components/schemas/Cat' - - $ref: '#/components/schemas/Dog' - - $ref: '#/components/schemas/Rat' - '401': - description: Unauthorized - '500': - description: Internal Server Error -components: - securitySchemes: - ApiKeyAuth: - type: apiKey - in: header - name: X-API-Key - schemas: - Cat: - type: object - description: This is a cat - properties: - id: - type: string - name: - type: string - breed: - type: string - color: - type: string - purrs: - type: boolean - Dog: - type: object - description: This is a dog - properties: - id: - type: string - name: - type: string - breed: - type: string - color: - type: string - barks: - type: boolean - Rat: - type: object - description: This is a rat - properties: - id: - type: string - name: - type: string - color: - type: string - squeaks: - type: boolean diff --git a/internal/test/any_of/codegen/ref_schema/config.yaml b/internal/test/any_of/codegen/ref_schema/config.yaml deleted file mode 100644 index 07176c2906..0000000000 --- a/internal/test/any_of/codegen/ref_schema/config.yaml +++ /dev/null @@ -1,6 +0,0 @@ -package: ref_schema -generate: - models: true - client: true - echo-server: true -output: openapi.gen.go diff --git a/internal/test/any_of/codegen/ref_schema/generate.go b/internal/test/any_of/codegen/ref_schema/generate.go deleted file mode 100644 index 061e2a828d..0000000000 --- a/internal/test/any_of/codegen/ref_schema/generate.go +++ /dev/null @@ -1,3 +0,0 @@ -package ref_schema - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml spec.yaml diff --git a/internal/test/any_of/codegen/ref_schema/openapi.gen.go b/internal/test/any_of/codegen/ref_schema/openapi.gen.go deleted file mode 100644 index 38f87c47be..0000000000 --- a/internal/test/any_of/codegen/ref_schema/openapi.gen.go +++ /dev/null @@ -1,420 +0,0 @@ -// Package ref_schema provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package ref_schema - -import ( - "context" - "encoding/json" - "fmt" - "io" - "net/http" - "net/url" - "strings" - - "github.com/labstack/echo/v4" - "github.com/oapi-codegen/runtime" -) - -const ( - ApiKeyAuthScopes = "ApiKeyAuth.Scopes" -) - -// Cat This is a cat -type Cat struct { - Breed *string `json:"breed,omitempty"` - Color *string `json:"color,omitempty"` - Id *string `json:"id,omitempty"` - Name *string `json:"name,omitempty"` - Purrs *bool `json:"purrs,omitempty"` -} - -// Dog This is a dog -type Dog struct { - Barks *bool `json:"barks,omitempty"` - Breed *string `json:"breed,omitempty"` - Color *string `json:"color,omitempty"` - Id *string `json:"id,omitempty"` - Name *string `json:"name,omitempty"` -} - -// GetPetsDto defines model for GetPetsDto. -type GetPetsDto struct { - Data *GetPetsDto_Data `json:"data,omitempty"` -} - -// GetPetsDto_Data defines model for GetPetsDto.Data. -type GetPetsDto_Data struct { - union json.RawMessage -} - -// Rat This is a rat -type Rat struct { - Color *string `json:"color,omitempty"` - Id *string `json:"id,omitempty"` - Name *string `json:"name,omitempty"` - Squeaks *bool `json:"squeaks,omitempty"` -} - -// AsCat returns the union data inside the GetPetsDto_Data as a Cat -func (t GetPetsDto_Data) AsCat() (Cat, error) { - var body Cat - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromCat overwrites any union data inside the GetPetsDto_Data as the provided Cat -func (t *GetPetsDto_Data) FromCat(v Cat) error { - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeCat performs a merge with any union data inside the GetPetsDto_Data, using the provided Cat -func (t *GetPetsDto_Data) MergeCat(v Cat) error { - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -// AsDog returns the union data inside the GetPetsDto_Data as a Dog -func (t GetPetsDto_Data) AsDog() (Dog, error) { - var body Dog - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromDog overwrites any union data inside the GetPetsDto_Data as the provided Dog -func (t *GetPetsDto_Data) FromDog(v Dog) error { - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeDog performs a merge with any union data inside the GetPetsDto_Data, using the provided Dog -func (t *GetPetsDto_Data) MergeDog(v Dog) error { - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -// AsRat returns the union data inside the GetPetsDto_Data as a Rat -func (t GetPetsDto_Data) AsRat() (Rat, error) { - var body Rat - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromRat overwrites any union data inside the GetPetsDto_Data as the provided Rat -func (t *GetPetsDto_Data) FromRat(v Rat) error { - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeRat performs a merge with any union data inside the GetPetsDto_Data, using the provided Rat -func (t *GetPetsDto_Data) MergeRat(v Rat) error { - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -func (t GetPetsDto_Data) MarshalJSON() ([]byte, error) { - b, err := t.union.MarshalJSON() - return b, err -} - -func (t *GetPetsDto_Data) UnmarshalJSON(b []byte) error { - err := t.union.UnmarshalJSON(b) - return err -} - -// RequestEditorFn is the function signature for the RequestEditor callback function -type RequestEditorFn func(ctx context.Context, req *http.Request) error - -// Doer performs HTTP requests. -// -// The standard http.Client implements this interface. -type HttpRequestDoer interface { - Do(req *http.Request) (*http.Response, error) -} - -// Client which conforms to the OpenAPI3 specification for this service. -type Client struct { - // The endpoint of the server conforming to this interface, with scheme, - // https://api.deepmap.com for example. This can contain a path relative - // to the server, such as https://api.deepmap.com/dev-test, and all the - // paths in the swagger spec will be appended to the server. - Server string - - // Doer for performing requests, typically a *http.Client with any - // customized settings, such as certificate chains. - Client HttpRequestDoer - - // A list of callbacks for modifying requests which are generated before sending over - // the network. - RequestEditors []RequestEditorFn -} - -// ClientOption allows setting custom parameters during construction -type ClientOption func(*Client) error - -// Creates a new Client, with reasonable defaults -func NewClient(server string, opts ...ClientOption) (*Client, error) { - // create a client with sane default values - client := Client{ - Server: server, - } - // mutate client and add all optional params - for _, o := range opts { - if err := o(&client); err != nil { - return nil, err - } - } - // ensure the server URL always has a trailing slash - if !strings.HasSuffix(client.Server, "/") { - client.Server += "/" - } - // create httpClient, if not already present - if client.Client == nil { - client.Client = &http.Client{} - } - return &client, nil -} - -// WithHTTPClient allows overriding the default Doer, which is -// automatically created using http.Client. This is useful for tests. -func WithHTTPClient(doer HttpRequestDoer) ClientOption { - return func(c *Client) error { - c.Client = doer - return nil - } -} - -// WithRequestEditorFn allows setting up a callback function, which will be -// called right before sending the request. This can be used to mutate the request. -func WithRequestEditorFn(fn RequestEditorFn) ClientOption { - return func(c *Client) error { - c.RequestEditors = append(c.RequestEditors, fn) - return nil - } -} - -// The interface specification for the client above. -type ClientInterface interface { - // GetPets request - GetPets(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) -} - -func (c *Client) GetPets(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewGetPetsRequest(c.Server) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -// NewGetPetsRequest generates requests for GetPets -func NewGetPetsRequest(server string) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/pets") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -func (c *Client) applyEditors(ctx context.Context, req *http.Request, additionalEditors []RequestEditorFn) error { - for _, r := range c.RequestEditors { - if err := r(ctx, req); err != nil { - return err - } - } - for _, r := range additionalEditors { - if err := r(ctx, req); err != nil { - return err - } - } - return nil -} - -// ClientWithResponses builds on ClientInterface to offer response payloads -type ClientWithResponses struct { - ClientInterface -} - -// NewClientWithResponses creates a new ClientWithResponses, which wraps -// Client with return type handling -func NewClientWithResponses(server string, opts ...ClientOption) (*ClientWithResponses, error) { - client, err := NewClient(server, opts...) - if err != nil { - return nil, err - } - return &ClientWithResponses{client}, nil -} - -// WithBaseURL overrides the baseURL. -func WithBaseURL(baseURL string) ClientOption { - return func(c *Client) error { - newBaseURL, err := url.Parse(baseURL) - if err != nil { - return err - } - c.Server = newBaseURL.String() - return nil - } -} - -// ClientWithResponsesInterface is the interface specification for the client with responses above. -type ClientWithResponsesInterface interface { - // GetPetsWithResponse request - GetPetsWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*GetPetsResponse, error) -} - -type GetPetsResponse struct { - Body []byte - HTTPResponse *http.Response - JSON200 *GetPetsDto -} - -// Status returns HTTPResponse.Status -func (r GetPetsResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r GetPetsResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -// GetPetsWithResponse request returning *GetPetsResponse -func (c *ClientWithResponses) GetPetsWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*GetPetsResponse, error) { - rsp, err := c.GetPets(ctx, reqEditors...) - if err != nil { - return nil, err - } - return ParseGetPetsResponse(rsp) -} - -// ParseGetPetsResponse parses an HTTP response from a GetPetsWithResponse call -func ParseGetPetsResponse(rsp *http.Response) (*GetPetsResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &GetPetsResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest GetPetsDto - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON200 = &dest - - } - - return response, nil -} - -// ServerInterface represents all server handlers. -type ServerInterface interface { - // Get a list of pets - // (GET /pets) - GetPets(ctx echo.Context) error -} - -// ServerInterfaceWrapper converts echo contexts to parameters. -type ServerInterfaceWrapper struct { - Handler ServerInterface -} - -// GetPets converts echo context to params. -func (w *ServerInterfaceWrapper) GetPets(ctx echo.Context) error { - var err error - - ctx.Set(ApiKeyAuthScopes, []string{}) - - // Invoke the callback with all the unmarshaled arguments - err = w.Handler.GetPets(ctx) - return err -} - -// This is a simple interface which specifies echo.Route addition functions which -// are present on both echo.Echo and echo.Group, since we want to allow using -// either of them for path registration -type EchoRouter interface { - CONNECT(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - DELETE(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - GET(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - HEAD(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - OPTIONS(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - PATCH(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - POST(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - PUT(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - TRACE(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route -} - -// RegisterHandlers adds each server route to the EchoRouter. -func RegisterHandlers(router EchoRouter, si ServerInterface) { - RegisterHandlersWithBaseURL(router, si, "") -} - -// Registers handlers, and prepends BaseURL to the paths, so that the paths -// can be served under a prefix. -func RegisterHandlersWithBaseURL(router EchoRouter, si ServerInterface, baseURL string) { - - wrapper := ServerInterfaceWrapper{ - Handler: si, - } - - router.GET(baseURL+"/pets", wrapper.GetPets) - -} diff --git a/internal/test/any_of/codegen/ref_schema/spec.yaml b/internal/test/any_of/codegen/ref_schema/spec.yaml deleted file mode 100644 index f571db0134..0000000000 --- a/internal/test/any_of/codegen/ref_schema/spec.yaml +++ /dev/null @@ -1,81 +0,0 @@ -openapi: 3.0.0 -info: - version: 1.0.0 - title: Cats, Dogs and Rats API - description: This API allows the client to receive information about cats, dogs and rats. -servers: - - url: https://example.com/api -security: - - ApiKeyAuth: [] -paths: - /pets: - get: - summary: Get a list of pets - description: This endpoint returns a list of pets. Each pet can be either a cat, dog or a rat. - operationId: getPets - responses: - '200': - description: Successful response - content: - application/json: - schema: - $ref: '#/components/schemas/GetPetsDto' - '401': - description: Unauthorized - '500': - description: Internal Server Error -components: - securitySchemes: - ApiKeyAuth: - type: apiKey - in: header - name: X-API-Key - schemas: - GetPetsDto: - type: object - properties: - data: - anyOf: - - $ref: '#/components/schemas/Cat' - - $ref: '#/components/schemas/Dog' - - $ref: '#/components/schemas/Rat' - Cat: - type: object - description: This is a cat - properties: - id: - type: string - name: - type: string - breed: - type: string - color: - type: string - purrs: - type: boolean - Dog: - type: object - description: This is a dog - properties: - id: - type: string - name: - type: string - breed: - type: string - color: - type: string - barks: - type: boolean - Rat: - type: object - description: This is a rat - properties: - id: - type: string - name: - type: string - color: - type: string - squeaks: - type: boolean diff --git a/internal/test/any_of/param/param.gen.go b/internal/test/any_of/param/param.gen.go deleted file mode 100644 index 483228d045..0000000000 --- a/internal/test/any_of/param/param.gen.go +++ /dev/null @@ -1,421 +0,0 @@ -// Package param provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package param - -import ( - "context" - "encoding/json" - "fmt" - "io" - "net/http" - "net/url" - "strings" - - "github.com/oapi-codegen/runtime" -) - -// Test defines model for test. -type Test struct { - union json.RawMessage -} - -// Test0 defines model for . -type Test0 struct { - Item1 string `json:"item1"` - Item2 string `json:"item2"` -} - -// Test1 defines model for . -type Test1 struct { - Item2 *string `json:"item2,omitempty"` - Item3 *string `json:"item3,omitempty"` -} - -// Test2 defines model for test2. -type Test2 struct { - union json.RawMessage -} - -// Test20 defines model for . -type Test20 = int - -// Test21 defines model for . -type Test21 = string - -// GetTestParams defines parameters for GetTest. -type GetTestParams struct { - Test *Test `form:"test,omitempty" json:"test,omitempty"` - Test2 *[]Test2 `form:"test2,omitempty" json:"test2,omitempty"` -} - -// AsTest0 returns the union data inside the Test as a Test0 -func (t Test) AsTest0() (Test0, error) { - var body Test0 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromTest0 overwrites any union data inside the Test as the provided Test0 -func (t *Test) FromTest0(v Test0) error { - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeTest0 performs a merge with any union data inside the Test, using the provided Test0 -func (t *Test) MergeTest0(v Test0) error { - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -// AsTest1 returns the union data inside the Test as a Test1 -func (t Test) AsTest1() (Test1, error) { - var body Test1 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromTest1 overwrites any union data inside the Test as the provided Test1 -func (t *Test) FromTest1(v Test1) error { - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeTest1 performs a merge with any union data inside the Test, using the provided Test1 -func (t *Test) MergeTest1(v Test1) error { - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -func (t Test) MarshalJSON() ([]byte, error) { - b, err := t.union.MarshalJSON() - return b, err -} - -func (t *Test) UnmarshalJSON(b []byte) error { - err := t.union.UnmarshalJSON(b) - return err -} - -// AsTest20 returns the union data inside the Test2 as a Test20 -func (t Test2) AsTest20() (Test20, error) { - var body Test20 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromTest20 overwrites any union data inside the Test2 as the provided Test20 -func (t *Test2) FromTest20(v Test20) error { - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeTest20 performs a merge with any union data inside the Test2, using the provided Test20 -func (t *Test2) MergeTest20(v Test20) error { - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -// AsTest21 returns the union data inside the Test2 as a Test21 -func (t Test2) AsTest21() (Test21, error) { - var body Test21 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromTest21 overwrites any union data inside the Test2 as the provided Test21 -func (t *Test2) FromTest21(v Test21) error { - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeTest21 performs a merge with any union data inside the Test2, using the provided Test21 -func (t *Test2) MergeTest21(v Test21) error { - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -func (t Test2) MarshalJSON() ([]byte, error) { - b, err := t.union.MarshalJSON() - return b, err -} - -func (t *Test2) UnmarshalJSON(b []byte) error { - err := t.union.UnmarshalJSON(b) - return err -} - -// RequestEditorFn is the function signature for the RequestEditor callback function -type RequestEditorFn func(ctx context.Context, req *http.Request) error - -// Doer performs HTTP requests. -// -// The standard http.Client implements this interface. -type HttpRequestDoer interface { - Do(req *http.Request) (*http.Response, error) -} - -// Client which conforms to the OpenAPI3 specification for this service. -type Client struct { - // The endpoint of the server conforming to this interface, with scheme, - // https://api.deepmap.com for example. This can contain a path relative - // to the server, such as https://api.deepmap.com/dev-test, and all the - // paths in the swagger spec will be appended to the server. - Server string - - // Doer for performing requests, typically a *http.Client with any - // customized settings, such as certificate chains. - Client HttpRequestDoer - - // A list of callbacks for modifying requests which are generated before sending over - // the network. - RequestEditors []RequestEditorFn -} - -// ClientOption allows setting custom parameters during construction -type ClientOption func(*Client) error - -// Creates a new Client, with reasonable defaults -func NewClient(server string, opts ...ClientOption) (*Client, error) { - // create a client with sane default values - client := Client{ - Server: server, - } - // mutate client and add all optional params - for _, o := range opts { - if err := o(&client); err != nil { - return nil, err - } - } - // ensure the server URL always has a trailing slash - if !strings.HasSuffix(client.Server, "/") { - client.Server += "/" - } - // create httpClient, if not already present - if client.Client == nil { - client.Client = &http.Client{} - } - return &client, nil -} - -// WithHTTPClient allows overriding the default Doer, which is -// automatically created using http.Client. This is useful for tests. -func WithHTTPClient(doer HttpRequestDoer) ClientOption { - return func(c *Client) error { - c.Client = doer - return nil - } -} - -// WithRequestEditorFn allows setting up a callback function, which will be -// called right before sending the request. This can be used to mutate the request. -func WithRequestEditorFn(fn RequestEditorFn) ClientOption { - return func(c *Client) error { - c.RequestEditors = append(c.RequestEditors, fn) - return nil - } -} - -// The interface specification for the client above. -type ClientInterface interface { - // GetTest request - GetTest(ctx context.Context, params *GetTestParams, reqEditors ...RequestEditorFn) (*http.Response, error) -} - -func (c *Client) GetTest(ctx context.Context, params *GetTestParams, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewGetTestRequest(c.Server, params) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -// NewGetTestRequest generates requests for GetTest -func NewGetTestRequest(server string, params *GetTestParams) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/test") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - if params != nil { - queryValues := queryURL.Query() - - if params.Test != nil { - - if queryFrag, err := runtime.StyleParamWithOptions("form", true, "test", *params.Test, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "", Format: ""}); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { - return nil, err - } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } - } - } - - } - - if params.Test2 != nil { - - if queryFrag, err := runtime.StyleParamWithOptions("form", true, "test2", *params.Test2, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "array", Format: ""}); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { - return nil, err - } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } - } - } - - } - - queryURL.RawQuery = queryValues.Encode() - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -func (c *Client) applyEditors(ctx context.Context, req *http.Request, additionalEditors []RequestEditorFn) error { - for _, r := range c.RequestEditors { - if err := r(ctx, req); err != nil { - return err - } - } - for _, r := range additionalEditors { - if err := r(ctx, req); err != nil { - return err - } - } - return nil -} - -// ClientWithResponses builds on ClientInterface to offer response payloads -type ClientWithResponses struct { - ClientInterface -} - -// NewClientWithResponses creates a new ClientWithResponses, which wraps -// Client with return type handling -func NewClientWithResponses(server string, opts ...ClientOption) (*ClientWithResponses, error) { - client, err := NewClient(server, opts...) - if err != nil { - return nil, err - } - return &ClientWithResponses{client}, nil -} - -// WithBaseURL overrides the baseURL. -func WithBaseURL(baseURL string) ClientOption { - return func(c *Client) error { - newBaseURL, err := url.Parse(baseURL) - if err != nil { - return err - } - c.Server = newBaseURL.String() - return nil - } -} - -// ClientWithResponsesInterface is the interface specification for the client with responses above. -type ClientWithResponsesInterface interface { - // GetTestWithResponse request - GetTestWithResponse(ctx context.Context, params *GetTestParams, reqEditors ...RequestEditorFn) (*GetTestResponse, error) -} - -type GetTestResponse struct { - Body []byte - HTTPResponse *http.Response -} - -// Status returns HTTPResponse.Status -func (r GetTestResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r GetTestResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -// GetTestWithResponse request returning *GetTestResponse -func (c *ClientWithResponses) GetTestWithResponse(ctx context.Context, params *GetTestParams, reqEditors ...RequestEditorFn) (*GetTestResponse, error) { - rsp, err := c.GetTest(ctx, params, reqEditors...) - if err != nil { - return nil, err - } - return ParseGetTestResponse(rsp) -} - -// ParseGetTestResponse parses an HTTP response from a GetTestWithResponse call -func ParseGetTestResponse(rsp *http.Response) (*GetTestResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &GetTestResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - return response, nil -} diff --git a/internal/test/any_of/param/param_test.go b/internal/test/any_of/param/param_test.go deleted file mode 100644 index 94641b3650..0000000000 --- a/internal/test/any_of/param/param_test.go +++ /dev/null @@ -1,38 +0,0 @@ -package param_test - -import ( - "testing" - - "github.com/oapi-codegen/oapi-codegen/v2/internal/test/any_of/param" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestAnyOfParameter(t *testing.T) { - var p param.GetTestParams - - p.Test = new(param.Test) - err := p.Test.FromTest0(param.Test0{ - Item1: "foo", - Item2: "bar", - }) - require.NoError(t, err) - - hp, err := param.NewGetTestRequest("", &p) - assert.NoError(t, err) - assert.Equal(t, "/test?item1=foo&item2=bar", hp.URL.String()) -} - -func TestArrayOfAnyOfParameter(t *testing.T) { - var p param.GetTestParams - - p.Test2 = &[]param.Test2{ - {}, - } - err := (*p.Test2)[0].FromTest20(100) - require.NoError(t, err) - - hp, err := param.NewGetTestRequest("", &p) - assert.NoError(t, err) - assert.Equal(t, "/test?test2=100", hp.URL.String()) -} diff --git a/internal/test/any_of/param/spec.yaml b/internal/test/any_of/param/spec.yaml deleted file mode 100644 index 090c97c6c1..0000000000 --- a/internal/test/any_of/param/spec.yaml +++ /dev/null @@ -1,42 +0,0 @@ -openapi: "3.0.0" -info: - version: 1.0.0 - title: AnyOf parameter - description: Checks parameter serialize has AnyOf -paths: - /test: - get: - parameters: - - name: test - in: query - schema: - $ref: '#/components/schemas/test' - - name: test2 - in: query - schema: - type: array - items: - $ref: '#/components/schemas/test2' -components: - schemas: - test: - anyOf: - - type: object - required: - - item1 - - item2 - properties: - item1: - type: string - item2: - type: string - - type: object - properties: - item2: - type: string - item3: - type: string - test2: - oneOf: - - type: integer - - type: string diff --git a/internal/test/client/client.gen.go b/internal/test/client/client.gen.go deleted file mode 100644 index 275c72cf0f..0000000000 --- a/internal/test/client/client.gen.go +++ /dev/null @@ -1,996 +0,0 @@ -// Package client provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package client - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "io" - "net/http" - "net/url" - "strings" -) - -const ( - OpenIdScopes = "OpenId.Scopes" -) - -// SchemaObject defines model for SchemaObject. -type SchemaObject struct { - FirstName string `json:"firstName"` - Role string `json:"role"` -} - -// PostVendorJsonApplicationVndAPIPlusJSONBody defines parameters for PostVendorJson. -type PostVendorJsonApplicationVndAPIPlusJSONBody = map[string]interface{} - -// PostBothJSONRequestBody defines body for PostBoth for application/json ContentType. -type PostBothJSONRequestBody = SchemaObject - -// PostJsonJSONRequestBody defines body for PostJson for application/json ContentType. -type PostJsonJSONRequestBody = SchemaObject - -// PostVendorJsonApplicationVndAPIPlusJSONRequestBody defines body for PostVendorJson for application/vnd.api+json ContentType. -type PostVendorJsonApplicationVndAPIPlusJSONRequestBody = PostVendorJsonApplicationVndAPIPlusJSONBody - -// RequestEditorFn is the function signature for the RequestEditor callback function -type RequestEditorFn func(ctx context.Context, req *http.Request) error - -// Doer performs HTTP requests. -// -// The standard http.Client implements this interface. -type HttpRequestDoer interface { - Do(req *http.Request) (*http.Response, error) -} - -// Client which conforms to the OpenAPI3 specification for this service. -type Client struct { - // The endpoint of the server conforming to this interface, with scheme, - // https://api.deepmap.com for example. This can contain a path relative - // to the server, such as https://api.deepmap.com/dev-test, and all the - // paths in the swagger spec will be appended to the server. - Server string - - // Doer for performing requests, typically a *http.Client with any - // customized settings, such as certificate chains. - Client HttpRequestDoer - - // A list of callbacks for modifying requests which are generated before sending over - // the network. - RequestEditors []RequestEditorFn -} - -// ClientOption allows setting custom parameters during construction -type ClientOption func(*Client) error - -// Creates a new Client, with reasonable defaults -func NewClient(server string, opts ...ClientOption) (*Client, error) { - // create a client with sane default values - client := Client{ - Server: server, - } - // mutate client and add all optional params - for _, o := range opts { - if err := o(&client); err != nil { - return nil, err - } - } - // ensure the server URL always has a trailing slash - if !strings.HasSuffix(client.Server, "/") { - client.Server += "/" - } - // create httpClient, if not already present - if client.Client == nil { - client.Client = &http.Client{} - } - return &client, nil -} - -// WithHTTPClient allows overriding the default Doer, which is -// automatically created using http.Client. This is useful for tests. -func WithHTTPClient(doer HttpRequestDoer) ClientOption { - return func(c *Client) error { - c.Client = doer - return nil - } -} - -// WithRequestEditorFn allows setting up a callback function, which will be -// called right before sending the request. This can be used to mutate the request. -func WithRequestEditorFn(fn RequestEditorFn) ClientOption { - return func(c *Client) error { - c.RequestEditors = append(c.RequestEditors, fn) - return nil - } -} - -// The interface specification for the client above. -type ClientInterface interface { - // PostBothWithBody request with any body - PostBothWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) - - PostBoth(ctx context.Context, body PostBothJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) - - // GetBoth request - GetBoth(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) - - // PostJsonWithBody request with any body - PostJsonWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) - - PostJson(ctx context.Context, body PostJsonJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) - - // GetJson request - GetJson(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) - - // PostOtherWithBody request with any body - PostOtherWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) - - // GetOther request - GetOther(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) - - // GetJsonWithTrailingSlash request - GetJsonWithTrailingSlash(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) - - // PostVendorJsonWithBody request with any body - PostVendorJsonWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) - - PostVendorJsonWithApplicationVndAPIPlusJSONBody(ctx context.Context, body PostVendorJsonApplicationVndAPIPlusJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) -} - -func (c *Client) PostBothWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewPostBothRequestWithBody(c.Server, contentType, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) PostBoth(ctx context.Context, body PostBothJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewPostBothRequest(c.Server, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) GetBoth(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewGetBothRequest(c.Server) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) PostJsonWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewPostJsonRequestWithBody(c.Server, contentType, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) PostJson(ctx context.Context, body PostJsonJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewPostJsonRequest(c.Server, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) GetJson(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewGetJsonRequest(c.Server) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) PostOtherWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewPostOtherRequestWithBody(c.Server, contentType, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) GetOther(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewGetOtherRequest(c.Server) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) GetJsonWithTrailingSlash(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewGetJsonWithTrailingSlashRequest(c.Server) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) PostVendorJsonWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewPostVendorJsonRequestWithBody(c.Server, contentType, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) PostVendorJsonWithApplicationVndAPIPlusJSONBody(ctx context.Context, body PostVendorJsonApplicationVndAPIPlusJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewPostVendorJsonRequestWithApplicationVndAPIPlusJSONBody(c.Server, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -// NewPostBothRequest calls the generic PostBoth builder with application/json body -func NewPostBothRequest(server string, body PostBothJSONRequestBody) (*http.Request, error) { - var bodyReader io.Reader - buf, err := json.Marshal(body) - if err != nil { - return nil, err - } - bodyReader = bytes.NewReader(buf) - return NewPostBothRequestWithBody(server, "application/json", bodyReader) -} - -// NewPostBothRequestWithBody generates requests for PostBoth with any type of body -func NewPostBothRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/with_both_bodies") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("POST", queryURL.String(), body) - if err != nil { - return nil, err - } - - req.Header.Add("Content-Type", contentType) - - return req, nil -} - -// NewGetBothRequest generates requests for GetBoth -func NewGetBothRequest(server string) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/with_both_responses") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -// NewPostJsonRequest calls the generic PostJson builder with application/json body -func NewPostJsonRequest(server string, body PostJsonJSONRequestBody) (*http.Request, error) { - var bodyReader io.Reader - buf, err := json.Marshal(body) - if err != nil { - return nil, err - } - bodyReader = bytes.NewReader(buf) - return NewPostJsonRequestWithBody(server, "application/json", bodyReader) -} - -// NewPostJsonRequestWithBody generates requests for PostJson with any type of body -func NewPostJsonRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/with_json_body") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("POST", queryURL.String(), body) - if err != nil { - return nil, err - } - - req.Header.Add("Content-Type", contentType) - - return req, nil -} - -// NewGetJsonRequest generates requests for GetJson -func NewGetJsonRequest(server string) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/with_json_response") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -// NewPostOtherRequestWithBody generates requests for PostOther with any type of body -func NewPostOtherRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/with_other_body") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("POST", queryURL.String(), body) - if err != nil { - return nil, err - } - - req.Header.Add("Content-Type", contentType) - - return req, nil -} - -// NewGetOtherRequest generates requests for GetOther -func NewGetOtherRequest(server string) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/with_other_response") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -// NewGetJsonWithTrailingSlashRequest generates requests for GetJsonWithTrailingSlash -func NewGetJsonWithTrailingSlashRequest(server string) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/with_trailing_slash/") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -// NewPostVendorJsonRequestWithApplicationVndAPIPlusJSONBody calls the generic PostVendorJson builder with application/vnd.api+json body -func NewPostVendorJsonRequestWithApplicationVndAPIPlusJSONBody(server string, body PostVendorJsonApplicationVndAPIPlusJSONRequestBody) (*http.Request, error) { - var bodyReader io.Reader - buf, err := json.Marshal(body) - if err != nil { - return nil, err - } - bodyReader = bytes.NewReader(buf) - return NewPostVendorJsonRequestWithBody(server, "application/vnd.api+json", bodyReader) -} - -// NewPostVendorJsonRequestWithBody generates requests for PostVendorJson with any type of body -func NewPostVendorJsonRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/with_vendor_json") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("POST", queryURL.String(), body) - if err != nil { - return nil, err - } - - req.Header.Add("Content-Type", contentType) - - return req, nil -} - -func (c *Client) applyEditors(ctx context.Context, req *http.Request, additionalEditors []RequestEditorFn) error { - for _, r := range c.RequestEditors { - if err := r(ctx, req); err != nil { - return err - } - } - for _, r := range additionalEditors { - if err := r(ctx, req); err != nil { - return err - } - } - return nil -} - -// ClientWithResponses builds on ClientInterface to offer response payloads -type ClientWithResponses struct { - ClientInterface -} - -// NewClientWithResponses creates a new ClientWithResponses, which wraps -// Client with return type handling -func NewClientWithResponses(server string, opts ...ClientOption) (*ClientWithResponses, error) { - client, err := NewClient(server, opts...) - if err != nil { - return nil, err - } - return &ClientWithResponses{client}, nil -} - -// WithBaseURL overrides the baseURL. -func WithBaseURL(baseURL string) ClientOption { - return func(c *Client) error { - newBaseURL, err := url.Parse(baseURL) - if err != nil { - return err - } - c.Server = newBaseURL.String() - return nil - } -} - -// ClientWithResponsesInterface is the interface specification for the client with responses above. -type ClientWithResponsesInterface interface { - // PostBothWithBodyWithResponse request with any body - PostBothWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*PostBothResponse, error) - - PostBothWithResponse(ctx context.Context, body PostBothJSONRequestBody, reqEditors ...RequestEditorFn) (*PostBothResponse, error) - - // GetBothWithResponse request - GetBothWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*GetBothResponse, error) - - // PostJsonWithBodyWithResponse request with any body - PostJsonWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*PostJsonResponse, error) - - PostJsonWithResponse(ctx context.Context, body PostJsonJSONRequestBody, reqEditors ...RequestEditorFn) (*PostJsonResponse, error) - - // GetJsonWithResponse request - GetJsonWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*GetJsonResponse, error) - - // PostOtherWithBodyWithResponse request with any body - PostOtherWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*PostOtherResponse, error) - - // GetOtherWithResponse request - GetOtherWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*GetOtherResponse, error) - - // GetJsonWithTrailingSlashWithResponse request - GetJsonWithTrailingSlashWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*GetJsonWithTrailingSlashResponse, error) - - // PostVendorJsonWithBodyWithResponse request with any body - PostVendorJsonWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*PostVendorJsonResponse, error) - - PostVendorJsonWithApplicationVndAPIPlusJSONBodyWithResponse(ctx context.Context, body PostVendorJsonApplicationVndAPIPlusJSONRequestBody, reqEditors ...RequestEditorFn) (*PostVendorJsonResponse, error) -} - -type PostBothResponse struct { - Body []byte - HTTPResponse *http.Response -} - -// Status returns HTTPResponse.Status -func (r PostBothResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r PostBothResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type GetBothResponse struct { - Body []byte - HTTPResponse *http.Response -} - -// Status returns HTTPResponse.Status -func (r GetBothResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r GetBothResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type PostJsonResponse struct { - Body []byte - HTTPResponse *http.Response -} - -// Status returns HTTPResponse.Status -func (r PostJsonResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r PostJsonResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type GetJsonResponse struct { - Body []byte - HTTPResponse *http.Response -} - -// Status returns HTTPResponse.Status -func (r GetJsonResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r GetJsonResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type PostOtherResponse struct { - Body []byte - HTTPResponse *http.Response -} - -// Status returns HTTPResponse.Status -func (r PostOtherResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r PostOtherResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type GetOtherResponse struct { - Body []byte - HTTPResponse *http.Response -} - -// Status returns HTTPResponse.Status -func (r GetOtherResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r GetOtherResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type GetJsonWithTrailingSlashResponse struct { - Body []byte - HTTPResponse *http.Response -} - -// Status returns HTTPResponse.Status -func (r GetJsonWithTrailingSlashResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r GetJsonWithTrailingSlashResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type PostVendorJsonResponse struct { - Body []byte - HTTPResponse *http.Response -} - -// Status returns HTTPResponse.Status -func (r PostVendorJsonResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r PostVendorJsonResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -// PostBothWithBodyWithResponse request with arbitrary body returning *PostBothResponse -func (c *ClientWithResponses) PostBothWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*PostBothResponse, error) { - rsp, err := c.PostBothWithBody(ctx, contentType, body, reqEditors...) - if err != nil { - return nil, err - } - return ParsePostBothResponse(rsp) -} - -func (c *ClientWithResponses) PostBothWithResponse(ctx context.Context, body PostBothJSONRequestBody, reqEditors ...RequestEditorFn) (*PostBothResponse, error) { - rsp, err := c.PostBoth(ctx, body, reqEditors...) - if err != nil { - return nil, err - } - return ParsePostBothResponse(rsp) -} - -// GetBothWithResponse request returning *GetBothResponse -func (c *ClientWithResponses) GetBothWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*GetBothResponse, error) { - rsp, err := c.GetBoth(ctx, reqEditors...) - if err != nil { - return nil, err - } - return ParseGetBothResponse(rsp) -} - -// PostJsonWithBodyWithResponse request with arbitrary body returning *PostJsonResponse -func (c *ClientWithResponses) PostJsonWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*PostJsonResponse, error) { - rsp, err := c.PostJsonWithBody(ctx, contentType, body, reqEditors...) - if err != nil { - return nil, err - } - return ParsePostJsonResponse(rsp) -} - -func (c *ClientWithResponses) PostJsonWithResponse(ctx context.Context, body PostJsonJSONRequestBody, reqEditors ...RequestEditorFn) (*PostJsonResponse, error) { - rsp, err := c.PostJson(ctx, body, reqEditors...) - if err != nil { - return nil, err - } - return ParsePostJsonResponse(rsp) -} - -// GetJsonWithResponse request returning *GetJsonResponse -func (c *ClientWithResponses) GetJsonWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*GetJsonResponse, error) { - rsp, err := c.GetJson(ctx, reqEditors...) - if err != nil { - return nil, err - } - return ParseGetJsonResponse(rsp) -} - -// PostOtherWithBodyWithResponse request with arbitrary body returning *PostOtherResponse -func (c *ClientWithResponses) PostOtherWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*PostOtherResponse, error) { - rsp, err := c.PostOtherWithBody(ctx, contentType, body, reqEditors...) - if err != nil { - return nil, err - } - return ParsePostOtherResponse(rsp) -} - -// GetOtherWithResponse request returning *GetOtherResponse -func (c *ClientWithResponses) GetOtherWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*GetOtherResponse, error) { - rsp, err := c.GetOther(ctx, reqEditors...) - if err != nil { - return nil, err - } - return ParseGetOtherResponse(rsp) -} - -// GetJsonWithTrailingSlashWithResponse request returning *GetJsonWithTrailingSlashResponse -func (c *ClientWithResponses) GetJsonWithTrailingSlashWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*GetJsonWithTrailingSlashResponse, error) { - rsp, err := c.GetJsonWithTrailingSlash(ctx, reqEditors...) - if err != nil { - return nil, err - } - return ParseGetJsonWithTrailingSlashResponse(rsp) -} - -// PostVendorJsonWithBodyWithResponse request with arbitrary body returning *PostVendorJsonResponse -func (c *ClientWithResponses) PostVendorJsonWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*PostVendorJsonResponse, error) { - rsp, err := c.PostVendorJsonWithBody(ctx, contentType, body, reqEditors...) - if err != nil { - return nil, err - } - return ParsePostVendorJsonResponse(rsp) -} - -func (c *ClientWithResponses) PostVendorJsonWithApplicationVndAPIPlusJSONBodyWithResponse(ctx context.Context, body PostVendorJsonApplicationVndAPIPlusJSONRequestBody, reqEditors ...RequestEditorFn) (*PostVendorJsonResponse, error) { - rsp, err := c.PostVendorJsonWithApplicationVndAPIPlusJSONBody(ctx, body, reqEditors...) - if err != nil { - return nil, err - } - return ParsePostVendorJsonResponse(rsp) -} - -// ParsePostBothResponse parses an HTTP response from a PostBothWithResponse call -func ParsePostBothResponse(rsp *http.Response) (*PostBothResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &PostBothResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - return response, nil -} - -// ParseGetBothResponse parses an HTTP response from a GetBothWithResponse call -func ParseGetBothResponse(rsp *http.Response) (*GetBothResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &GetBothResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - return response, nil -} - -// ParsePostJsonResponse parses an HTTP response from a PostJsonWithResponse call -func ParsePostJsonResponse(rsp *http.Response) (*PostJsonResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &PostJsonResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - return response, nil -} - -// ParseGetJsonResponse parses an HTTP response from a GetJsonWithResponse call -func ParseGetJsonResponse(rsp *http.Response) (*GetJsonResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &GetJsonResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - return response, nil -} - -// ParsePostOtherResponse parses an HTTP response from a PostOtherWithResponse call -func ParsePostOtherResponse(rsp *http.Response) (*PostOtherResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &PostOtherResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - return response, nil -} - -// ParseGetOtherResponse parses an HTTP response from a GetOtherWithResponse call -func ParseGetOtherResponse(rsp *http.Response) (*GetOtherResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &GetOtherResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - return response, nil -} - -// ParseGetJsonWithTrailingSlashResponse parses an HTTP response from a GetJsonWithTrailingSlashWithResponse call -func ParseGetJsonWithTrailingSlashResponse(rsp *http.Response) (*GetJsonWithTrailingSlashResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &GetJsonWithTrailingSlashResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - return response, nil -} - -// ParsePostVendorJsonResponse parses an HTTP response from a PostVendorJsonWithResponse call -func ParsePostVendorJsonResponse(rsp *http.Response) (*PostVendorJsonResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &PostVendorJsonResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - return response, nil -} diff --git a/internal/test/client/client.yaml b/internal/test/client/client.yaml deleted file mode 100644 index ea4c1c3b1e..0000000000 --- a/internal/test/client/client.yaml +++ /dev/null @@ -1,102 +0,0 @@ -openapi: "3.0.1" -info: - version: 1.0.0 - title: Test Server - license: - name: MIT - description: | - This tests whether the Client and ClientWithResponses are generated correctly -paths: - /with_json_response: - get: - operationId: GetJson - security: - - OpenId: [ json.read, json.admin ] - responses: - 200: - application/json: - schema: - $ref: '#/components/schemas/SchemaObject' - /with_trailing_slash/: - get: - operationId: GetJsonWithTrailingSlash - security: - - OpenId: [ json.read, json.admin ] - responses: - 200: - application/json: - schema: - $ref: '#/components/schemas/SchemaObject' - /with_other_response: - get: - operationId: GetOther - responses: - 200: - application/octet-stream: - schema: - type: string - format: binary - /with_both_responses: - get: - operationId: GetBoth - responses: - 200: - application/json: - schema: - $ref: '#/components/schemas/SchemaObject' - application/octet-stream: - schema: - type: string - format: binary - /with_json_body: - post: - operationId: PostJson - requestBody: - required: true - content: - application/json: - schema: - $ref: '#/components/schemas/SchemaObject' - /with_other_body: - post: - operationId: PostOther - requestBody: - required: true - content: - application/octet-stream: - schema: - type: string - format: binary - /with_both_bodies: - post: - operationId: PostBoth - requestBody: - required: true - content: - application/octet-stream: - schema: - type: string - format: binary - application/json: - schema: - $ref: '#/components/schemas/SchemaObject' - /with_vendor_json: - post: - operationId: PostVendorJson - requestBody: - required: true - content: - application/vnd.api+json: - schema: - type: object -components: - schemas: - SchemaObject: - properties: - role: - type: string - firstName: - type: string - required: - - role - - firstName diff --git a/internal/test/client/client_test.go b/internal/test/client/client_test.go deleted file mode 100644 index ef7c5df169..0000000000 --- a/internal/test/client/client_test.go +++ /dev/null @@ -1,79 +0,0 @@ -package client - -import ( - "testing" - - "github.com/oapi-codegen/oapi-codegen/v2/pkg/securityprovider" - "github.com/stretchr/testify/assert" -) - -var ( - withTrailingSlash = "https://my-api.com/some-base-url/v1/" -) - -func TestTemp(t *testing.T) { - - var ( - withTrailingSlash = "https://my-api.com/some-base-url/v1/" - withoutTrailingSlash = "https://my-api.com/some-base-url/v1" - ) - - client1, err := NewClient( - withTrailingSlash, - ) - assert.NoError(t, err) - - client2, err := NewClient( - withoutTrailingSlash, - ) - assert.NoError(t, err) - - client3, err := NewClient( - "", - WithBaseURL(withTrailingSlash), - ) - assert.NoError(t, err) - - client4, err := NewClient( - "", - WithBaseURL(withoutTrailingSlash), - ) - assert.NoError(t, err) - - expectedURL := withTrailingSlash - - assert.Equal(t, expectedURL, client1.Server) - assert.Equal(t, expectedURL, client2.Server) - assert.Equal(t, expectedURL, client3.Server) - assert.Equal(t, expectedURL, client4.Server) -} - -func TestSecurityProviders(t *testing.T) { - bearer, err := securityprovider.NewSecurityProviderBearerToken("mytoken") - assert.NoError(t, err) - client1, err := NewClient( - withTrailingSlash, - WithRequestEditorFn(bearer.Intercept), - ) - assert.NoError(t, err) - - apiKey, err := securityprovider.NewSecurityProviderApiKey("cookie", "apikey", "mykey") - assert.NoError(t, err) - client2, err := NewClient( - withTrailingSlash, - WithRequestEditorFn(apiKey.Intercept), - ) - assert.NoError(t, err) - - basicAuth, err := securityprovider.NewSecurityProviderBasicAuth("username", "password") - assert.NoError(t, err) - client3, err := NewClient( - withTrailingSlash, - WithRequestEditorFn(basicAuth.Intercept), - ) - assert.NoError(t, err) - - assert.Equal(t, withTrailingSlash, client1.Server) - assert.Equal(t, withTrailingSlash, client2.Server) - assert.Equal(t, withTrailingSlash, client3.Server) -} diff --git a/internal/test/client/doc.go b/internal/test/client/doc.go deleted file mode 100644 index 930039dadd..0000000000 --- a/internal/test/client/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -package client - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --package=client --generate=client,types -o client.gen.go client.yaml diff --git a/internal/test/compatibility/preserve-original-operation-id-casing-in-embedded-spec/api.yaml b/internal/test/compatibility/preserve-original-operation-id-casing-in-embedded-spec/api.yaml deleted file mode 100644 index ace3dbd4b9..0000000000 --- a/internal/test/compatibility/preserve-original-operation-id-casing-in-embedded-spec/api.yaml +++ /dev/null @@ -1,24 +0,0 @@ -openapi: "3.0.0" -info: - title: "my spec" - version: 1.0.0 -paths: - /pet: - get: - operationId: getPet - responses: - 200: - content: - application/json: - schema: - type: string - delete: - # Via https://spec.openapis.org/oas/v3.0.3.html - # operationId: Unique string used to identify the operation. The id MUST be unique among all operations described in the API. The operationId value is case-sensitive. Tools and libraries MAY use the operationId to uniquely identify an operation, therefore, it is RECOMMENDED to follow common programming naming conventions. - operationId: this-is-a-kebabAndCamel_SNAKE - responses: - 200: - content: - application/json: - schema: - type: string diff --git a/internal/test/compatibility/preserve-original-operation-id-casing-in-embedded-spec/cfg.yaml b/internal/test/compatibility/preserve-original-operation-id-casing-in-embedded-spec/cfg.yaml deleted file mode 100644 index 055e75c884..0000000000 --- a/internal/test/compatibility/preserve-original-operation-id-casing-in-embedded-spec/cfg.yaml +++ /dev/null @@ -1,9 +0,0 @@ -# yaml-language-server: $schema=../../../../configuration-schema.json -package: preserveoriginaloperationidcasinginembeddedspec -output: spec.gen.go -generate: - embedded-spec: true -output-options: - skip-prune: false -compatibility: - preserve-original-operation-id-casing-in-embedded-spec: true diff --git a/internal/test/compatibility/preserve-original-operation-id-casing-in-embedded-spec/generate.go b/internal/test/compatibility/preserve-original-operation-id-casing-in-embedded-spec/generate.go deleted file mode 100644 index 5a48f1eece..0000000000 --- a/internal/test/compatibility/preserve-original-operation-id-casing-in-embedded-spec/generate.go +++ /dev/null @@ -1,3 +0,0 @@ -package preserveoriginaloperationidcasinginembeddedspec - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen -config cfg.yaml api.yaml diff --git a/internal/test/compatibility/preserve-original-operation-id-casing-in-embedded-spec/spec.gen.go b/internal/test/compatibility/preserve-original-operation-id-casing-in-embedded-spec/spec.gen.go deleted file mode 100644 index 030c8277d9..0000000000 --- a/internal/test/compatibility/preserve-original-operation-id-casing-in-embedded-spec/spec.gen.go +++ /dev/null @@ -1,97 +0,0 @@ -// Package preserveoriginaloperationidcasinginembeddedspec provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package preserveoriginaloperationidcasinginembeddedspec - -import ( - "bytes" - "compress/gzip" - "encoding/base64" - "fmt" - "net/url" - "path" - "strings" - - "github.com/getkin/kin-openapi/openapi3" -) - -// Base64 encoded, gzipped, json marshaled Swagger object -var swaggerSpec = []string{ - - "H4sIAAAAAAAC/7SOwUrFQAxFf0Xuevpe1d3sHuJCBBH8AJnXxjbaZkIThFLm32XGlR9gNjcEcu45wPKR", - "EQ84+0KIWPcbUxoQ8E2bcRZE3J76U48SkJUkKSPivp0CNPls9f+s5DVHWsipbllpS85ZnkZE+MzWsXWp", - "+6Jrul5kfEgrLe9vL5fnRwRsZJrFqMHu+r7GkMVJGjapLjw03PnTqtUBG2ZaU5PftbqbbywTSpuA6dfo", - "r8dE/kr+H4WllJ8AAAD//+CJBDdPAQAA", -} - -// GetSwagger returns the content of the embedded swagger specification file -// or error if failed to decode -func decodeSpec() ([]byte, error) { - zipped, err := base64.StdEncoding.DecodeString(strings.Join(swaggerSpec, "")) - if err != nil { - return nil, fmt.Errorf("error base64 decoding spec: %w", err) - } - zr, err := gzip.NewReader(bytes.NewReader(zipped)) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - var buf bytes.Buffer - _, err = buf.ReadFrom(zr) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - - return buf.Bytes(), nil -} - -var rawSpec = decodeSpecCached() - -// a naive cached of a decoded swagger spec -func decodeSpecCached() func() ([]byte, error) { - data, err := decodeSpec() - return func() ([]byte, error) { - return data, err - } -} - -// Constructs a synthetic filesystem for resolving external references when loading openapi specifications. -func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { - res := make(map[string]func() ([]byte, error)) - if len(pathToFile) > 0 { - res[pathToFile] = rawSpec - } - - return res -} - -// GetSwagger returns the Swagger specification corresponding to the generated code -// in this file. The external references of Swagger specification are resolved. -// The logic of resolving external references is tightly connected to "import-mapping" feature. -// Externally referenced files must be embedded in the corresponding golang packages. -// Urls can be supported but this task was out of the scope. -func GetSwagger() (swagger *openapi3.T, err error) { - resolvePath := PathToRawSpec("") - - loader := openapi3.NewLoader() - loader.IsExternalRefsAllowed = true - loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() - pathToFile = path.Clean(pathToFile) - getSpec, ok := resolvePath[pathToFile] - if !ok { - err1 := fmt.Errorf("path not found: %s", pathToFile) - return nil, err1 - } - return getSpec() - } - var specData []byte - specData, err = rawSpec() - if err != nil { - return - } - swagger, err = loader.LoadFromData(specData) - if err != nil { - return - } - return -} diff --git a/internal/test/compatibility/preserve-original-operation-id-casing-in-embedded-spec/spec_test.go b/internal/test/compatibility/preserve-original-operation-id-casing-in-embedded-spec/spec_test.go deleted file mode 100644 index 2f395b5776..0000000000 --- a/internal/test/compatibility/preserve-original-operation-id-casing-in-embedded-spec/spec_test.go +++ /dev/null @@ -1,29 +0,0 @@ -package preserveoriginaloperationidcasinginembeddedspec - -import ( - "net/http" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestSpecReturnsOperationIdAsOriginallySpecified(t *testing.T) { - spec, err := GetSwagger() - require.NoError(t, err) - - path := spec.Paths.Find("/pet") - require.NotNil(t, path, "The path /pet could not be found") - - operation := path.GetOperation(http.MethodGet) - require.NotNil(t, operation, "The GET operation on the path /pet could not be found") - - // this should be the raw operationId from the spec - assert.Equal(t, "getPet", operation.OperationID) - - operation = path.GetOperation(http.MethodDelete) - require.NotNil(t, operation, "The DELETE operation on the path /pet could not be found") - - // this should be the raw operationId from the spec - assert.Equal(t, "this-is-a-kebabAndCamel_SNAKE", operation.OperationID) -} diff --git a/internal/test/components/components.gen.go b/internal/test/components/components.gen.go deleted file mode 100644 index 0bfc1747e6..0000000000 --- a/internal/test/components/components.gen.go +++ /dev/null @@ -1,2549 +0,0 @@ -// Package components provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package components - -import ( - "encoding/json" - "errors" - "fmt" - - "github.com/oapi-codegen/runtime" -) - -// Defines values for Enum1. -const ( - Enum1One Enum1 = "One" - Enum1Three Enum1 = "Three" - Enum1Two Enum1 = "Two" -) - -// Valid indicates whether the value is a known member of the Enum1 enum. -func (e Enum1) Valid() bool { - switch e { - case Enum1One: - return true - case Enum1Three: - return true - case Enum1Two: - return true - default: - return false - } -} - -// Defines values for Enum2. -const ( - Enum2Four Enum2 = "Four" - Enum2Three Enum2 = "Three" - Enum2Two Enum2 = "Two" -) - -// Valid indicates whether the value is a known member of the Enum2 enum. -func (e Enum2) Valid() bool { - switch e { - case Enum2Four: - return true - case Enum2Three: - return true - case Enum2Two: - return true - default: - return false - } -} - -// Defines values for Enum3. -const ( - Enum3Bar Enum3 = "Bar" - Enum3Enum1One Enum3 = "Enum1One" - Enum3Foo Enum3 = "Foo" -) - -// Valid indicates whether the value is a known member of the Enum3 enum. -func (e Enum3) Valid() bool { - switch e { - case Enum3Bar: - return true - case Enum3Enum1One: - return true - case Enum3Foo: - return true - default: - return false - } -} - -// Defines values for Enum4. -const ( - Cat Enum4 = "Cat" - Dog Enum4 = "Dog" - Mouse Enum4 = "Mouse" -) - -// Valid indicates whether the value is a known member of the Enum4 enum. -func (e Enum4) Valid() bool { - switch e { - case Cat: - return true - case Dog: - return true - case Mouse: - return true - default: - return false - } -} - -// Defines values for Enum5. -const ( - Enum5N5 Enum5 = 5 - Enum5N6 Enum5 = 6 - Enum5N7 Enum5 = 7 -) - -// Valid indicates whether the value is a known member of the Enum5 enum. -func (e Enum5) Valid() bool { - switch e { - case Enum5N5: - return true - case Enum5N6: - return true - case Enum5N7: - return true - default: - return false - } -} - -// Defines values for EnumUnion. -const ( - EnumUnionFour EnumUnion = "Four" - EnumUnionOne EnumUnion = "One" - EnumUnionThree EnumUnion = "Three" - EnumUnionTwo EnumUnion = "Two" -) - -// Valid indicates whether the value is a known member of the EnumUnion enum. -func (e EnumUnion) Valid() bool { - switch e { - case EnumUnionFour: - return true - case EnumUnionOne: - return true - case EnumUnionThree: - return true - case EnumUnionTwo: - return true - default: - return false - } -} - -// Defines values for EnumUnion2. -const ( - EnumUnion2One EnumUnion2 = "One" - EnumUnion2Seven EnumUnion2 = "Seven" - EnumUnion2Three EnumUnion2 = "Three" - EnumUnion2Two EnumUnion2 = "Two" -) - -// Valid indicates whether the value is a known member of the EnumUnion2 enum. -func (e EnumUnion2) Valid() bool { - switch e { - case EnumUnion2One: - return true - case EnumUnion2Seven: - return true - case EnumUnion2Three: - return true - case EnumUnion2Two: - return true - default: - return false - } -} - -// Defines values for FunnyValues. -const ( - FunnyValuesAnd FunnyValues = "&" - FunnyValuesAsterisk FunnyValues = "*" - FunnyValuesEmpty FunnyValues = "" - FunnyValuesN5 FunnyValues = "5" - FunnyValuesPercent FunnyValues = "%" -) - -// Valid indicates whether the value is a known member of the FunnyValues enum. -func (e FunnyValues) Valid() bool { - switch e { - case FunnyValuesAnd: - return true - case FunnyValuesAsterisk: - return true - case FunnyValuesEmpty: - return true - case FunnyValuesN5: - return true - case FunnyValuesPercent: - return true - default: - return false - } -} - -// Defines values for EnumParam1. -const ( - EnumParam1Both EnumParam1 = "both" - EnumParam1Off EnumParam1 = "off" - EnumParam1On EnumParam1 = "on" -) - -// Valid indicates whether the value is a known member of the EnumParam1 enum. -func (e EnumParam1) Valid() bool { - switch e { - case EnumParam1Both: - return true - case EnumParam1Off: - return true - case EnumParam1On: - return true - default: - return false - } -} - -// Defines values for EnumParam2. -const ( - EnumParam2Both EnumParam2 = "both" - EnumParam2Off EnumParam2 = "off" - EnumParam2On EnumParam2 = "on" -) - -// Valid indicates whether the value is a known member of the EnumParam2 enum. -func (e EnumParam2) Valid() bool { - switch e { - case EnumParam2Both: - return true - case EnumParam2Off: - return true - case EnumParam2On: - return true - default: - return false - } -} - -// Defines values for EnumParam3. -const ( - Alice EnumParam3 = "alice" - Bob EnumParam3 = "bob" - Eve EnumParam3 = "eve" -) - -// Valid indicates whether the value is a known member of the EnumParam3 enum. -func (e EnumParam3) Valid() bool { - switch e { - case Alice: - return true - case Bob: - return true - case Eve: - return true - default: - return false - } -} - -// AdditionalPropertiesObject1 Has additional properties of type int -type AdditionalPropertiesObject1 struct { - Id int `json:"id"` - Name string `json:"name"` - Optional *string `json:"optional,omitempty"` - AdditionalProperties map[string]int `json:"-"` -} - -// AdditionalPropertiesObject2 Does not allow additional properties -type AdditionalPropertiesObject2 struct { - Id int `json:"id"` - Name string `json:"name"` -} - -// AdditionalPropertiesObject3 Allows any additional property -type AdditionalPropertiesObject3 struct { - Name string `json:"name"` - AdditionalProperties map[string]interface{} `json:"-"` -} - -// AdditionalPropertiesObject4 Has anonymous field which has additional properties -type AdditionalPropertiesObject4 struct { - Inner AdditionalPropertiesObject4_Inner `json:"inner"` - Name string `json:"name"` - AdditionalProperties map[string]interface{} `json:"-"` -} - -// AdditionalPropertiesObject4_Inner defines model for AdditionalPropertiesObject4.Inner. -type AdditionalPropertiesObject4_Inner struct { - Name string `json:"name"` - AdditionalProperties map[string]interface{} `json:"-"` -} - -// AdditionalPropertiesObject5 Has additional properties with schema for dictionaries -type AdditionalPropertiesObject5 map[string]SchemaObject - -// AdditionalPropertiesObject6 Array of object with additional properties -type AdditionalPropertiesObject6 = []map[string]SchemaObject - -// AdditionalPropertiesObject7 Has additional properties with schema for dictionaries -type AdditionalPropertiesObject7 map[string]*SchemaObjectNullable - -// AnyOfObject1 simple anyOf case -type AnyOfObject1 struct { - union json.RawMessage -} - -// Enum1 Conflicts with Enum2, enum values need to be prefixed with type -// name. -type Enum1 string - -// Enum2 Conflicts with Enum1, enum values need to be prefixed with type -// name. -type Enum2 string - -// Enum3 Enum values conflict with Enums above, need to be prefixed -// with type name. -type Enum3 string - -// Enum4 No conflicts here, should have unmodified enums -type Enum4 string - -// Enum5 Numerical enum -type Enum5 int - -// EnumUnion defines model for EnumUnion. -type EnumUnion string - -// EnumUnion2 defines model for EnumUnion2. -type EnumUnion2 string - -// FunnyValues Edge cases for enum names -type FunnyValues string - -// ObjectWithJsonField defines model for ObjectWithJsonField. -type ObjectWithJsonField struct { - Name string `json:"name"` - Value1 json.RawMessage `json:"value1"` - Value2 json.RawMessage `json:"value2,omitempty"` -} - -// OneOfObject1 oneOf with references and no discriminator -type OneOfObject1 struct { - union json.RawMessage -} - -// OneOfObject10 fixed properties, variable required - will compile, but not much sense -type OneOfObject10 struct { - One *string `json:"one,omitempty"` - Three *bool `json:"three,omitempty"` - Two *int `json:"two,omitempty"` - union json.RawMessage -} - -// OneOfObject100 defines model for . -type OneOfObject100 = interface{} - -// OneOfObject101 defines model for . -type OneOfObject101 = interface{} - -// OneOfObject11 additional properties of oneOf -type OneOfObject11 map[string]OneOfObject11_AdditionalProperties - -// OneOfObject110 defines model for . -type OneOfObject110 = bool - -// OneOfObject111 defines model for . -type OneOfObject111 = float32 - -// OneOfObject112 defines model for . -type OneOfObject112 = string - -// OneOfObject11_AdditionalProperties defines model for OneOfObject11.AdditionalProperties. -type OneOfObject11_AdditionalProperties struct { - union json.RawMessage -} - -// OneOfObject12 defines model for OneOfObject12. -type OneOfObject12 struct { - union json.RawMessage -} - -// OneOfObject120 defines model for . -type OneOfObject120 = string - -// OneOfObject121 defines model for . -type OneOfObject121 = float32 - -// OneOfObject13 oneOf with fixed discriminator and other fields allowed -type OneOfObject13 struct { - Type string `json:"type"` - AdditionalProperties map[string]interface{} `json:"-"` - union json.RawMessage -} - -// OneOfObject2 oneOf with inline elements -type OneOfObject2 struct { - union json.RawMessage -} - -// OneOfObject20 defines model for . -type OneOfObject20 struct { - Name *string `json:"name,omitempty"` -} - -// OneOfObject21 defines model for . -type OneOfObject21 = []float32 - -// OneOfObject22 defines model for . -type OneOfObject22 = bool - -// OneOfObject3 inline OneOf -type OneOfObject3 struct { - Union *OneOfObject3_Union `json:"union,omitempty"` -} - -// OneOfObject3_Union defines model for OneOfObject3.Union. -type OneOfObject3_Union struct { - union json.RawMessage -} - -// OneOfObject4 oneOf plus fixed type - custom marshaling/unmarshaling -type OneOfObject4 struct { - FixedProperty *string `json:"fixedProperty,omitempty"` - union json.RawMessage -} - -// OneOfObject5 oneOf with discriminator but no mapping -type OneOfObject5 struct { - union json.RawMessage -} - -// OneOfObject6 oneOf with discriminator and mapping -type OneOfObject6 struct { - union json.RawMessage -} - -// OneOfObject61 oneOf with discriminator and partial mapping -type OneOfObject61 struct { - union json.RawMessage -} - -// OneOfObject62 oneOf with snake_case discriminator and partial snake_case mapping -type OneOfObject62 struct { - union json.RawMessage -} - -// OneOfObject7 array of oneOf -type OneOfObject7 = []OneOfObject7_Item - -// OneOfObject7_Item defines model for OneOfObject7.Item. -type OneOfObject7_Item struct { - union json.RawMessage -} - -// OneOfObject8 oneOf with fixed properties -type OneOfObject8 struct { - Fixed *string `json:"fixed,omitempty"` - union json.RawMessage -} - -// OneOfObject9 oneOf with fixed discriminator -type OneOfObject9 struct { - Type string `json:"type"` - union json.RawMessage -} - -// OneOfVariant1 defines model for OneOfVariant1. -type OneOfVariant1 struct { - Name string `json:"name"` -} - -// OneOfVariant2 defines model for OneOfVariant2. -type OneOfVariant2 = []int - -// OneOfVariant3 defines model for OneOfVariant3. -type OneOfVariant3 = bool - -// OneOfVariant4 defines model for OneOfVariant4. -type OneOfVariant4 struct { - Discriminator string `json:"discriminator"` - Name string `json:"name"` -} - -// OneOfVariant5 defines model for OneOfVariant5. -type OneOfVariant5 struct { - Discriminator string `json:"discriminator"` - Id int `json:"id"` -} - -// OneOfVariant6 defines model for OneOfVariant6. -type OneOfVariant6 struct { - Values OneOfVariant2 `json:"values"` -} - -// ReferenceToRenameMe When a Schema is renamed, $ref should refer to the new name -type ReferenceToRenameMe struct { - // NewName This schema should be renamed via x-go-name when generating - NewName NewName `json:"ToNewName"` -} - -// NewName This schema should be renamed via x-go-name when generating -type NewName struct { - Prop1 string `json:"prop1"` - Prop2 string `json:"prop2"` -} - -// SchemaObject defines model for SchemaObject. -type SchemaObject struct { - FirstName string `json:"firstName"` - - // ReadOnlyRequiredProp This property is required and readOnly, so the go model should have it as a pointer, - // as it will not be included when it is sent from client to server. - ReadOnlyRequiredProp *string `json:"readOnlyRequiredProp,omitempty"` - Role string `json:"role"` - WriteOnlyRequiredProp *int `json:"writeOnlyRequiredProp,omitempty"` -} - -// SchemaObjectNullable defines model for SchemaObjectNullable. -type SchemaObjectNullable struct { - FirstName string `json:"firstName"` - - // ReadOnlyRequiredProp This property is required and readOnly, so the go model should have it as a pointer, - // as it will not be included when it is sent from client to server. - ReadOnlyRequiredProp *string `json:"readOnlyRequiredProp,omitempty"` - Role string `json:"role"` - WriteOnlyRequiredProp *int `json:"writeOnlyRequiredProp,omitempty"` -} - -// OneOfVariant51 defines model for one_of_variant51. -type OneOfVariant51 struct { - Discriminator string `json:"discriminator"` - Id int `json:"id"` -} - -// EnumParam1 defines model for EnumParam1. -type EnumParam1 string - -// EnumParam2 defines model for EnumParam2. -type EnumParam2 string - -// EnumParam3 defines model for EnumParam3. -type EnumParam3 string - -// RenamedParameterObject // a parameter -type RenamedParameterObject string - -// RenamedResponseObject defines model for ResponseObject. -type RenamedResponseObject struct { - Field SchemaObject `json:"Field"` -} - -// RenamedRequestBody defines model for RequestBody. -type RenamedRequestBody struct { - Field SchemaObject `json:"Field"` -} - -// EnsureEverythingIsReferencedJSONBody defines parameters for EnsureEverythingIsReferenced. -type EnsureEverythingIsReferencedJSONBody struct { - Field SchemaObject `json:"Field"` -} - -// EnsureEverythingIsReferencedTextBody defines parameters for EnsureEverythingIsReferenced. -type EnsureEverythingIsReferencedTextBody = string - -// ParamsWithAddPropsParams defines parameters for ParamsWithAddProps. -type ParamsWithAddPropsParams struct { - // P1 This parameter has additional properties - P1 map[string]interface{} `json:"p1"` - - // P2 This parameter has an anonymous inner property which needs to be - // turned into a proper type for additionalProperties to work - P2 struct { - Inner map[string]string `json:"inner"` - } `form:"p2" json:"p2"` -} - -// BodyWithAddPropsJSONBody defines parameters for BodyWithAddProps. -type BodyWithAddPropsJSONBody struct { - Inner map[string]int `json:"inner"` - Name string `json:"name"` - AdditionalProperties map[string]interface{} `json:"-"` -} - -// EnsureEverythingIsReferencedJSONRequestBody defines body for EnsureEverythingIsReferenced for application/json ContentType. -type EnsureEverythingIsReferencedJSONRequestBody EnsureEverythingIsReferencedJSONBody - -// EnsureEverythingIsReferencedTextRequestBody defines body for EnsureEverythingIsReferenced for text/plain ContentType. -type EnsureEverythingIsReferencedTextRequestBody = EnsureEverythingIsReferencedTextBody - -// BodyWithAddPropsJSONRequestBody defines body for BodyWithAddProps for application/json ContentType. -type BodyWithAddPropsJSONRequestBody BodyWithAddPropsJSONBody - -// Getter for additional properties for BodyWithAddPropsJSONBody. Returns the specified -// element and whether it was found -func (a BodyWithAddPropsJSONBody) Get(fieldName string) (value interface{}, found bool) { - if a.AdditionalProperties != nil { - value, found = a.AdditionalProperties[fieldName] - } - return -} - -// Setter for additional properties for BodyWithAddPropsJSONBody -func (a *BodyWithAddPropsJSONBody) Set(fieldName string, value interface{}) { - if a.AdditionalProperties == nil { - a.AdditionalProperties = make(map[string]interface{}) - } - a.AdditionalProperties[fieldName] = value -} - -// Override default JSON handling for BodyWithAddPropsJSONBody to handle AdditionalProperties -func (a *BodyWithAddPropsJSONBody) UnmarshalJSON(b []byte) error { - object := make(map[string]json.RawMessage) - err := json.Unmarshal(b, &object) - if err != nil { - return err - } - - if raw, found := object["inner"]; found { - err = json.Unmarshal(raw, &a.Inner) - if err != nil { - return fmt.Errorf("error reading 'inner': %w", err) - } - delete(object, "inner") - } - - if raw, found := object["name"]; found { - err = json.Unmarshal(raw, &a.Name) - if err != nil { - return fmt.Errorf("error reading 'name': %w", err) - } - delete(object, "name") - } - - if len(object) != 0 { - a.AdditionalProperties = make(map[string]interface{}) - for fieldName, fieldBuf := range object { - var fieldVal interface{} - err := json.Unmarshal(fieldBuf, &fieldVal) - if err != nil { - return fmt.Errorf("error unmarshaling field %s: %w", fieldName, err) - } - a.AdditionalProperties[fieldName] = fieldVal - } - } - return nil -} - -// Override default JSON handling for BodyWithAddPropsJSONBody to handle AdditionalProperties -func (a BodyWithAddPropsJSONBody) MarshalJSON() ([]byte, error) { - var err error - object := make(map[string]json.RawMessage) - - object["inner"], err = json.Marshal(a.Inner) - if err != nil { - return nil, fmt.Errorf("error marshaling 'inner': %w", err) - } - - object["name"], err = json.Marshal(a.Name) - if err != nil { - return nil, fmt.Errorf("error marshaling 'name': %w", err) - } - - for fieldName, field := range a.AdditionalProperties { - object[fieldName], err = json.Marshal(field) - if err != nil { - return nil, fmt.Errorf("error marshaling '%s': %w", fieldName, err) - } - } - return json.Marshal(object) -} - -// Getter for additional properties for AdditionalPropertiesObject1. Returns the specified -// element and whether it was found -func (a AdditionalPropertiesObject1) Get(fieldName string) (value int, found bool) { - if a.AdditionalProperties != nil { - value, found = a.AdditionalProperties[fieldName] - } - return -} - -// Setter for additional properties for AdditionalPropertiesObject1 -func (a *AdditionalPropertiesObject1) Set(fieldName string, value int) { - if a.AdditionalProperties == nil { - a.AdditionalProperties = make(map[string]int) - } - a.AdditionalProperties[fieldName] = value -} - -// Override default JSON handling for AdditionalPropertiesObject1 to handle AdditionalProperties -func (a *AdditionalPropertiesObject1) UnmarshalJSON(b []byte) error { - object := make(map[string]json.RawMessage) - err := json.Unmarshal(b, &object) - if err != nil { - return err - } - - if raw, found := object["id"]; found { - err = json.Unmarshal(raw, &a.Id) - if err != nil { - return fmt.Errorf("error reading 'id': %w", err) - } - delete(object, "id") - } - - if raw, found := object["name"]; found { - err = json.Unmarshal(raw, &a.Name) - if err != nil { - return fmt.Errorf("error reading 'name': %w", err) - } - delete(object, "name") - } - - if raw, found := object["optional"]; found { - err = json.Unmarshal(raw, &a.Optional) - if err != nil { - return fmt.Errorf("error reading 'optional': %w", err) - } - delete(object, "optional") - } - - if len(object) != 0 { - a.AdditionalProperties = make(map[string]int) - for fieldName, fieldBuf := range object { - var fieldVal int - err := json.Unmarshal(fieldBuf, &fieldVal) - if err != nil { - return fmt.Errorf("error unmarshaling field %s: %w", fieldName, err) - } - a.AdditionalProperties[fieldName] = fieldVal - } - } - return nil -} - -// Override default JSON handling for AdditionalPropertiesObject1 to handle AdditionalProperties -func (a AdditionalPropertiesObject1) MarshalJSON() ([]byte, error) { - var err error - object := make(map[string]json.RawMessage) - - object["id"], err = json.Marshal(a.Id) - if err != nil { - return nil, fmt.Errorf("error marshaling 'id': %w", err) - } - - object["name"], err = json.Marshal(a.Name) - if err != nil { - return nil, fmt.Errorf("error marshaling 'name': %w", err) - } - - if a.Optional != nil { - object["optional"], err = json.Marshal(a.Optional) - if err != nil { - return nil, fmt.Errorf("error marshaling 'optional': %w", err) - } - } - - for fieldName, field := range a.AdditionalProperties { - object[fieldName], err = json.Marshal(field) - if err != nil { - return nil, fmt.Errorf("error marshaling '%s': %w", fieldName, err) - } - } - return json.Marshal(object) -} - -// Getter for additional properties for AdditionalPropertiesObject3. Returns the specified -// element and whether it was found -func (a AdditionalPropertiesObject3) Get(fieldName string) (value interface{}, found bool) { - if a.AdditionalProperties != nil { - value, found = a.AdditionalProperties[fieldName] - } - return -} - -// Setter for additional properties for AdditionalPropertiesObject3 -func (a *AdditionalPropertiesObject3) Set(fieldName string, value interface{}) { - if a.AdditionalProperties == nil { - a.AdditionalProperties = make(map[string]interface{}) - } - a.AdditionalProperties[fieldName] = value -} - -// Override default JSON handling for AdditionalPropertiesObject3 to handle AdditionalProperties -func (a *AdditionalPropertiesObject3) UnmarshalJSON(b []byte) error { - object := make(map[string]json.RawMessage) - err := json.Unmarshal(b, &object) - if err != nil { - return err - } - - if raw, found := object["name"]; found { - err = json.Unmarshal(raw, &a.Name) - if err != nil { - return fmt.Errorf("error reading 'name': %w", err) - } - delete(object, "name") - } - - if len(object) != 0 { - a.AdditionalProperties = make(map[string]interface{}) - for fieldName, fieldBuf := range object { - var fieldVal interface{} - err := json.Unmarshal(fieldBuf, &fieldVal) - if err != nil { - return fmt.Errorf("error unmarshaling field %s: %w", fieldName, err) - } - a.AdditionalProperties[fieldName] = fieldVal - } - } - return nil -} - -// Override default JSON handling for AdditionalPropertiesObject3 to handle AdditionalProperties -func (a AdditionalPropertiesObject3) MarshalJSON() ([]byte, error) { - var err error - object := make(map[string]json.RawMessage) - - object["name"], err = json.Marshal(a.Name) - if err != nil { - return nil, fmt.Errorf("error marshaling 'name': %w", err) - } - - for fieldName, field := range a.AdditionalProperties { - object[fieldName], err = json.Marshal(field) - if err != nil { - return nil, fmt.Errorf("error marshaling '%s': %w", fieldName, err) - } - } - return json.Marshal(object) -} - -// Getter for additional properties for AdditionalPropertiesObject4. Returns the specified -// element and whether it was found -func (a AdditionalPropertiesObject4) Get(fieldName string) (value interface{}, found bool) { - if a.AdditionalProperties != nil { - value, found = a.AdditionalProperties[fieldName] - } - return -} - -// Setter for additional properties for AdditionalPropertiesObject4 -func (a *AdditionalPropertiesObject4) Set(fieldName string, value interface{}) { - if a.AdditionalProperties == nil { - a.AdditionalProperties = make(map[string]interface{}) - } - a.AdditionalProperties[fieldName] = value -} - -// Override default JSON handling for AdditionalPropertiesObject4 to handle AdditionalProperties -func (a *AdditionalPropertiesObject4) UnmarshalJSON(b []byte) error { - object := make(map[string]json.RawMessage) - err := json.Unmarshal(b, &object) - if err != nil { - return err - } - - if raw, found := object["inner"]; found { - err = json.Unmarshal(raw, &a.Inner) - if err != nil { - return fmt.Errorf("error reading 'inner': %w", err) - } - delete(object, "inner") - } - - if raw, found := object["name"]; found { - err = json.Unmarshal(raw, &a.Name) - if err != nil { - return fmt.Errorf("error reading 'name': %w", err) - } - delete(object, "name") - } - - if len(object) != 0 { - a.AdditionalProperties = make(map[string]interface{}) - for fieldName, fieldBuf := range object { - var fieldVal interface{} - err := json.Unmarshal(fieldBuf, &fieldVal) - if err != nil { - return fmt.Errorf("error unmarshaling field %s: %w", fieldName, err) - } - a.AdditionalProperties[fieldName] = fieldVal - } - } - return nil -} - -// Override default JSON handling for AdditionalPropertiesObject4 to handle AdditionalProperties -func (a AdditionalPropertiesObject4) MarshalJSON() ([]byte, error) { - var err error - object := make(map[string]json.RawMessage) - - object["inner"], err = json.Marshal(a.Inner) - if err != nil { - return nil, fmt.Errorf("error marshaling 'inner': %w", err) - } - - object["name"], err = json.Marshal(a.Name) - if err != nil { - return nil, fmt.Errorf("error marshaling 'name': %w", err) - } - - for fieldName, field := range a.AdditionalProperties { - object[fieldName], err = json.Marshal(field) - if err != nil { - return nil, fmt.Errorf("error marshaling '%s': %w", fieldName, err) - } - } - return json.Marshal(object) -} - -// Getter for additional properties for AdditionalPropertiesObject4_Inner. Returns the specified -// element and whether it was found -func (a AdditionalPropertiesObject4_Inner) Get(fieldName string) (value interface{}, found bool) { - if a.AdditionalProperties != nil { - value, found = a.AdditionalProperties[fieldName] - } - return -} - -// Setter for additional properties for AdditionalPropertiesObject4_Inner -func (a *AdditionalPropertiesObject4_Inner) Set(fieldName string, value interface{}) { - if a.AdditionalProperties == nil { - a.AdditionalProperties = make(map[string]interface{}) - } - a.AdditionalProperties[fieldName] = value -} - -// Override default JSON handling for AdditionalPropertiesObject4_Inner to handle AdditionalProperties -func (a *AdditionalPropertiesObject4_Inner) UnmarshalJSON(b []byte) error { - object := make(map[string]json.RawMessage) - err := json.Unmarshal(b, &object) - if err != nil { - return err - } - - if raw, found := object["name"]; found { - err = json.Unmarshal(raw, &a.Name) - if err != nil { - return fmt.Errorf("error reading 'name': %w", err) - } - delete(object, "name") - } - - if len(object) != 0 { - a.AdditionalProperties = make(map[string]interface{}) - for fieldName, fieldBuf := range object { - var fieldVal interface{} - err := json.Unmarshal(fieldBuf, &fieldVal) - if err != nil { - return fmt.Errorf("error unmarshaling field %s: %w", fieldName, err) - } - a.AdditionalProperties[fieldName] = fieldVal - } - } - return nil -} - -// Override default JSON handling for AdditionalPropertiesObject4_Inner to handle AdditionalProperties -func (a AdditionalPropertiesObject4_Inner) MarshalJSON() ([]byte, error) { - var err error - object := make(map[string]json.RawMessage) - - object["name"], err = json.Marshal(a.Name) - if err != nil { - return nil, fmt.Errorf("error marshaling 'name': %w", err) - } - - for fieldName, field := range a.AdditionalProperties { - object[fieldName], err = json.Marshal(field) - if err != nil { - return nil, fmt.Errorf("error marshaling '%s': %w", fieldName, err) - } - } - return json.Marshal(object) -} - -// Getter for additional properties for OneOfObject13. Returns the specified -// element and whether it was found -func (a OneOfObject13) Get(fieldName string) (value interface{}, found bool) { - if a.AdditionalProperties != nil { - value, found = a.AdditionalProperties[fieldName] - } - return -} - -// Setter for additional properties for OneOfObject13 -func (a *OneOfObject13) Set(fieldName string, value interface{}) { - if a.AdditionalProperties == nil { - a.AdditionalProperties = make(map[string]interface{}) - } - a.AdditionalProperties[fieldName] = value -} - -// AsOneOfVariant4 returns the union data inside the AnyOfObject1 as a OneOfVariant4 -func (t AnyOfObject1) AsOneOfVariant4() (OneOfVariant4, error) { - var body OneOfVariant4 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromOneOfVariant4 overwrites any union data inside the AnyOfObject1 as the provided OneOfVariant4 -func (t *AnyOfObject1) FromOneOfVariant4(v OneOfVariant4) error { - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeOneOfVariant4 performs a merge with any union data inside the AnyOfObject1, using the provided OneOfVariant4 -func (t *AnyOfObject1) MergeOneOfVariant4(v OneOfVariant4) error { - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -// AsOneOfVariant5 returns the union data inside the AnyOfObject1 as a OneOfVariant5 -func (t AnyOfObject1) AsOneOfVariant5() (OneOfVariant5, error) { - var body OneOfVariant5 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromOneOfVariant5 overwrites any union data inside the AnyOfObject1 as the provided OneOfVariant5 -func (t *AnyOfObject1) FromOneOfVariant5(v OneOfVariant5) error { - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeOneOfVariant5 performs a merge with any union data inside the AnyOfObject1, using the provided OneOfVariant5 -func (t *AnyOfObject1) MergeOneOfVariant5(v OneOfVariant5) error { - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -func (t AnyOfObject1) MarshalJSON() ([]byte, error) { - b, err := t.union.MarshalJSON() - return b, err -} - -func (t *AnyOfObject1) UnmarshalJSON(b []byte) error { - err := t.union.UnmarshalJSON(b) - return err -} - -// AsOneOfVariant1 returns the union data inside the OneOfObject1 as a OneOfVariant1 -func (t OneOfObject1) AsOneOfVariant1() (OneOfVariant1, error) { - var body OneOfVariant1 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromOneOfVariant1 overwrites any union data inside the OneOfObject1 as the provided OneOfVariant1 -func (t *OneOfObject1) FromOneOfVariant1(v OneOfVariant1) error { - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeOneOfVariant1 performs a merge with any union data inside the OneOfObject1, using the provided OneOfVariant1 -func (t *OneOfObject1) MergeOneOfVariant1(v OneOfVariant1) error { - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -// AsOneOfVariant2 returns the union data inside the OneOfObject1 as a OneOfVariant2 -func (t OneOfObject1) AsOneOfVariant2() (OneOfVariant2, error) { - var body OneOfVariant2 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromOneOfVariant2 overwrites any union data inside the OneOfObject1 as the provided OneOfVariant2 -func (t *OneOfObject1) FromOneOfVariant2(v OneOfVariant2) error { - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeOneOfVariant2 performs a merge with any union data inside the OneOfObject1, using the provided OneOfVariant2 -func (t *OneOfObject1) MergeOneOfVariant2(v OneOfVariant2) error { - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -// AsOneOfVariant3 returns the union data inside the OneOfObject1 as a OneOfVariant3 -func (t OneOfObject1) AsOneOfVariant3() (OneOfVariant3, error) { - var body OneOfVariant3 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromOneOfVariant3 overwrites any union data inside the OneOfObject1 as the provided OneOfVariant3 -func (t *OneOfObject1) FromOneOfVariant3(v OneOfVariant3) error { - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeOneOfVariant3 performs a merge with any union data inside the OneOfObject1, using the provided OneOfVariant3 -func (t *OneOfObject1) MergeOneOfVariant3(v OneOfVariant3) error { - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -func (t OneOfObject1) MarshalJSON() ([]byte, error) { - b, err := t.union.MarshalJSON() - return b, err -} - -func (t *OneOfObject1) UnmarshalJSON(b []byte) error { - err := t.union.UnmarshalJSON(b) - return err -} - -// AsOneOfObject100 returns the union data inside the OneOfObject10 as a OneOfObject100 -func (t OneOfObject10) AsOneOfObject100() (OneOfObject100, error) { - var body OneOfObject100 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromOneOfObject100 overwrites any union data inside the OneOfObject10 as the provided OneOfObject100 -func (t *OneOfObject10) FromOneOfObject100(v OneOfObject100) error { - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeOneOfObject100 performs a merge with any union data inside the OneOfObject10, using the provided OneOfObject100 -func (t *OneOfObject10) MergeOneOfObject100(v OneOfObject100) error { - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -// AsOneOfObject101 returns the union data inside the OneOfObject10 as a OneOfObject101 -func (t OneOfObject10) AsOneOfObject101() (OneOfObject101, error) { - var body OneOfObject101 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromOneOfObject101 overwrites any union data inside the OneOfObject10 as the provided OneOfObject101 -func (t *OneOfObject10) FromOneOfObject101(v OneOfObject101) error { - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeOneOfObject101 performs a merge with any union data inside the OneOfObject10, using the provided OneOfObject101 -func (t *OneOfObject10) MergeOneOfObject101(v OneOfObject101) error { - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -func (t OneOfObject10) MarshalJSON() ([]byte, error) { - b, err := t.union.MarshalJSON() - if err != nil { - return nil, err - } - object := make(map[string]json.RawMessage) - if t.union != nil { - err = json.Unmarshal(b, &object) - if err != nil { - return nil, err - } - } - - if t.One != nil { - object["one"], err = json.Marshal(t.One) - if err != nil { - return nil, fmt.Errorf("error marshaling 'one': %w", err) - } - } - - if t.Three != nil { - object["three"], err = json.Marshal(t.Three) - if err != nil { - return nil, fmt.Errorf("error marshaling 'three': %w", err) - } - } - - if t.Two != nil { - object["two"], err = json.Marshal(t.Two) - if err != nil { - return nil, fmt.Errorf("error marshaling 'two': %w", err) - } - } - b, err = json.Marshal(object) - return b, err -} - -func (t *OneOfObject10) UnmarshalJSON(b []byte) error { - err := t.union.UnmarshalJSON(b) - if err != nil { - return err - } - object := make(map[string]json.RawMessage) - err = json.Unmarshal(b, &object) - if err != nil { - return err - } - - if raw, found := object["one"]; found { - err = json.Unmarshal(raw, &t.One) - if err != nil { - return fmt.Errorf("error reading 'one': %w", err) - } - } - - if raw, found := object["three"]; found { - err = json.Unmarshal(raw, &t.Three) - if err != nil { - return fmt.Errorf("error reading 'three': %w", err) - } - } - - if raw, found := object["two"]; found { - err = json.Unmarshal(raw, &t.Two) - if err != nil { - return fmt.Errorf("error reading 'two': %w", err) - } - } - - return err -} - -// AsOneOfObject110 returns the union data inside the OneOfObject11_AdditionalProperties as a OneOfObject110 -func (t OneOfObject11_AdditionalProperties) AsOneOfObject110() (OneOfObject110, error) { - var body OneOfObject110 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromOneOfObject110 overwrites any union data inside the OneOfObject11_AdditionalProperties as the provided OneOfObject110 -func (t *OneOfObject11_AdditionalProperties) FromOneOfObject110(v OneOfObject110) error { - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeOneOfObject110 performs a merge with any union data inside the OneOfObject11_AdditionalProperties, using the provided OneOfObject110 -func (t *OneOfObject11_AdditionalProperties) MergeOneOfObject110(v OneOfObject110) error { - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -// AsOneOfObject111 returns the union data inside the OneOfObject11_AdditionalProperties as a OneOfObject111 -func (t OneOfObject11_AdditionalProperties) AsOneOfObject111() (OneOfObject111, error) { - var body OneOfObject111 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromOneOfObject111 overwrites any union data inside the OneOfObject11_AdditionalProperties as the provided OneOfObject111 -func (t *OneOfObject11_AdditionalProperties) FromOneOfObject111(v OneOfObject111) error { - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeOneOfObject111 performs a merge with any union data inside the OneOfObject11_AdditionalProperties, using the provided OneOfObject111 -func (t *OneOfObject11_AdditionalProperties) MergeOneOfObject111(v OneOfObject111) error { - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -// AsOneOfObject112 returns the union data inside the OneOfObject11_AdditionalProperties as a OneOfObject112 -func (t OneOfObject11_AdditionalProperties) AsOneOfObject112() (OneOfObject112, error) { - var body OneOfObject112 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromOneOfObject112 overwrites any union data inside the OneOfObject11_AdditionalProperties as the provided OneOfObject112 -func (t *OneOfObject11_AdditionalProperties) FromOneOfObject112(v OneOfObject112) error { - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeOneOfObject112 performs a merge with any union data inside the OneOfObject11_AdditionalProperties, using the provided OneOfObject112 -func (t *OneOfObject11_AdditionalProperties) MergeOneOfObject112(v OneOfObject112) error { - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -func (t OneOfObject11_AdditionalProperties) MarshalJSON() ([]byte, error) { - b, err := t.union.MarshalJSON() - return b, err -} - -func (t *OneOfObject11_AdditionalProperties) UnmarshalJSON(b []byte) error { - err := t.union.UnmarshalJSON(b) - return err -} - -// AsOneOfObject120 returns the union data inside the OneOfObject12 as a OneOfObject120 -func (t OneOfObject12) AsOneOfObject120() (OneOfObject120, error) { - var body OneOfObject120 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromOneOfObject120 overwrites any union data inside the OneOfObject12 as the provided OneOfObject120 -func (t *OneOfObject12) FromOneOfObject120(v OneOfObject120) error { - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeOneOfObject120 performs a merge with any union data inside the OneOfObject12, using the provided OneOfObject120 -func (t *OneOfObject12) MergeOneOfObject120(v OneOfObject120) error { - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -// AsOneOfObject121 returns the union data inside the OneOfObject12 as a OneOfObject121 -func (t OneOfObject12) AsOneOfObject121() (OneOfObject121, error) { - var body OneOfObject121 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromOneOfObject121 overwrites any union data inside the OneOfObject12 as the provided OneOfObject121 -func (t *OneOfObject12) FromOneOfObject121(v OneOfObject121) error { - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeOneOfObject121 performs a merge with any union data inside the OneOfObject12, using the provided OneOfObject121 -func (t *OneOfObject12) MergeOneOfObject121(v OneOfObject121) error { - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -// AsOneOfVariant3 returns the union data inside the OneOfObject12 as a OneOfVariant3 -func (t OneOfObject12) AsOneOfVariant3() (OneOfVariant3, error) { - var body OneOfVariant3 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromOneOfVariant3 overwrites any union data inside the OneOfObject12 as the provided OneOfVariant3 -func (t *OneOfObject12) FromOneOfVariant3(v OneOfVariant3) error { - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeOneOfVariant3 performs a merge with any union data inside the OneOfObject12, using the provided OneOfVariant3 -func (t *OneOfObject12) MergeOneOfVariant3(v OneOfVariant3) error { - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -// AsOneOfVariant4 returns the union data inside the OneOfObject12 as a OneOfVariant4 -func (t OneOfObject12) AsOneOfVariant4() (OneOfVariant4, error) { - var body OneOfVariant4 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromOneOfVariant4 overwrites any union data inside the OneOfObject12 as the provided OneOfVariant4 -func (t *OneOfObject12) FromOneOfVariant4(v OneOfVariant4) error { - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeOneOfVariant4 performs a merge with any union data inside the OneOfObject12, using the provided OneOfVariant4 -func (t *OneOfObject12) MergeOneOfVariant4(v OneOfVariant4) error { - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -func (t OneOfObject12) MarshalJSON() ([]byte, error) { - b, err := t.union.MarshalJSON() - return b, err -} - -func (t *OneOfObject12) UnmarshalJSON(b []byte) error { - err := t.union.UnmarshalJSON(b) - return err -} - -// AsOneOfVariant1 returns the union data inside the OneOfObject13 as a OneOfVariant1 -func (t OneOfObject13) AsOneOfVariant1() (OneOfVariant1, error) { - var body OneOfVariant1 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromOneOfVariant1 overwrites any union data inside the OneOfObject13 as the provided OneOfVariant1 -func (t *OneOfObject13) FromOneOfVariant1(v OneOfVariant1) error { - t.Type = "v1" - - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeOneOfVariant1 performs a merge with any union data inside the OneOfObject13, using the provided OneOfVariant1 -func (t *OneOfObject13) MergeOneOfVariant1(v OneOfVariant1) error { - t.Type = "v1" - - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -// AsOneOfVariant6 returns the union data inside the OneOfObject13 as a OneOfVariant6 -func (t OneOfObject13) AsOneOfVariant6() (OneOfVariant6, error) { - var body OneOfVariant6 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromOneOfVariant6 overwrites any union data inside the OneOfObject13 as the provided OneOfVariant6 -func (t *OneOfObject13) FromOneOfVariant6(v OneOfVariant6) error { - t.Type = "v6" - - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeOneOfVariant6 performs a merge with any union data inside the OneOfObject13, using the provided OneOfVariant6 -func (t *OneOfObject13) MergeOneOfVariant6(v OneOfVariant6) error { - t.Type = "v6" - - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -func (t OneOfObject13) Discriminator() (string, error) { - var discriminator struct { - Discriminator string `json:"type"` - } - err := json.Unmarshal(t.union, &discriminator) - return discriminator.Discriminator, err -} - -func (t OneOfObject13) ValueByDiscriminator() (interface{}, error) { - discriminator, err := t.Discriminator() - if err != nil { - return nil, err - } - switch discriminator { - case "v1": - return t.AsOneOfVariant1() - case "v6": - return t.AsOneOfVariant6() - default: - return nil, errors.New("unknown discriminator value: " + discriminator) - } -} - -// AsOneOfObject20 returns the union data inside the OneOfObject2 as a OneOfObject20 -func (t OneOfObject2) AsOneOfObject20() (OneOfObject20, error) { - var body OneOfObject20 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromOneOfObject20 overwrites any union data inside the OneOfObject2 as the provided OneOfObject20 -func (t *OneOfObject2) FromOneOfObject20(v OneOfObject20) error { - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeOneOfObject20 performs a merge with any union data inside the OneOfObject2, using the provided OneOfObject20 -func (t *OneOfObject2) MergeOneOfObject20(v OneOfObject20) error { - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -// AsOneOfObject21 returns the union data inside the OneOfObject2 as a OneOfObject21 -func (t OneOfObject2) AsOneOfObject21() (OneOfObject21, error) { - var body OneOfObject21 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromOneOfObject21 overwrites any union data inside the OneOfObject2 as the provided OneOfObject21 -func (t *OneOfObject2) FromOneOfObject21(v OneOfObject21) error { - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeOneOfObject21 performs a merge with any union data inside the OneOfObject2, using the provided OneOfObject21 -func (t *OneOfObject2) MergeOneOfObject21(v OneOfObject21) error { - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -// AsOneOfObject22 returns the union data inside the OneOfObject2 as a OneOfObject22 -func (t OneOfObject2) AsOneOfObject22() (OneOfObject22, error) { - var body OneOfObject22 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromOneOfObject22 overwrites any union data inside the OneOfObject2 as the provided OneOfObject22 -func (t *OneOfObject2) FromOneOfObject22(v OneOfObject22) error { - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeOneOfObject22 performs a merge with any union data inside the OneOfObject2, using the provided OneOfObject22 -func (t *OneOfObject2) MergeOneOfObject22(v OneOfObject22) error { - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -func (t OneOfObject2) MarshalJSON() ([]byte, error) { - b, err := t.union.MarshalJSON() - return b, err -} - -func (t *OneOfObject2) UnmarshalJSON(b []byte) error { - err := t.union.UnmarshalJSON(b) - return err -} - -// AsOneOfVariant1 returns the union data inside the OneOfObject3_Union as a OneOfVariant1 -func (t OneOfObject3_Union) AsOneOfVariant1() (OneOfVariant1, error) { - var body OneOfVariant1 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromOneOfVariant1 overwrites any union data inside the OneOfObject3_Union as the provided OneOfVariant1 -func (t *OneOfObject3_Union) FromOneOfVariant1(v OneOfVariant1) error { - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeOneOfVariant1 performs a merge with any union data inside the OneOfObject3_Union, using the provided OneOfVariant1 -func (t *OneOfObject3_Union) MergeOneOfVariant1(v OneOfVariant1) error { - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -// AsOneOfVariant2 returns the union data inside the OneOfObject3_Union as a OneOfVariant2 -func (t OneOfObject3_Union) AsOneOfVariant2() (OneOfVariant2, error) { - var body OneOfVariant2 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromOneOfVariant2 overwrites any union data inside the OneOfObject3_Union as the provided OneOfVariant2 -func (t *OneOfObject3_Union) FromOneOfVariant2(v OneOfVariant2) error { - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeOneOfVariant2 performs a merge with any union data inside the OneOfObject3_Union, using the provided OneOfVariant2 -func (t *OneOfObject3_Union) MergeOneOfVariant2(v OneOfVariant2) error { - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -// AsOneOfVariant3 returns the union data inside the OneOfObject3_Union as a OneOfVariant3 -func (t OneOfObject3_Union) AsOneOfVariant3() (OneOfVariant3, error) { - var body OneOfVariant3 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromOneOfVariant3 overwrites any union data inside the OneOfObject3_Union as the provided OneOfVariant3 -func (t *OneOfObject3_Union) FromOneOfVariant3(v OneOfVariant3) error { - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeOneOfVariant3 performs a merge with any union data inside the OneOfObject3_Union, using the provided OneOfVariant3 -func (t *OneOfObject3_Union) MergeOneOfVariant3(v OneOfVariant3) error { - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -func (t OneOfObject3_Union) MarshalJSON() ([]byte, error) { - b, err := t.union.MarshalJSON() - return b, err -} - -func (t *OneOfObject3_Union) UnmarshalJSON(b []byte) error { - err := t.union.UnmarshalJSON(b) - return err -} - -// AsOneOfVariant1 returns the union data inside the OneOfObject4 as a OneOfVariant1 -func (t OneOfObject4) AsOneOfVariant1() (OneOfVariant1, error) { - var body OneOfVariant1 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromOneOfVariant1 overwrites any union data inside the OneOfObject4 as the provided OneOfVariant1 -func (t *OneOfObject4) FromOneOfVariant1(v OneOfVariant1) error { - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeOneOfVariant1 performs a merge with any union data inside the OneOfObject4, using the provided OneOfVariant1 -func (t *OneOfObject4) MergeOneOfVariant1(v OneOfVariant1) error { - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -// AsOneOfVariant2 returns the union data inside the OneOfObject4 as a OneOfVariant2 -func (t OneOfObject4) AsOneOfVariant2() (OneOfVariant2, error) { - var body OneOfVariant2 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromOneOfVariant2 overwrites any union data inside the OneOfObject4 as the provided OneOfVariant2 -func (t *OneOfObject4) FromOneOfVariant2(v OneOfVariant2) error { - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeOneOfVariant2 performs a merge with any union data inside the OneOfObject4, using the provided OneOfVariant2 -func (t *OneOfObject4) MergeOneOfVariant2(v OneOfVariant2) error { - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -// AsOneOfVariant3 returns the union data inside the OneOfObject4 as a OneOfVariant3 -func (t OneOfObject4) AsOneOfVariant3() (OneOfVariant3, error) { - var body OneOfVariant3 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromOneOfVariant3 overwrites any union data inside the OneOfObject4 as the provided OneOfVariant3 -func (t *OneOfObject4) FromOneOfVariant3(v OneOfVariant3) error { - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeOneOfVariant3 performs a merge with any union data inside the OneOfObject4, using the provided OneOfVariant3 -func (t *OneOfObject4) MergeOneOfVariant3(v OneOfVariant3) error { - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -func (t OneOfObject4) MarshalJSON() ([]byte, error) { - b, err := t.union.MarshalJSON() - if err != nil { - return nil, err - } - object := make(map[string]json.RawMessage) - if t.union != nil { - err = json.Unmarshal(b, &object) - if err != nil { - return nil, err - } - } - - if t.FixedProperty != nil { - object["fixedProperty"], err = json.Marshal(t.FixedProperty) - if err != nil { - return nil, fmt.Errorf("error marshaling 'fixedProperty': %w", err) - } - } - b, err = json.Marshal(object) - return b, err -} - -func (t *OneOfObject4) UnmarshalJSON(b []byte) error { - err := t.union.UnmarshalJSON(b) - if err != nil { - return err - } - object := make(map[string]json.RawMessage) - err = json.Unmarshal(b, &object) - if err != nil { - return err - } - - if raw, found := object["fixedProperty"]; found { - err = json.Unmarshal(raw, &t.FixedProperty) - if err != nil { - return fmt.Errorf("error reading 'fixedProperty': %w", err) - } - } - - return err -} - -// AsOneOfVariant4 returns the union data inside the OneOfObject5 as a OneOfVariant4 -func (t OneOfObject5) AsOneOfVariant4() (OneOfVariant4, error) { - var body OneOfVariant4 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromOneOfVariant4 overwrites any union data inside the OneOfObject5 as the provided OneOfVariant4 -func (t *OneOfObject5) FromOneOfVariant4(v OneOfVariant4) error { - v.Discriminator = "OneOfVariant4" - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeOneOfVariant4 performs a merge with any union data inside the OneOfObject5, using the provided OneOfVariant4 -func (t *OneOfObject5) MergeOneOfVariant4(v OneOfVariant4) error { - v.Discriminator = "OneOfVariant4" - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -// AsOneOfVariant5 returns the union data inside the OneOfObject5 as a OneOfVariant5 -func (t OneOfObject5) AsOneOfVariant5() (OneOfVariant5, error) { - var body OneOfVariant5 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromOneOfVariant5 overwrites any union data inside the OneOfObject5 as the provided OneOfVariant5 -func (t *OneOfObject5) FromOneOfVariant5(v OneOfVariant5) error { - v.Discriminator = "OneOfVariant5" - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeOneOfVariant5 performs a merge with any union data inside the OneOfObject5, using the provided OneOfVariant5 -func (t *OneOfObject5) MergeOneOfVariant5(v OneOfVariant5) error { - v.Discriminator = "OneOfVariant5" - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -func (t OneOfObject5) Discriminator() (string, error) { - var discriminator struct { - Discriminator string `json:"discriminator"` - } - err := json.Unmarshal(t.union, &discriminator) - return discriminator.Discriminator, err -} - -func (t OneOfObject5) ValueByDiscriminator() (interface{}, error) { - discriminator, err := t.Discriminator() - if err != nil { - return nil, err - } - switch discriminator { - case "OneOfVariant4": - return t.AsOneOfVariant4() - case "OneOfVariant5": - return t.AsOneOfVariant5() - default: - return nil, errors.New("unknown discriminator value: " + discriminator) - } -} - -func (t OneOfObject5) MarshalJSON() ([]byte, error) { - b, err := t.union.MarshalJSON() - return b, err -} - -func (t *OneOfObject5) UnmarshalJSON(b []byte) error { - err := t.union.UnmarshalJSON(b) - return err -} - -// AsOneOfVariant4 returns the union data inside the OneOfObject6 as a OneOfVariant4 -func (t OneOfObject6) AsOneOfVariant4() (OneOfVariant4, error) { - var body OneOfVariant4 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromOneOfVariant4 overwrites any union data inside the OneOfObject6 as the provided OneOfVariant4 -func (t *OneOfObject6) FromOneOfVariant4(v OneOfVariant4) error { - v.Discriminator = "v4" - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeOneOfVariant4 performs a merge with any union data inside the OneOfObject6, using the provided OneOfVariant4 -func (t *OneOfObject6) MergeOneOfVariant4(v OneOfVariant4) error { - v.Discriminator = "v4" - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -// AsOneOfVariant5 returns the union data inside the OneOfObject6 as a OneOfVariant5 -func (t OneOfObject6) AsOneOfVariant5() (OneOfVariant5, error) { - var body OneOfVariant5 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromOneOfVariant5 overwrites any union data inside the OneOfObject6 as the provided OneOfVariant5 -func (t *OneOfObject6) FromOneOfVariant5(v OneOfVariant5) error { - v.Discriminator = "v5" - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeOneOfVariant5 performs a merge with any union data inside the OneOfObject6, using the provided OneOfVariant5 -func (t *OneOfObject6) MergeOneOfVariant5(v OneOfVariant5) error { - v.Discriminator = "v5" - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -func (t OneOfObject6) Discriminator() (string, error) { - var discriminator struct { - Discriminator string `json:"discriminator"` - } - err := json.Unmarshal(t.union, &discriminator) - return discriminator.Discriminator, err -} - -func (t OneOfObject6) ValueByDiscriminator() (interface{}, error) { - discriminator, err := t.Discriminator() - if err != nil { - return nil, err - } - switch discriminator { - case "v4": - return t.AsOneOfVariant4() - case "v5": - return t.AsOneOfVariant5() - default: - return nil, errors.New("unknown discriminator value: " + discriminator) - } -} - -func (t OneOfObject6) MarshalJSON() ([]byte, error) { - b, err := t.union.MarshalJSON() - return b, err -} - -func (t *OneOfObject6) UnmarshalJSON(b []byte) error { - err := t.union.UnmarshalJSON(b) - return err -} - -// AsOneOfVariant4 returns the union data inside the OneOfObject61 as a OneOfVariant4 -func (t OneOfObject61) AsOneOfVariant4() (OneOfVariant4, error) { - var body OneOfVariant4 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromOneOfVariant4 overwrites any union data inside the OneOfObject61 as the provided OneOfVariant4 -func (t *OneOfObject61) FromOneOfVariant4(v OneOfVariant4) error { - v.Discriminator = "v4" - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeOneOfVariant4 performs a merge with any union data inside the OneOfObject61, using the provided OneOfVariant4 -func (t *OneOfObject61) MergeOneOfVariant4(v OneOfVariant4) error { - v.Discriminator = "v4" - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -// AsOneOfVariant5 returns the union data inside the OneOfObject61 as a OneOfVariant5 -func (t OneOfObject61) AsOneOfVariant5() (OneOfVariant5, error) { - var body OneOfVariant5 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromOneOfVariant5 overwrites any union data inside the OneOfObject61 as the provided OneOfVariant5 -func (t *OneOfObject61) FromOneOfVariant5(v OneOfVariant5) error { - v.Discriminator = "OneOfVariant5" - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeOneOfVariant5 performs a merge with any union data inside the OneOfObject61, using the provided OneOfVariant5 -func (t *OneOfObject61) MergeOneOfVariant5(v OneOfVariant5) error { - v.Discriminator = "OneOfVariant5" - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -func (t OneOfObject61) Discriminator() (string, error) { - var discriminator struct { - Discriminator string `json:"discriminator"` - } - err := json.Unmarshal(t.union, &discriminator) - return discriminator.Discriminator, err -} - -func (t OneOfObject61) ValueByDiscriminator() (interface{}, error) { - discriminator, err := t.Discriminator() - if err != nil { - return nil, err - } - switch discriminator { - case "OneOfVariant5": - return t.AsOneOfVariant5() - case "v4": - return t.AsOneOfVariant4() - default: - return nil, errors.New("unknown discriminator value: " + discriminator) - } -} - -func (t OneOfObject61) MarshalJSON() ([]byte, error) { - b, err := t.union.MarshalJSON() - return b, err -} - -func (t *OneOfObject61) UnmarshalJSON(b []byte) error { - err := t.union.UnmarshalJSON(b) - return err -} - -// AsOneOfVariant4 returns the union data inside the OneOfObject62 as a OneOfVariant4 -func (t OneOfObject62) AsOneOfVariant4() (OneOfVariant4, error) { - var body OneOfVariant4 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromOneOfVariant4 overwrites any union data inside the OneOfObject62 as the provided OneOfVariant4 -func (t *OneOfObject62) FromOneOfVariant4(v OneOfVariant4) error { - v.Discriminator = "variant_four" - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeOneOfVariant4 performs a merge with any union data inside the OneOfObject62, using the provided OneOfVariant4 -func (t *OneOfObject62) MergeOneOfVariant4(v OneOfVariant4) error { - v.Discriminator = "variant_four" - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -// AsOneOfVariant51 returns the union data inside the OneOfObject62 as a OneOfVariant51 -func (t OneOfObject62) AsOneOfVariant51() (OneOfVariant51, error) { - var body OneOfVariant51 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromOneOfVariant51 overwrites any union data inside the OneOfObject62 as the provided OneOfVariant51 -func (t *OneOfObject62) FromOneOfVariant51(v OneOfVariant51) error { - v.Discriminator = "one_of_variant51" - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeOneOfVariant51 performs a merge with any union data inside the OneOfObject62, using the provided OneOfVariant51 -func (t *OneOfObject62) MergeOneOfVariant51(v OneOfVariant51) error { - v.Discriminator = "one_of_variant51" - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -func (t OneOfObject62) Discriminator() (string, error) { - var discriminator struct { - Discriminator string `json:"discriminator"` - } - err := json.Unmarshal(t.union, &discriminator) - return discriminator.Discriminator, err -} - -func (t OneOfObject62) ValueByDiscriminator() (interface{}, error) { - discriminator, err := t.Discriminator() - if err != nil { - return nil, err - } - switch discriminator { - case "one_of_variant51": - return t.AsOneOfVariant51() - case "variant_four": - return t.AsOneOfVariant4() - default: - return nil, errors.New("unknown discriminator value: " + discriminator) - } -} - -func (t OneOfObject62) MarshalJSON() ([]byte, error) { - b, err := t.union.MarshalJSON() - return b, err -} - -func (t *OneOfObject62) UnmarshalJSON(b []byte) error { - err := t.union.UnmarshalJSON(b) - return err -} - -// AsOneOfVariant1 returns the union data inside the OneOfObject7_Item as a OneOfVariant1 -func (t OneOfObject7_Item) AsOneOfVariant1() (OneOfVariant1, error) { - var body OneOfVariant1 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromOneOfVariant1 overwrites any union data inside the OneOfObject7_Item as the provided OneOfVariant1 -func (t *OneOfObject7_Item) FromOneOfVariant1(v OneOfVariant1) error { - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeOneOfVariant1 performs a merge with any union data inside the OneOfObject7_Item, using the provided OneOfVariant1 -func (t *OneOfObject7_Item) MergeOneOfVariant1(v OneOfVariant1) error { - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -// AsOneOfVariant2 returns the union data inside the OneOfObject7_Item as a OneOfVariant2 -func (t OneOfObject7_Item) AsOneOfVariant2() (OneOfVariant2, error) { - var body OneOfVariant2 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromOneOfVariant2 overwrites any union data inside the OneOfObject7_Item as the provided OneOfVariant2 -func (t *OneOfObject7_Item) FromOneOfVariant2(v OneOfVariant2) error { - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeOneOfVariant2 performs a merge with any union data inside the OneOfObject7_Item, using the provided OneOfVariant2 -func (t *OneOfObject7_Item) MergeOneOfVariant2(v OneOfVariant2) error { - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -func (t OneOfObject7_Item) MarshalJSON() ([]byte, error) { - b, err := t.union.MarshalJSON() - return b, err -} - -func (t *OneOfObject7_Item) UnmarshalJSON(b []byte) error { - err := t.union.UnmarshalJSON(b) - return err -} - -// AsOneOfVariant1 returns the union data inside the OneOfObject8 as a OneOfVariant1 -func (t OneOfObject8) AsOneOfVariant1() (OneOfVariant1, error) { - var body OneOfVariant1 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromOneOfVariant1 overwrites any union data inside the OneOfObject8 as the provided OneOfVariant1 -func (t *OneOfObject8) FromOneOfVariant1(v OneOfVariant1) error { - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeOneOfVariant1 performs a merge with any union data inside the OneOfObject8, using the provided OneOfVariant1 -func (t *OneOfObject8) MergeOneOfVariant1(v OneOfVariant1) error { - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -// AsOneOfVariant2 returns the union data inside the OneOfObject8 as a OneOfVariant2 -func (t OneOfObject8) AsOneOfVariant2() (OneOfVariant2, error) { - var body OneOfVariant2 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromOneOfVariant2 overwrites any union data inside the OneOfObject8 as the provided OneOfVariant2 -func (t *OneOfObject8) FromOneOfVariant2(v OneOfVariant2) error { - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeOneOfVariant2 performs a merge with any union data inside the OneOfObject8, using the provided OneOfVariant2 -func (t *OneOfObject8) MergeOneOfVariant2(v OneOfVariant2) error { - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -func (t OneOfObject8) MarshalJSON() ([]byte, error) { - b, err := t.union.MarshalJSON() - if err != nil { - return nil, err - } - object := make(map[string]json.RawMessage) - if t.union != nil { - err = json.Unmarshal(b, &object) - if err != nil { - return nil, err - } - } - - if t.Fixed != nil { - object["fixed"], err = json.Marshal(t.Fixed) - if err != nil { - return nil, fmt.Errorf("error marshaling 'fixed': %w", err) - } - } - b, err = json.Marshal(object) - return b, err -} - -func (t *OneOfObject8) UnmarshalJSON(b []byte) error { - err := t.union.UnmarshalJSON(b) - if err != nil { - return err - } - object := make(map[string]json.RawMessage) - err = json.Unmarshal(b, &object) - if err != nil { - return err - } - - if raw, found := object["fixed"]; found { - err = json.Unmarshal(raw, &t.Fixed) - if err != nil { - return fmt.Errorf("error reading 'fixed': %w", err) - } - } - - return err -} - -// AsOneOfVariant1 returns the union data inside the OneOfObject9 as a OneOfVariant1 -func (t OneOfObject9) AsOneOfVariant1() (OneOfVariant1, error) { - var body OneOfVariant1 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromOneOfVariant1 overwrites any union data inside the OneOfObject9 as the provided OneOfVariant1 -func (t *OneOfObject9) FromOneOfVariant1(v OneOfVariant1) error { - t.Type = "v1" - - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeOneOfVariant1 performs a merge with any union data inside the OneOfObject9, using the provided OneOfVariant1 -func (t *OneOfObject9) MergeOneOfVariant1(v OneOfVariant1) error { - t.Type = "v1" - - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -// AsOneOfVariant6 returns the union data inside the OneOfObject9 as a OneOfVariant6 -func (t OneOfObject9) AsOneOfVariant6() (OneOfVariant6, error) { - var body OneOfVariant6 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromOneOfVariant6 overwrites any union data inside the OneOfObject9 as the provided OneOfVariant6 -func (t *OneOfObject9) FromOneOfVariant6(v OneOfVariant6) error { - t.Type = "v6" - - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeOneOfVariant6 performs a merge with any union data inside the OneOfObject9, using the provided OneOfVariant6 -func (t *OneOfObject9) MergeOneOfVariant6(v OneOfVariant6) error { - t.Type = "v6" - - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -func (t OneOfObject9) Discriminator() (string, error) { - var discriminator struct { - Discriminator string `json:"type"` - } - err := json.Unmarshal(t.union, &discriminator) - return discriminator.Discriminator, err -} - -func (t OneOfObject9) ValueByDiscriminator() (interface{}, error) { - discriminator, err := t.Discriminator() - if err != nil { - return nil, err - } - switch discriminator { - case "v1": - return t.AsOneOfVariant1() - case "v6": - return t.AsOneOfVariant6() - default: - return nil, errors.New("unknown discriminator value: " + discriminator) - } -} - -func (t OneOfObject9) MarshalJSON() ([]byte, error) { - b, err := t.union.MarshalJSON() - if err != nil { - return nil, err - } - object := make(map[string]json.RawMessage) - if t.union != nil { - err = json.Unmarshal(b, &object) - if err != nil { - return nil, err - } - } - - object["type"], err = json.Marshal(t.Type) - if err != nil { - return nil, fmt.Errorf("error marshaling 'type': %w", err) - } - - b, err = json.Marshal(object) - return b, err -} - -func (t *OneOfObject9) UnmarshalJSON(b []byte) error { - err := t.union.UnmarshalJSON(b) - if err != nil { - return err - } - object := make(map[string]json.RawMessage) - err = json.Unmarshal(b, &object) - if err != nil { - return err - } - - if raw, found := object["type"]; found { - err = json.Unmarshal(raw, &t.Type) - if err != nil { - return fmt.Errorf("error reading 'type': %w", err) - } - } - - return err -} - -// Override default JSON handling for OneOfObject13 to handle AdditionalProperties and union -func (a *OneOfObject13) UnmarshalJSON(b []byte) error { - err := a.union.UnmarshalJSON(b) - if err != nil { - return err - } - object := make(map[string]json.RawMessage) - err = json.Unmarshal(b, &object) - if err != nil { - return err - } - - if raw, found := object["type"]; found { - err = json.Unmarshal(raw, &a.Type) - if err != nil { - return fmt.Errorf("error reading 'type': %w", err) - } - delete(object, "type") - } - - if len(object) != 0 { - a.AdditionalProperties = make(map[string]interface{}) - for fieldName, fieldBuf := range object { - var fieldVal interface{} - err := json.Unmarshal(fieldBuf, &fieldVal) - if err != nil { - return fmt.Errorf("error unmarshaling field %s: %w", fieldName, err) - } - a.AdditionalProperties[fieldName] = fieldVal - } - } - return nil -} - -// Override default JSON handling for OneOfObject13 to handle AdditionalProperties and union -func (a OneOfObject13) MarshalJSON() ([]byte, error) { - var err error - b, err := a.union.MarshalJSON() - if err != nil { - return nil, err - } - object := make(map[string]json.RawMessage) - if a.union != nil { - err = json.Unmarshal(b, &object) - if err != nil { - return nil, err - } - } - - object["type"], err = json.Marshal(a.Type) - if err != nil { - return nil, fmt.Errorf("error marshaling 'type': %w", err) - } - - for fieldName, field := range a.AdditionalProperties { - object[fieldName], err = json.Marshal(field) - if err != nil { - return nil, fmt.Errorf("error marshaling '%s': %w", fieldName, err) - } - } - return json.Marshal(object) -} diff --git a/internal/test/components/components.yaml b/internal/test/components/components.yaml deleted file mode 100644 index f711510e37..0000000000 --- a/internal/test/components/components.yaml +++ /dev/null @@ -1,585 +0,0 @@ -openapi: "3.0.1" -info: - version: 1.0.0 - title: Test Server - license: - name: MIT -paths: - /ensure-everything-is-referenced: - get: - operationId: ensureEverythingIsReferenced - description: | - This endpoint exists so that components can be created in this - spec and not be pruned - # TODO: figure out why uncommenting this causes failures - # parameters: - # - $ref: "#/components/parameters/ParameterObject" - requestBody: - $ref: "#/components/requestBodies/RequestBody" - responses: - 200: - description: placeholder - content: - application/json: - schema: - type: object - properties: - one: - $ref: "#/components/schemas/AdditionalPropertiesObject1" - two: - $ref: "#/components/schemas/AdditionalPropertiesObject2" - three: - $ref: "#/components/schemas/AdditionalPropertiesObject3" - four: - $ref: "#/components/schemas/AdditionalPropertiesObject4" - five: - $ref: "#/components/schemas/AdditionalPropertiesObject5" - six: - $ref: "#/components/schemas/AdditionalPropertiesObject6" - oneOf1: - $ref: "#/components/schemas/OneOfObject1" - oneOf2: - $ref: "#/components/schemas/OneOfObject2" - oneOf3: - $ref: "#/components/schemas/OneOfObject3" - oneOf4: - $ref: "#/components/schemas/OneOfObject4" - oneOf5: - $ref: "#/components/schemas/OneOfObject5" - oneOf6: - $ref: "#/components/schemas/OneOfObject6" - oneOf7: - $ref: "#/components/schemas/OneOfObject7" - oneOf8: - $ref: "#/components/schemas/OneOfObject8" - oneOf9: - $ref: "#/components/schemas/OneOfObject9" - oneOf10: - $ref: "#/components/schemas/OneOfObject10" - oneOf11: - $ref: "#/components/schemas/OneOfObject11" - oneOf12: - $ref: "#/components/schemas/OneOfObject12" - anyOf1: - $ref: "#/components/schemas/AnyOfObject1" - jsonField: - $ref: "#/components/schemas/ObjectWithJsonField" - default: - $ref: "#/components/responses/ResponseObject" - /params_with_add_props: - get: - operationId: ParamsWithAddProps - description: | - A path with parameters and a body which require additional properties - parameters: - - name: p1 - description: | - This parameter has additional properties - in: query - required: true - style: simple - schema: - type: object - additionalProperties: true - - name: p2 - description: | - This parameter has an anonymous inner property which needs to be - turned into a proper type for additionalProperties to work - in: query - required: true - schema: - properties: - inner: - type: object - additionalProperties: - type: string - required: [ inner ] - responses: - default: - description: placeholder - content: - text/plain: - schema: - type: string - post: - operationId: BodyWithAddProps - description: | - Has a request body which contains a direct additionalProperties, and - an anonymous inner property with additionalProperties - requestBody: - required: true - content: - application/json: - schema: - properties: - name: - type: string - inner: - type: object - additionalProperties: - type: integer - required: [ name, inner ] - additionalProperties: true - responses: - default: - description: placeholder - content: - text/plain: - schema: - type: string -components: - schemas: - SchemaObject: - properties: - role: - type: string - firstName: - type: string - readOnlyRequiredProp: - description: | - This property is required and readOnly, so the go model should have it as a pointer, - as it will not be included when it is sent from client to server. - type: string - readOnly: true - writeOnlyRequiredProp: - type: integer - writeOnly: true - required: - - role - - firstName - - readOnlyRequiredProp - - writeOnlyRequiredProp - SchemaObjectNullable: - properties: - role: - type: string - firstName: - type: string - readOnlyRequiredProp: - description: | - This property is required and readOnly, so the go model should have it as a pointer, - as it will not be included when it is sent from client to server. - type: string - readOnly: true - writeOnlyRequiredProp: - type: integer - writeOnly: true - required: - - role - - firstName - - readOnlyRequiredProp - - writeOnlyRequiredProp - nullable: true - AdditionalPropertiesObject1: - description: Has additional properties of type int - type: object - properties: - name: - type: string - id: - type: integer - optional: - type: string - required: [ name, id ] - additionalProperties: - type: integer - AdditionalPropertiesObject2: - description: Does not allow additional properties - type: object - properties: - name: - type: string - id: - type: integer - required: [ name, id ] - additionalProperties: false - AdditionalPropertiesObject3: - description: Allows any additional property - type: object - properties: - name: - type: string - required: [ name ] - additionalProperties: true - AdditionalPropertiesObject4: - description: Has anonymous field which has additional properties - type: object - properties: - name: - type: string - inner: - type: object - properties: - name: - type: string - required: [ name ] - additionalProperties: true - required: [ inner, name ] - additionalProperties: true - AdditionalPropertiesObject5: - description: Has additional properties with schema for dictionaries - type: object - additionalProperties: - $ref: '#/components/schemas/SchemaObject' - AdditionalPropertiesObject6: - description: Array of object with additional properties - type: array - items: - type: object - additionalProperties: - $ref: '#/components/schemas/SchemaObject' - AdditionalPropertiesObject7: - description: Has additional properties with schema for dictionaries - type: object - additionalProperties: - $ref: '#/components/schemas/SchemaObjectNullable' - OneOfObject1: - description: oneOf with references and no discriminator - oneOf: - - $ref: '#/components/schemas/OneOfVariant1' - - $ref: '#/components/schemas/OneOfVariant2' - - $ref: '#/components/schemas/OneOfVariant3' - OneOfObject2: - description: oneOf with inline elements - oneOf: - - type: object - properties: - name: - type: string - - type: array - items: - type: number - - type: boolean - OneOfObject3: - description: inline OneOf - type: object - properties: - union: - oneOf: - - $ref: '#/components/schemas/OneOfVariant1' - - $ref: '#/components/schemas/OneOfVariant2' - - $ref: '#/components/schemas/OneOfVariant3' - OneOfObject4: - description: oneOf plus fixed type - custom marshaling/unmarshaling - type: object - properties: - fixedProperty: - type: string - oneOf: - - $ref: '#/components/schemas/OneOfVariant1' - - $ref: '#/components/schemas/OneOfVariant2' - - $ref: '#/components/schemas/OneOfVariant3' - OneOfObject5: - description: oneOf with discriminator but no mapping - oneOf: - - $ref: '#/components/schemas/OneOfVariant4' - - $ref: '#/components/schemas/OneOfVariant5' - discriminator: - propertyName: discriminator - OneOfObject6: - description: oneOf with discriminator and mapping - oneOf: - - $ref: '#/components/schemas/OneOfVariant4' - - $ref: '#/components/schemas/OneOfVariant5' - discriminator: - propertyName: discriminator - mapping: - v4: '#/components/schemas/OneOfVariant4' - v5: '#/components/schemas/OneOfVariant5' - OneOfObject61: - description: oneOf with discriminator and partial mapping - oneOf: - - $ref: '#/components/schemas/OneOfVariant4' - - $ref: '#/components/schemas/OneOfVariant5' - discriminator: - propertyName: discriminator - mapping: - v4: '#/components/schemas/OneOfVariant4' - OneOfObject62: - description: oneOf with snake_case discriminator and partial snake_case mapping - oneOf: - - $ref: '#/components/schemas/OneOfVariant4' - - $ref: '#/components/schemas/one_of_variant51' - discriminator: - propertyName: discriminator - mapping: - variant_four: '#/components/schemas/OneOfVariant4' - OneOfObject7: - description: array of oneOf - type: array - items: - oneOf: - - $ref: '#/components/schemas/OneOfVariant1' - - $ref: '#/components/schemas/OneOfVariant2' - OneOfObject8: - description: oneOf with fixed properties - type: object - properties: - fixed: - type: string - oneOf: - - $ref: '#/components/schemas/OneOfVariant1' - - $ref: '#/components/schemas/OneOfVariant2' - OneOfObject9: - description: oneOf with fixed discriminator - type: object - properties: - type: - type: string - oneOf: - - $ref: '#/components/schemas/OneOfVariant1' - - $ref: '#/components/schemas/OneOfVariant6' - discriminator: - propertyName: type - mapping: - v1: '#/components/schemas/OneOfVariant1' - v6: '#/components/schemas/OneOfVariant6' - required: - - type - OneOfObject10: - description: fixed properties, variable required - will compile, but not much sense - type: object - properties: - one: - type: string - two: - type: integer - three: - type: boolean - oneOf: - - required: - - one - - required: - - two - - three - OneOfObject11: - description: additional properties of oneOf - type: object - additionalProperties: - oneOf: - - type: boolean - - type: number - - type: string - OneOfObject12: - description: allOf of oneOfs - allOf: - - oneOf: - - type: string - - type: number - - oneOf: - - $ref: '#/components/schemas/OneOfVariant3' - - $ref: '#/components/schemas/OneOfVariant4' - OneOfObject13: - description: oneOf with fixed discriminator and other fields allowed - type: object - properties: - type: - type: string - oneOf: - - $ref: '#/components/schemas/OneOfVariant1' - - $ref: '#/components/schemas/OneOfVariant6' - discriminator: - propertyName: type - mapping: - v1: '#/components/schemas/OneOfVariant1' - v6: '#/components/schemas/OneOfVariant6' - required: - - type - additionalProperties: true - AnyOfObject1: - description: simple anyOf case - anyOf: - - $ref: '#/components/schemas/OneOfVariant4' - - $ref: '#/components/schemas/OneOfVariant5' - OneOfVariant1: - type: object - properties: - name: - type: string - required: - - name - OneOfVariant2: - type: array - items: - type: integer - OneOfVariant3: - type: boolean - OneOfVariant4: - type: object - properties: - discriminator: - type: string - name: - type: string - required: - - discriminator - - name - OneOfVariant5: - type: object - properties: - discriminator: - type: string - id: - type: integer - required: - - discriminator - - id - one_of_variant51: - type: object - properties: - discriminator: - type: string - id: - type: integer - required: - - discriminator - - id - OneOfVariant6: - type: object - properties: - values: - $ref: '#/components/schemas/OneOfVariant2' - required: - - values - ObjectWithJsonField: - type: object - properties: - name: - type: string - value1: - type: string - format: json - value2: - type: string - format: json - required: [ name, value1 ] - Enum1: - description: | - Conflicts with Enum2, enum values need to be prefixed with type - name. - type: string - enum: [ One, Two, Three ] - Enum2: - description: | - Conflicts with Enum1, enum values need to be prefixed with type - name. - type: string - enum: [ Two, Three, Four ] - Enum3: - description: | - Enum values conflict with Enums above, need to be prefixed - with type name. - type: string - enum: [ Enum1One, Foo, Bar ] - Enum4: - description: | - No conflicts here, should have unmodified enums - type: string - enum: [ Cat, Dog, Mouse ] - Enum5: - description: | - Numerical enum - type: integer - enum: [ 5, 6, 7 ] - EnumUnion: - description: | - Two enums of the same type combined with allOf. - allOf: - - $ref: "#/components/schemas/Enum1" - - $ref: "#/components/schemas/Enum2" - EnumUnion2: - description: | - Two enums of the same type combined with allOf. - allOf: - - $ref: "#/components/schemas/Enum1" - - enum: [ Seven ] - FunnyValues: - description: Edge cases for enum names - type: string - enum: - - '*' - - '5' - - '&' - - '%' - - '' - RenameMe: - description: This schema should be renamed via x-go-name when generating - x-go-name: NewName - type: object - properties: - prop1: - type: string - prop2: - type: string - required: [ prop1, prop2 ] - ReferenceToRenameMe: - description: When a Schema is renamed, $ref should refer to the new name - type: object - properties: - ToNewName: - $ref: "#/components/schemas/RenameMe" - required: [ ToNewName ] - responses: - ResponseObject: - x-go-name: RenamedResponseObject - description: A simple response object - content: - application/json: - schema: - properties: - Field: - $ref: "#/components/schemas/SchemaObject" - required: [ Field ] - text/plain: - schema: - type: string - parameters: - ParameterObject: - x-go-name: RenamedParameterObject - name: ParameterObject - description: a parameter - in: query - content: - application/json: - schema: - properties: - Field: - $ref: "#/components/schemas/SchemaObject" - required: [ Field ] - text/plain: - schema: - type: string - EnumParam1: - name: ParamEnum1 - description: a parameter - in: query - schema: - type: string - enum: [ on, off, both ] - EnumParam2: - name: ParamEnum2 - description: a parameter - in: query - schema: - type: string - enum: [ on, off, both ] - EnumParam3: - name: ParamEnum3 - description: a parameter - in: query - schema: - type: string - enum: [ alice, eve, bob ] - requestBodies: - RequestBody: - x-go-name: RenamedRequestBody - content: - application/json: - schema: - properties: - Field: - $ref: "#/components/schemas/SchemaObject" - required: [ Field ] - text/plain: - schema: - type: string diff --git a/internal/test/components/components_test.go b/internal/test/components/components_test.go deleted file mode 100644 index 268612a3d6..0000000000 --- a/internal/test/components/components_test.go +++ /dev/null @@ -1,361 +0,0 @@ -package components - -import ( - "encoding/json" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func assertJsonEqual(t *testing.T, j1 []byte, j2 []byte) { - t.Helper() - assert.JSONEq(t, string(j1), string(j2)) -} - -func TestRawJSON(t *testing.T) { - // Check raw json unmarshaling - const buf = `{"name":"bob","value1":{"present":true}}` - var dst ObjectWithJsonField - err := json.Unmarshal([]byte(buf), &dst) - assert.NoError(t, err) - - buf2, err := json.Marshal(dst) - assert.NoError(t, err) - - assertJsonEqual(t, []byte(buf), buf2) - -} - -func TestAdditionalProperties(t *testing.T) { - buf := `{"name": "bob", "id": 5, "optional":"yes", "additional": 42}` - var dst AdditionalPropertiesObject1 - err := json.Unmarshal([]byte(buf), &dst) - assert.NoError(t, err) - assert.Equal(t, "bob", dst.Name) - assert.Equal(t, 5, dst.Id) - assert.Equal(t, "yes", *dst.Optional) - additional, found := dst.Get("additional") - assert.True(t, found) - assert.Equal(t, 42, additional) - - obj4 := AdditionalPropertiesObject4{ - Name: "bob", - } - obj4.Set("add1", "hi") - obj4.Set("add2", 7) - - foo, found := obj4.Get("add1") - assert.True(t, found) - assert.EqualValues(t, "hi", foo) - foo, found = obj4.Get("add2") - assert.True(t, found) - assert.EqualValues(t, 7, foo) - - // test that additionalProperties that reference a schema work when unmarshaling - bossSchema := SchemaObject{ - FirstName: "bob", - Role: "warehouse manager", - } - - buf2 := `{"boss": { "firstName": "bob", "role": "warehouse manager" }, "employee": { "firstName": "kevin", "role": "warehouse"}}` - var obj5 AdditionalPropertiesObject5 - err = json.Unmarshal([]byte(buf2), &obj5) - assert.NoError(t, err) - assert.Equal(t, bossSchema, obj5["boss"]) - - bossSchemaNullable := &SchemaObjectNullable{ - FirstName: "bob", - Role: "warehouse manager", - } - - buf3 := `{"boss": { "firstName": "bob", "role": "warehouse manager" }, "employee": null}` - var obj7 AdditionalPropertiesObject7 - err = json.Unmarshal([]byte(buf3), &obj7) - assert.NoError(t, err) - employee, ok := obj7["employee"] - assert.True(t, ok) - assert.Equal(t, bossSchemaNullable, obj7["boss"]) - assert.Nil(t, employee) -} - -func TestOneOf(t *testing.T) { - const variant1 = `{"name": "123"}` - const variant2 = `[1, 2, 3]` - const variant3 = `true` - var dst OneOfObject1 - - err := json.Unmarshal([]byte(variant1), &dst) - assert.NoError(t, err) - v1, err := dst.AsOneOfVariant1() - assert.NoError(t, err) - assert.Equal(t, "123", v1.Name) - - err = json.Unmarshal([]byte(variant2), &dst) - assert.NoError(t, err) - v2, err := dst.AsOneOfVariant2() - assert.NoError(t, err) - assert.Equal(t, []int{1, 2, 3}, v2) - - err = json.Unmarshal([]byte(variant3), &dst) - assert.NoError(t, err) - v3, err := dst.AsOneOfVariant3() - assert.NoError(t, err) - assert.Equal(t, OneOfVariant3(true), v3) - - err = dst.FromOneOfVariant1(OneOfVariant1{Name: "123"}) - assert.NoError(t, err) - marshaled, err := json.Marshal(dst) - assert.NoError(t, err) - assertJsonEqual(t, []byte(variant1), marshaled) - - err = dst.FromOneOfVariant2([]int{1, 2, 3}) - assert.NoError(t, err) - marshaled, err = json.Marshal(dst) - assert.NoError(t, err) - assertJsonEqual(t, []byte(variant2), marshaled) - - err = dst.FromOneOfVariant3(true) - assert.NoError(t, err) - marshaled, err = json.Marshal(dst) - assert.NoError(t, err) - assertJsonEqual(t, []byte(variant3), marshaled) -} - -func TestOneOfWithDiscriminator(t *testing.T) { - const variant4 = `{"discriminator": "v4", "name": "123"}` - const variant5 = `{"discriminator": "v5", "id": 123}` - var dst OneOfObject6 - - err := json.Unmarshal([]byte(variant4), &dst) - assert.NoError(t, err) - discriminator, err := dst.Discriminator() - assert.NoError(t, err) - assert.Equal(t, "v4", discriminator) - v4, err := dst.ValueByDiscriminator() - assert.NoError(t, err) - assert.Equal(t, OneOfVariant4{Discriminator: "v4", Name: "123"}, v4) - - err = json.Unmarshal([]byte(variant5), &dst) - assert.NoError(t, err) - discriminator, err = dst.Discriminator() - assert.NoError(t, err) - assert.Equal(t, "v5", discriminator) - v5, err := dst.ValueByDiscriminator() - assert.NoError(t, err) - assert.Equal(t, OneOfVariant5{Discriminator: "v5", Id: 123}, v5) - - // discriminator value will be filled by the generated code - err = dst.FromOneOfVariant4(OneOfVariant4{Name: "123"}) - assert.NoError(t, err) - marshaled, err := json.Marshal(dst) - assert.NoError(t, err) - assertJsonEqual(t, []byte(variant4), marshaled) - - err = dst.FromOneOfVariant5(OneOfVariant5{Id: 123}) - assert.NoError(t, err) - marshaled, err = json.Marshal(dst) - assert.NoError(t, err) - assertJsonEqual(t, []byte(variant5), marshaled) -} - -func TestOneOfWithDiscriminator_PartialMapping(t *testing.T) { - const variant4 = `{"discriminator": "v4", "name": "123"}` - const variant5 = `{"discriminator": "OneOfVariant5", "id": 321}` - var dst OneOfObject61 - - err := json.Unmarshal([]byte(variant4), &dst) - assert.NoError(t, err) - discriminator, err := dst.Discriminator() - require.NoError(t, err) - assert.Equal(t, "v4", discriminator) - v4, err := dst.ValueByDiscriminator() - require.NoError(t, err) - assert.Equal(t, OneOfVariant4{Discriminator: "v4", Name: "123"}, v4) - - err = json.Unmarshal([]byte(variant5), &dst) - require.NoError(t, err) - discriminator, err = dst.Discriminator() - require.NoError(t, err) - assert.Equal(t, "OneOfVariant5", discriminator) - v5, err := dst.ValueByDiscriminator() - require.NoError(t, err) - assert.Equal(t, OneOfVariant5{Discriminator: "OneOfVariant5", Id: 321}, v5) - - // discriminator value will be filled by the generated code - err = dst.FromOneOfVariant4(OneOfVariant4{Name: "123"}) - require.NoError(t, err) - marshaled, err := json.Marshal(dst) - require.NoError(t, err) - assertJsonEqual(t, []byte(variant4), marshaled) - - err = dst.FromOneOfVariant5(OneOfVariant5{Id: 321}) - require.NoError(t, err) - marshaled, err = json.Marshal(dst) - require.NoError(t, err) - assertJsonEqual(t, []byte(variant5), marshaled) -} - -func TestOneOfWithDiscriminator_SchemaNameUsed(t *testing.T) { - const variant4 = `{"discriminator": "variant_four", "name": "789"}` - const variant51 = `{"discriminator": "one_of_variant51", "id": 987}` - var dst OneOfObject62 - - err := json.Unmarshal([]byte(variant4), &dst) - assert.NoError(t, err) - discriminator, err := dst.Discriminator() - require.NoError(t, err) - assert.Equal(t, "variant_four", discriminator) - v4, err := dst.ValueByDiscriminator() - require.NoError(t, err) - assert.Equal(t, OneOfVariant4{Discriminator: "variant_four", Name: "789"}, v4) - - err = json.Unmarshal([]byte(variant51), &dst) - require.NoError(t, err) - discriminator, err = dst.Discriminator() - require.NoError(t, err) - assert.Equal(t, "one_of_variant51", discriminator) - v5, err := dst.ValueByDiscriminator() - require.NoError(t, err) - assert.Equal(t, OneOfVariant51{Discriminator: "one_of_variant51", Id: 987}, v5) - - // discriminator value will be filled by the generated code - err = dst.FromOneOfVariant4(OneOfVariant4{Name: "789"}) - require.NoError(t, err) - marshaled, err := json.Marshal(dst) - require.NoError(t, err) - assertJsonEqual(t, []byte(variant4), marshaled) - - err = dst.FromOneOfVariant51(OneOfVariant51{Id: 987}) - require.NoError(t, err) - marshaled, err = json.Marshal(dst) - require.NoError(t, err) - assertJsonEqual(t, []byte(variant51), marshaled) -} - -func TestOneOfWithDiscriminator_FullImplicitMapping(t *testing.T) { - const variant4 = `{"discriminator": "OneOfVariant4", "name": "456"}` - const variant5 = `{"discriminator": "OneOfVariant5", "id": 654}` - var dst OneOfObject5 - - err := json.Unmarshal([]byte(variant4), &dst) - assert.NoError(t, err) - discriminator, err := dst.Discriminator() - require.NoError(t, err) - assert.Equal(t, "OneOfVariant4", discriminator) - v4, err := dst.ValueByDiscriminator() - require.NoError(t, err) - assert.Equal(t, OneOfVariant4{Discriminator: "OneOfVariant4", Name: "456"}, v4) - - err = json.Unmarshal([]byte(variant5), &dst) - require.NoError(t, err) - discriminator, err = dst.Discriminator() - require.NoError(t, err) - assert.Equal(t, "OneOfVariant5", discriminator) - v5, err := dst.ValueByDiscriminator() - require.NoError(t, err) - assert.Equal(t, OneOfVariant5{Discriminator: "OneOfVariant5", Id: 654}, v5) - - // discriminator value will be filled by the generated code - err = dst.FromOneOfVariant4(OneOfVariant4{Name: "456"}) - require.NoError(t, err) - marshaled, err := json.Marshal(dst) - require.NoError(t, err) - assertJsonEqual(t, []byte(variant4), marshaled) - - err = dst.FromOneOfVariant5(OneOfVariant5{Id: 654}) - require.NoError(t, err) - marshaled, err = json.Marshal(dst) - require.NoError(t, err) - assertJsonEqual(t, []byte(variant5), marshaled) -} - -func TestOneOfWithFixedProperties(t *testing.T) { - const variant1 = "{\"type\": \"v1\", \"name\": \"123\"}" - const variant6 = "{\"type\": \"v6\", \"values\": [1, 2, 3]}" - var dst OneOfObject9 - - err := json.Unmarshal([]byte(variant1), &dst) - assert.NoError(t, err) - discriminator, err := dst.Discriminator() - assert.NoError(t, err) - assert.Equal(t, "v1", discriminator) - v1, err := dst.ValueByDiscriminator() - assert.NoError(t, err) - assert.Equal(t, OneOfVariant1{Name: "123"}, v1) - - err = json.Unmarshal([]byte(variant6), &dst) - assert.NoError(t, err) - discriminator, err = dst.Discriminator() - assert.NoError(t, err) - assert.Equal(t, "v6", discriminator) - v2, err := dst.AsOneOfVariant6() - assert.NoError(t, err) - assert.Equal(t, OneOfVariant6{[]int{1, 2, 3}}, v2) - - err = dst.FromOneOfVariant1(OneOfVariant1{Name: "123"}) - assert.NoError(t, err) - marshaled, err := json.Marshal(dst) - assert.NoError(t, err) - assertJsonEqual(t, []byte(variant1), marshaled) - - err = dst.FromOneOfVariant6(OneOfVariant6{[]int{1, 2, 3}}) - assert.NoError(t, err) - marshaled, err = json.Marshal(dst) - assert.NoError(t, err) - assertJsonEqual(t, []byte(variant6), marshaled) -} - -func TestAnyOf(t *testing.T) { - const anyOfStr = `{"discriminator": "all", "name": "123", "id": 456}` - - var dst AnyOfObject1 - err := json.Unmarshal([]byte(anyOfStr), &dst) - assert.NoError(t, err) - - v4, err := dst.AsOneOfVariant4() - assert.NoError(t, err) - assert.Equal(t, OneOfVariant4{Discriminator: "all", Name: "123"}, v4) - - v5, err := dst.AsOneOfVariant5() - assert.NoError(t, err) - assert.Equal(t, OneOfVariant5{Discriminator: "all", Id: 456}, v5) -} - -func TestOneOfWithAdditional(t *testing.T) { - x := OneOfObject13{ - AdditionalProperties: map[string]interface{}{"x": "y"}, - } - err := x.MergeOneOfVariant1(OneOfVariant1{Name: "test-name"}) - require.NoError(t, err) - b, err := json.Marshal(x) - require.NoError(t, err) - assert.JSONEq(t, `{"x":"y", "name":"test-name", "type":"v1"}`, string(b)) - var y OneOfObject13 - err = json.Unmarshal(b, &y) - require.NoError(t, err) - assert.Equal(t, x.Type, y.Type) - xVariant, err := x.AsOneOfVariant1() - require.NoError(t, err) - yVariant, err := y.AsOneOfVariant1() - require.NoError(t, err) - assert.Equal(t, xVariant, yVariant) - xAdditional, ok := x.Get("x") - assert.True(t, ok) - yAdditional, ok := y.Get("x") - assert.True(t, ok) - assert.Equal(t, xAdditional, yAdditional) - b, err = json.Marshal(y) - require.NoError(t, err) - assert.JSONEq(t, `{"x":"y", "name":"test-name", "type":"v1"}`, string(b)) -} - -func TestMarshalWhenNoUnionValueSet(t *testing.T) { - const expected = `{}` - - var dst OneOfObject10 - - bytes, err := dst.MarshalJSON() - assert.Nil(t, err) - assert.Equal(t, expected, string(bytes)) -} diff --git a/internal/test/components/doc.go b/internal/test/components/doc.go deleted file mode 100644 index 64f995a9c0..0000000000 --- a/internal/test/components/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -package components - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml components.yaml diff --git a/internal/test/issues/issue-1039/types-config.yaml b/internal/test/components/nullable/config.yaml similarity index 76% rename from internal/test/issues/issue-1039/types-config.yaml rename to internal/test/components/nullable/config.yaml index 9f97d8bc62..c73df7dd58 100644 --- a/internal/test/issues/issue-1039/types-config.yaml +++ b/internal/test/components/nullable/config.yaml @@ -1,7 +1,7 @@ # yaml-language-server: $schema=../../../../configuration-schema.json -package: issue1039 +package: nullable generate: models: true output-options: nullable-type: true -output: types.gen.go +output: nullable.gen.go diff --git a/internal/test/externalref/packageA/doc.go b/internal/test/components/nullable/doc.go similarity index 86% rename from internal/test/externalref/packageA/doc.go rename to internal/test/components/nullable/doc.go index f05471ffbb..0e58944cb7 100644 --- a/internal/test/externalref/packageA/doc.go +++ b/internal/test/components/nullable/doc.go @@ -1,3 +1,3 @@ -package packagea +package nullable //go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml spec.yaml diff --git a/internal/test/issues/issue-1039/types.gen.go b/internal/test/components/nullable/nullable.gen.go similarity index 87% rename from internal/test/issues/issue-1039/types.gen.go rename to internal/test/components/nullable/nullable.gen.go index 9c11915344..ccfba19c6f 100644 --- a/internal/test/issues/issue-1039/types.gen.go +++ b/internal/test/components/nullable/nullable.gen.go @@ -1,13 +1,33 @@ -// Package issue1039 provides primitives to interact with the openapi HTTP API. +// Package nullable provides primitives to interact with the openapi HTTP API. // // Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package issue1039 +package nullable import ( "github.com/oapi-codegen/nullable" ) -// PatchRequest A request to patch an existing user object. +// ComplexOptionalNullable Complex, optional and nullable +type ComplexOptionalNullable struct { + // AliasName Optional and nullable + AliasName nullable.Nullable[string] `json:"alias_name,omitempty"` + + // Name Optional and non nullable + Name *string `json:"name,omitempty"` +} + +// ComplexRequiredNullable Complex required and nullable +type ComplexRequiredNullable struct { + // Name Optional and non nullable + Name *string `json:"name,omitempty"` +} + +// Container defines model for Container. +type Container struct { + MayBeNull []nullable.Nullable[string] `json:"may-be-null"` +} + +// PatchRequest A request to patch an existing object. type PatchRequest struct { // ComplexOptionalNullable Complex, optional and nullable ComplexOptionalNullable nullable.Nullable[ComplexOptionalNullable] `json:"complex_optional_nullable,omitempty"` @@ -25,21 +45,6 @@ type PatchRequest struct { SimpleRequiredNullable nullable.Nullable[SimpleRequiredNullable] `json:"simple_required_nullable"` } -// ComplexOptionalNullable Complex, optional and nullable -type ComplexOptionalNullable struct { - // AliasName Optional and nullable - AliasName nullable.Nullable[string] `json:"alias_name,omitempty"` - - // Name Optional and non nullable - Name *string `json:"name,omitempty"` -} - -// ComplexRequiredNullable Complex required and nullable -type ComplexRequiredNullable struct { - // Name Optional and non nullable - Name *string `json:"name,omitempty"` -} - // SimpleOptionalNonNullable Simple optional and non nullable type SimpleOptionalNonNullable = string diff --git a/internal/test/components/nullable/nullable_test.go b/internal/test/components/nullable/nullable_test.go new file mode 100644 index 0000000000..a8ec35cf51 --- /dev/null +++ b/internal/test/components/nullable/nullable_test.go @@ -0,0 +1,206 @@ +package nullable + +import ( + "encoding/json" + "testing" + + nullablepkg "github.com/oapi-codegen/nullable" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func ptr[T any](v T) *T { + return &v +} + +// From issue-1039: marshal with all fields present. +func TestNullableTypesMarshal(t *testing.T) { + patchReq := PatchRequest{ + ComplexRequiredNullable: nullablepkg.NewNullableWithValue(ComplexRequiredNullable{ + Name: ptr("test-name"), + }), + SimpleOptionalNonNullable: ptr(SimpleOptionalNonNullable("bar")), + ComplexOptionalNullable: nullablepkg.NewNullableWithValue(ComplexOptionalNullable{ + AliasName: nullablepkg.NewNullableWithValue("foo-alias"), + Name: ptr("foo"), + }), + SimpleOptionalNullable: nullablepkg.NewNullableWithValue(SimpleOptionalNullable(10)), + SimpleRequiredNullable: nullablepkg.NewNullableWithValue(SimpleRequiredNullable(5)), + } + + expected := `{"complex_optional_nullable":{"alias_name":"foo-alias","name":"foo"},"complex_required_nullable":{"name":"test-name"},"simple_optional_non_nullable":"bar","simple_optional_nullable":10,"simple_required_nullable":5}` + + actual, err := json.Marshal(patchReq) + require.NoError(t, err) + require.Equal(t, expected, string(actual)) +} + +// From issue-1039: marshal with some fields omitted. +func TestNullableTypesMarshalPartial(t *testing.T) { + patchReq := PatchRequest{ + ComplexRequiredNullable: nullablepkg.NewNullableWithValue(ComplexRequiredNullable{ + Name: ptr("test-name"), + }), + ComplexOptionalNullable: nullablepkg.NewNullableWithValue(ComplexOptionalNullable{ + AliasName: nullablepkg.NewNullableWithValue("test-alias-name"), + Name: ptr("test-name"), + }), + SimpleOptionalNullable: nullablepkg.NewNullableWithValue(SimpleOptionalNullable(10)), + } + + expected := `{"complex_optional_nullable":{"alias_name":"test-alias-name","name":"test-name"},"complex_required_nullable":{"name":"test-name"},"simple_optional_nullable":10,"simple_required_nullable":0}` + + actual, err := json.Marshal(patchReq) + require.NoError(t, err) + require.Equal(t, expected, string(actual)) +} + +// From issue-1039: unmarshal empty JSON. +func TestNullableTypesUnmarshalEmpty(t *testing.T) { + var obj PatchRequest + err := json.Unmarshal([]byte(`{}`), &obj) + require.NoError(t, err) + + assert.False(t, obj.SimpleRequiredNullable.IsSpecified()) + assert.False(t, obj.SimpleRequiredNullable.IsNull()) + assert.False(t, obj.SimpleOptionalNullable.IsSpecified()) + assert.False(t, obj.SimpleOptionalNullable.IsNull()) + assert.False(t, obj.ComplexOptionalNullable.IsSpecified()) + assert.False(t, obj.ComplexOptionalNullable.IsNull()) + assert.False(t, obj.ComplexRequiredNullable.IsSpecified()) + assert.False(t, obj.ComplexRequiredNullable.IsNull()) + assert.Nil(t, obj.SimpleOptionalNonNullable) +} + +// From issue-1039: unmarshal with empty complex_optional_nullable. +func TestNullableTypesUnmarshalEmptyComplex(t *testing.T) { + var obj PatchRequest + err := json.Unmarshal([]byte(`{"complex_optional_nullable":{}}`), &obj) + require.NoError(t, err) + + assert.True(t, obj.ComplexOptionalNullable.IsSpecified()) + assert.False(t, obj.ComplexOptionalNullable.IsNull()) + + assert.False(t, obj.SimpleRequiredNullable.IsSpecified()) + assert.False(t, obj.SimpleOptionalNullable.IsSpecified()) + assert.False(t, obj.ComplexRequiredNullable.IsSpecified()) + assert.Nil(t, obj.SimpleOptionalNonNullable) +} + +// From issue-1039: unmarshal with nested nullable child fields. +func TestNullableTypesUnmarshalNestedFields(t *testing.T) { + var obj PatchRequest + err := json.Unmarshal([]byte(`{"complex_optional_nullable":{"name":"test-name"}}`), &obj) + require.NoError(t, err) + + assert.True(t, obj.ComplexOptionalNullable.IsSpecified()) + assert.False(t, obj.ComplexOptionalNullable.IsNull()) + + gotComplexObj, err := obj.ComplexOptionalNullable.Get() + require.NoError(t, err) + assert.Equal(t, "test-name", *gotComplexObj.Name) + assert.False(t, gotComplexObj.AliasName.IsSpecified()) + assert.False(t, gotComplexObj.AliasName.IsNull()) +} + +// From issue-1039: unmarshal with explicit null child field. +func TestNullableTypesUnmarshalNullChild(t *testing.T) { + var obj PatchRequest + err := json.Unmarshal([]byte(`{"complex_optional_nullable":{"name":"test-name","alias_name":null}}`), &obj) + require.NoError(t, err) + + gotComplexObj, err := obj.ComplexOptionalNullable.Get() + require.NoError(t, err) + assert.Equal(t, "test-name", *gotComplexObj.Name) + assert.True(t, gotComplexObj.AliasName.IsSpecified()) + assert.True(t, gotComplexObj.AliasName.IsNull()) +} + +// From issue-1039: unmarshal with explicit null on required field. +func TestNullableTypesUnmarshalNullRequired(t *testing.T) { + var obj PatchRequest + err := json.Unmarshal([]byte(`{"simple_required_nullable":null}`), &obj) + require.NoError(t, err) + + assert.True(t, obj.SimpleRequiredNullable.IsSpecified()) + assert.True(t, obj.SimpleRequiredNullable.IsNull()) +} + +// From issue-1039: unmarshal with null required and non-null complex. +func TestNullableTypesUnmarshalMixed(t *testing.T) { + var obj PatchRequest + err := json.Unmarshal([]byte(`{"complex_optional_nullable":{"name":"foo","alias_name":"bar"},"simple_required_nullable":null}`), &obj) + require.NoError(t, err) + + assert.True(t, obj.SimpleRequiredNullable.IsSpecified()) + assert.True(t, obj.SimpleRequiredNullable.IsNull()) + + assert.True(t, obj.ComplexOptionalNullable.IsSpecified()) + assert.False(t, obj.ComplexOptionalNullable.IsNull()) + + gotComplexObj, err := obj.ComplexOptionalNullable.Get() + require.NoError(t, err) + assert.Equal(t, "foo", *gotComplexObj.Name) + assert.True(t, gotComplexObj.AliasName.IsSpecified()) + assert.False(t, gotComplexObj.AliasName.IsNull()) + + gotAliasName, err := gotComplexObj.AliasName.Get() + require.NoError(t, err) + assert.Equal(t, "bar", gotAliasName) +} + +// From issue-2185: array of nullable items. +func TestContainerWithNullableArrayItems(t *testing.T) { + c := Container{ + MayBeNull: []nullablepkg.Nullable[string]{ + nullablepkg.NewNullNullable[string](), + }, + } + + require.Len(t, c.MayBeNull, 1) + require.True(t, c.MayBeNull[0].IsNull()) +} + +func TestContainerWithMixedNullableItems(t *testing.T) { + c := Container{ + MayBeNull: []nullablepkg.Nullable[string]{ + nullablepkg.NewNullableWithValue("hello"), + nullablepkg.NewNullNullable[string](), + nullablepkg.NewNullableWithValue("world"), + }, + } + + require.Len(t, c.MayBeNull, 3) + + val, err := c.MayBeNull[0].Get() + require.NoError(t, err) + assert.Equal(t, "hello", val) + + assert.True(t, c.MayBeNull[1].IsNull()) + + val, err = c.MayBeNull[2].Get() + require.NoError(t, err) + assert.Equal(t, "world", val) +} + +func TestContainerNullableJSONRoundTrip(t *testing.T) { + c := Container{ + MayBeNull: []nullablepkg.Nullable[string]{ + nullablepkg.NewNullableWithValue("hello"), + nullablepkg.NewNullNullable[string](), + }, + } + + data, err := json.Marshal(c) + require.NoError(t, err) + + var roundTripped Container + err = json.Unmarshal(data, &roundTripped) + require.NoError(t, err) + + require.Len(t, roundTripped.MayBeNull, 2) + val, err := roundTripped.MayBeNull[0].Get() + require.NoError(t, err) + assert.Equal(t, "hello", val) + assert.True(t, roundTripped.MayBeNull[1].IsNull()) +} diff --git a/internal/test/issues/issue-1039/spec.yaml b/internal/test/components/nullable/spec.yaml similarity index 53% rename from internal/test/issues/issue-1039/spec.yaml rename to internal/test/components/nullable/spec.yaml index 821b71066e..ee290128b9 100644 --- a/internal/test/issues/issue-1039/spec.yaml +++ b/internal/test/components/nullable/spec.yaml @@ -1,67 +1,68 @@ -openapi: 3.0.1 +openapi: "3.0.1" info: - version: '0.0.1' - title: example - description: | - Make sure that nullable types are generated properly + version: 1.0.0 + title: Nullable Types + description: Tests nullable types and nullable array items paths: /example: patch: operationId: examplePatch requestBody: - description: The patch body required: true content: application/json: - example: - name: Example Patch schema: $ref: "#/components/schemas/PatchRequest" responses: - '200': - description: "OK" - + "200": + description: OK + /container: + get: + operationId: getContainer + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: "#/components/schemas/Container" components: schemas: + # From issue-1039: comprehensive nullable type combinations PatchRequest: type: object - description: A request to patch an existing user object. + description: A request to patch an existing object. required: - simple_required_nullable - complex_required_nullable properties: simple_required_nullable: - # required and nullable - $ref: "#/components/schemas/simple_required_nullable" + $ref: "#/components/schemas/SimpleRequiredNullable" simple_optional_nullable: - # optional and nullable - $ref: "#/components/schemas/simple_optional_nullable" + $ref: "#/components/schemas/SimpleOptionalNullable" simple_optional_non_nullable: - # optional and non-nullable - $ref: "#/components/schemas/simple_optional_non_nullable" + $ref: "#/components/schemas/SimpleOptionalNonNullable" complex_required_nullable: - # required and nullable - $ref: "#/components/schemas/complex_required_nullable" + $ref: "#/components/schemas/ComplexRequiredNullable" complex_optional_nullable: - # optional and nullable - $ref: "#/components/schemas/complex_optional_nullable" + $ref: "#/components/schemas/ComplexOptionalNullable" additionalProperties: false - simple_required_nullable: + SimpleRequiredNullable: type: integer nullable: true description: Simple required and nullable - simple_optional_nullable: + SimpleOptionalNullable: type: integer nullable: true description: Simple optional and nullable - simple_optional_non_nullable: + SimpleOptionalNonNullable: type: string description: Simple optional and non nullable - complex_required_nullable: + ComplexRequiredNullable: type: object nullable: true description: Complex required and nullable @@ -70,7 +71,7 @@ components: description: Optional and non nullable type: string - complex_optional_nullable: + ComplexOptionalNullable: type: object description: Complex, optional and nullable properties: @@ -82,3 +83,14 @@ components: description: Optional and non nullable type: string nullable: true + + # From issue-2185: array of nullable items + Container: + required: + - may-be-null + properties: + may-be-null: + type: array + items: + type: string + nullable: true diff --git a/internal/test/issues/issue-1127/server.config.yaml b/internal/test/components/objects/config.yaml similarity index 70% rename from internal/test/issues/issue-1127/server.config.yaml rename to internal/test/components/objects/config.yaml index fd6b9de19d..0c20fc6932 100644 --- a/internal/test/issues/issue-1127/server.config.yaml +++ b/internal/test/components/objects/config.yaml @@ -1,6 +1,5 @@ # yaml-language-server: $schema=../../../../configuration-schema.json -package: issue1127 -output: - api.gen.go +package: objects generate: models: true +output: objects.gen.go diff --git a/internal/test/issues/issue-52/doc.go b/internal/test/components/objects/doc.go similarity index 87% rename from internal/test/issues/issue-52/doc.go rename to internal/test/components/objects/doc.go index 3d239ebdcf..1c16d8e5d5 100644 --- a/internal/test/issues/issue-52/doc.go +++ b/internal/test/components/objects/doc.go @@ -1,3 +1,3 @@ -package issue52 +package objects //go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml spec.yaml diff --git a/internal/test/components/objects/objects.gen.go b/internal/test/components/objects/objects.gen.go new file mode 100644 index 0000000000..79862b3066 --- /dev/null +++ b/internal/test/components/objects/objects.gen.go @@ -0,0 +1,368 @@ +// Package objects provides primitives to interact with the openapi HTTP API. +// +// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. +package objects + +import ( + "encoding/json" + "fmt" +) + +// AnyAdditionalProperties Allows any additional property +type AnyAdditionalProperties struct { + Name string `json:"name"` + AdditionalProperties map[string]interface{} `json:"-"` +} + +// ArrayOfMaps Array of objects with additional properties +type ArrayOfMaps = []map[string]BaseObject + +// BaseObject defines model for BaseObject. +type BaseObject struct { + FirstName string `json:"firstName"` + Role string `json:"role"` +} + +// NestedAdditionalProperties Has anonymous field which has additional properties +type NestedAdditionalProperties struct { + Inner NestedAdditionalProperties_Inner `json:"inner"` + Name string `json:"name"` + AdditionalProperties map[string]interface{} `json:"-"` +} + +// NestedAdditionalProperties_Inner defines model for NestedAdditionalProperties.Inner. +type NestedAdditionalProperties_Inner struct { + Name string `json:"name"` + AdditionalProperties map[string]interface{} `json:"-"` +} + +// NoAdditionalProperties Does not allow additional properties +type NoAdditionalProperties struct { + Id int `json:"id"` + Name string `json:"name"` +} + +// ReadOnlyWriteOnly defines model for ReadOnlyWriteOnly. +type ReadOnlyWriteOnly struct { + NormalProp string `json:"normalProp"` + + // ReadOnlyProp This property is required and readOnly + ReadOnlyProp *string `json:"readOnlyProp,omitempty"` + WriteOnlyProp *int `json:"writeOnlyProp,omitempty"` +} + +// RefAdditionalProperties Has additional properties with schema reference for dictionaries +type RefAdditionalProperties map[string]BaseObject + +// TypedAdditionalProperties Has additional properties of type int +type TypedAdditionalProperties struct { + Id int `json:"id"` + Name string `json:"name"` + Optional *string `json:"optional,omitempty"` + AdditionalProperties map[string]int `json:"-"` +} + +// Getter for additional properties for AnyAdditionalProperties. Returns the specified +// element and whether it was found +func (a AnyAdditionalProperties) Get(fieldName string) (value interface{}, found bool) { + if a.AdditionalProperties != nil { + value, found = a.AdditionalProperties[fieldName] + } + return +} + +// Setter for additional properties for AnyAdditionalProperties +func (a *AnyAdditionalProperties) Set(fieldName string, value interface{}) { + if a.AdditionalProperties == nil { + a.AdditionalProperties = make(map[string]interface{}) + } + a.AdditionalProperties[fieldName] = value +} + +// Override default JSON handling for AnyAdditionalProperties to handle AdditionalProperties +func (a *AnyAdditionalProperties) UnmarshalJSON(b []byte) error { + object := make(map[string]json.RawMessage) + err := json.Unmarshal(b, &object) + if err != nil { + return err + } + + if raw, found := object["name"]; found { + err = json.Unmarshal(raw, &a.Name) + if err != nil { + return fmt.Errorf("error reading 'name': %w", err) + } + delete(object, "name") + } + + if len(object) != 0 { + a.AdditionalProperties = make(map[string]interface{}) + for fieldName, fieldBuf := range object { + var fieldVal interface{} + err := json.Unmarshal(fieldBuf, &fieldVal) + if err != nil { + return fmt.Errorf("error unmarshaling field %s: %w", fieldName, err) + } + a.AdditionalProperties[fieldName] = fieldVal + } + } + return nil +} + +// Override default JSON handling for AnyAdditionalProperties to handle AdditionalProperties +func (a AnyAdditionalProperties) MarshalJSON() ([]byte, error) { + var err error + object := make(map[string]json.RawMessage) + + object["name"], err = json.Marshal(a.Name) + if err != nil { + return nil, fmt.Errorf("error marshaling 'name': %w", err) + } + + for fieldName, field := range a.AdditionalProperties { + object[fieldName], err = json.Marshal(field) + if err != nil { + return nil, fmt.Errorf("error marshaling '%s': %w", fieldName, err) + } + } + return json.Marshal(object) +} + +// Getter for additional properties for NestedAdditionalProperties. Returns the specified +// element and whether it was found +func (a NestedAdditionalProperties) Get(fieldName string) (value interface{}, found bool) { + if a.AdditionalProperties != nil { + value, found = a.AdditionalProperties[fieldName] + } + return +} + +// Setter for additional properties for NestedAdditionalProperties +func (a *NestedAdditionalProperties) Set(fieldName string, value interface{}) { + if a.AdditionalProperties == nil { + a.AdditionalProperties = make(map[string]interface{}) + } + a.AdditionalProperties[fieldName] = value +} + +// Override default JSON handling for NestedAdditionalProperties to handle AdditionalProperties +func (a *NestedAdditionalProperties) UnmarshalJSON(b []byte) error { + object := make(map[string]json.RawMessage) + err := json.Unmarshal(b, &object) + if err != nil { + return err + } + + if raw, found := object["inner"]; found { + err = json.Unmarshal(raw, &a.Inner) + if err != nil { + return fmt.Errorf("error reading 'inner': %w", err) + } + delete(object, "inner") + } + + if raw, found := object["name"]; found { + err = json.Unmarshal(raw, &a.Name) + if err != nil { + return fmt.Errorf("error reading 'name': %w", err) + } + delete(object, "name") + } + + if len(object) != 0 { + a.AdditionalProperties = make(map[string]interface{}) + for fieldName, fieldBuf := range object { + var fieldVal interface{} + err := json.Unmarshal(fieldBuf, &fieldVal) + if err != nil { + return fmt.Errorf("error unmarshaling field %s: %w", fieldName, err) + } + a.AdditionalProperties[fieldName] = fieldVal + } + } + return nil +} + +// Override default JSON handling for NestedAdditionalProperties to handle AdditionalProperties +func (a NestedAdditionalProperties) MarshalJSON() ([]byte, error) { + var err error + object := make(map[string]json.RawMessage) + + object["inner"], err = json.Marshal(a.Inner) + if err != nil { + return nil, fmt.Errorf("error marshaling 'inner': %w", err) + } + + object["name"], err = json.Marshal(a.Name) + if err != nil { + return nil, fmt.Errorf("error marshaling 'name': %w", err) + } + + for fieldName, field := range a.AdditionalProperties { + object[fieldName], err = json.Marshal(field) + if err != nil { + return nil, fmt.Errorf("error marshaling '%s': %w", fieldName, err) + } + } + return json.Marshal(object) +} + +// Getter for additional properties for NestedAdditionalProperties_Inner. Returns the specified +// element and whether it was found +func (a NestedAdditionalProperties_Inner) Get(fieldName string) (value interface{}, found bool) { + if a.AdditionalProperties != nil { + value, found = a.AdditionalProperties[fieldName] + } + return +} + +// Setter for additional properties for NestedAdditionalProperties_Inner +func (a *NestedAdditionalProperties_Inner) Set(fieldName string, value interface{}) { + if a.AdditionalProperties == nil { + a.AdditionalProperties = make(map[string]interface{}) + } + a.AdditionalProperties[fieldName] = value +} + +// Override default JSON handling for NestedAdditionalProperties_Inner to handle AdditionalProperties +func (a *NestedAdditionalProperties_Inner) UnmarshalJSON(b []byte) error { + object := make(map[string]json.RawMessage) + err := json.Unmarshal(b, &object) + if err != nil { + return err + } + + if raw, found := object["name"]; found { + err = json.Unmarshal(raw, &a.Name) + if err != nil { + return fmt.Errorf("error reading 'name': %w", err) + } + delete(object, "name") + } + + if len(object) != 0 { + a.AdditionalProperties = make(map[string]interface{}) + for fieldName, fieldBuf := range object { + var fieldVal interface{} + err := json.Unmarshal(fieldBuf, &fieldVal) + if err != nil { + return fmt.Errorf("error unmarshaling field %s: %w", fieldName, err) + } + a.AdditionalProperties[fieldName] = fieldVal + } + } + return nil +} + +// Override default JSON handling for NestedAdditionalProperties_Inner to handle AdditionalProperties +func (a NestedAdditionalProperties_Inner) MarshalJSON() ([]byte, error) { + var err error + object := make(map[string]json.RawMessage) + + object["name"], err = json.Marshal(a.Name) + if err != nil { + return nil, fmt.Errorf("error marshaling 'name': %w", err) + } + + for fieldName, field := range a.AdditionalProperties { + object[fieldName], err = json.Marshal(field) + if err != nil { + return nil, fmt.Errorf("error marshaling '%s': %w", fieldName, err) + } + } + return json.Marshal(object) +} + +// Getter for additional properties for TypedAdditionalProperties. Returns the specified +// element and whether it was found +func (a TypedAdditionalProperties) Get(fieldName string) (value int, found bool) { + if a.AdditionalProperties != nil { + value, found = a.AdditionalProperties[fieldName] + } + return +} + +// Setter for additional properties for TypedAdditionalProperties +func (a *TypedAdditionalProperties) Set(fieldName string, value int) { + if a.AdditionalProperties == nil { + a.AdditionalProperties = make(map[string]int) + } + a.AdditionalProperties[fieldName] = value +} + +// Override default JSON handling for TypedAdditionalProperties to handle AdditionalProperties +func (a *TypedAdditionalProperties) UnmarshalJSON(b []byte) error { + object := make(map[string]json.RawMessage) + err := json.Unmarshal(b, &object) + if err != nil { + return err + } + + if raw, found := object["id"]; found { + err = json.Unmarshal(raw, &a.Id) + if err != nil { + return fmt.Errorf("error reading 'id': %w", err) + } + delete(object, "id") + } + + if raw, found := object["name"]; found { + err = json.Unmarshal(raw, &a.Name) + if err != nil { + return fmt.Errorf("error reading 'name': %w", err) + } + delete(object, "name") + } + + if raw, found := object["optional"]; found { + err = json.Unmarshal(raw, &a.Optional) + if err != nil { + return fmt.Errorf("error reading 'optional': %w", err) + } + delete(object, "optional") + } + + if len(object) != 0 { + a.AdditionalProperties = make(map[string]int) + for fieldName, fieldBuf := range object { + var fieldVal int + err := json.Unmarshal(fieldBuf, &fieldVal) + if err != nil { + return fmt.Errorf("error unmarshaling field %s: %w", fieldName, err) + } + a.AdditionalProperties[fieldName] = fieldVal + } + } + return nil +} + +// Override default JSON handling for TypedAdditionalProperties to handle AdditionalProperties +func (a TypedAdditionalProperties) MarshalJSON() ([]byte, error) { + var err error + object := make(map[string]json.RawMessage) + + object["id"], err = json.Marshal(a.Id) + if err != nil { + return nil, fmt.Errorf("error marshaling 'id': %w", err) + } + + object["name"], err = json.Marshal(a.Name) + if err != nil { + return nil, fmt.Errorf("error marshaling 'name': %w", err) + } + + if a.Optional != nil { + object["optional"], err = json.Marshal(a.Optional) + if err != nil { + return nil, fmt.Errorf("error marshaling 'optional': %w", err) + } + } + + for fieldName, field := range a.AdditionalProperties { + object[fieldName], err = json.Marshal(field) + if err != nil { + return nil, fmt.Errorf("error marshaling '%s': %w", fieldName, err) + } + } + return json.Marshal(object) +} diff --git a/internal/test/components/objects/objects_test.go b/internal/test/components/objects/objects_test.go new file mode 100644 index 0000000000..52d03cb4cc --- /dev/null +++ b/internal/test/components/objects/objects_test.go @@ -0,0 +1,176 @@ +package objects + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestBaseObjectRoundTrip(t *testing.T) { + obj := BaseObject{Role: "admin", FirstName: "Alex"} + data, err := json.Marshal(obj) + require.NoError(t, err) + + var roundTripped BaseObject + err = json.Unmarshal(data, &roundTripped) + require.NoError(t, err) + assert.Equal(t, obj, roundTripped) +} + +func TestTypedAdditionalProperties(t *testing.T) { + input := `{"name":"test","id":1,"extra1":10,"extra2":20}` + + var obj TypedAdditionalProperties + err := json.Unmarshal([]byte(input), &obj) + require.NoError(t, err) + + assert.Equal(t, "test", obj.Name) + assert.Equal(t, 1, obj.Id) + + val, found := obj.Get("extra1") + assert.True(t, found) + assert.Equal(t, 10, val) + + val, found = obj.Get("extra2") + assert.True(t, found) + assert.Equal(t, 20, val) + + // Round-trip + data, err := json.Marshal(obj) + require.NoError(t, err) + + var roundTripped TypedAdditionalProperties + err = json.Unmarshal(data, &roundTripped) + require.NoError(t, err) + assert.Equal(t, obj.Name, roundTripped.Name) + assert.Equal(t, obj.Id, roundTripped.Id) + v, _ := roundTripped.Get("extra1") + assert.Equal(t, 10, v) +} + +func TestTypedAdditionalPropertiesSetGet(t *testing.T) { + obj := TypedAdditionalProperties{Name: "test", Id: 1} + obj.Set("count", 42) + + val, found := obj.Get("count") + assert.True(t, found) + assert.Equal(t, 42, val) + + _, found = obj.Get("nonexistent") + assert.False(t, found) +} + +func TestNoAdditionalProperties(t *testing.T) { + obj := NoAdditionalProperties{Name: "test", Id: 1} + data, err := json.Marshal(obj) + require.NoError(t, err) + + var roundTripped NoAdditionalProperties + err = json.Unmarshal(data, &roundTripped) + require.NoError(t, err) + assert.Equal(t, obj, roundTripped) +} + +func TestAnyAdditionalProperties(t *testing.T) { + input := `{"name":"test","extra":"value","count":42}` + + var obj AnyAdditionalProperties + err := json.Unmarshal([]byte(input), &obj) + require.NoError(t, err) + + assert.Equal(t, "test", obj.Name) + + val, found := obj.Get("extra") + assert.True(t, found) + assert.Equal(t, "value", val) + + val, found = obj.Get("count") + assert.True(t, found) + assert.Equal(t, float64(42), val) // JSON numbers unmarshal as float64 + + // Set and round-trip + obj.Set("new_key", "new_value") + data, err := json.Marshal(obj) + require.NoError(t, err) + + var roundTripped AnyAdditionalProperties + err = json.Unmarshal(data, &roundTripped) + require.NoError(t, err) + v, _ := roundTripped.Get("new_key") + assert.Equal(t, "new_value", v) +} + +func TestNestedAdditionalProperties(t *testing.T) { + input := `{"name":"outer","inner":{"name":"inner_val","extra_inner":"hi"},"extra_outer":"bye"}` + + var obj NestedAdditionalProperties + err := json.Unmarshal([]byte(input), &obj) + require.NoError(t, err) + + assert.Equal(t, "outer", obj.Name) + assert.Equal(t, "inner_val", obj.Inner.Name) + + innerVal, found := obj.Inner.Get("extra_inner") + assert.True(t, found) + assert.Equal(t, "hi", innerVal) + + outerVal, found := obj.Get("extra_outer") + assert.True(t, found) + assert.Equal(t, "bye", outerVal) +} + +func TestRefAdditionalProperties(t *testing.T) { + refMap := RefAdditionalProperties{ + "user1": {Role: "admin", FirstName: "Alex"}, + "user2": {Role: "viewer", FirstName: "Sam"}, + } + + data, err := json.Marshal(refMap) + require.NoError(t, err) + + var roundTripped RefAdditionalProperties + err = json.Unmarshal(data, &roundTripped) + require.NoError(t, err) + + assert.Equal(t, "admin", roundTripped["user1"].Role) + assert.Equal(t, "Sam", roundTripped["user2"].FirstName) +} + +func TestArrayOfMaps(t *testing.T) { + arr := ArrayOfMaps{ + {"key1": {Role: "admin", FirstName: "Alex"}}, + {"key2": {Role: "viewer", FirstName: "Sam"}}, + } + + data, err := json.Marshal(arr) + require.NoError(t, err) + + var roundTripped ArrayOfMaps + err = json.Unmarshal(data, &roundTripped) + require.NoError(t, err) + + assert.Len(t, roundTripped, 2) + assert.Equal(t, "admin", roundTripped[0]["key1"].Role) +} + +func TestReadOnlyWriteOnly(t *testing.T) { + readOnly := "read_value" + writeOnly := 42 + obj := ReadOnlyWriteOnly{ + NormalProp: "normal", + ReadOnlyProp: &readOnly, + WriteOnlyProp: &writeOnly, + } + + data, err := json.Marshal(obj) + require.NoError(t, err) + + var roundTripped ReadOnlyWriteOnly + err = json.Unmarshal(data, &roundTripped) + require.NoError(t, err) + assert.Equal(t, "normal", roundTripped.NormalProp) + assert.Equal(t, "read_value", *roundTripped.ReadOnlyProp) + assert.Equal(t, 42, *roundTripped.WriteOnlyProp) +} diff --git a/internal/test/components/objects/spec.yaml b/internal/test/components/objects/spec.yaml new file mode 100644 index 0000000000..b97778dcb3 --- /dev/null +++ b/internal/test/components/objects/spec.yaml @@ -0,0 +1,119 @@ +openapi: "3.0.1" +info: + version: 1.0.0 + title: Object Schemas + description: Tests object schemas with various additionalProperties configurations +paths: + /ensure-everything-is-referenced: + get: + operationId: ensureEverythingIsReferenced + responses: + "200": + description: placeholder + content: + application/json: + schema: + type: object + properties: + one: + $ref: "#/components/schemas/TypedAdditionalProperties" + two: + $ref: "#/components/schemas/NoAdditionalProperties" + three: + $ref: "#/components/schemas/AnyAdditionalProperties" + four: + $ref: "#/components/schemas/NestedAdditionalProperties" + five: + $ref: "#/components/schemas/RefAdditionalProperties" + six: + $ref: "#/components/schemas/ArrayOfMaps" + seven: + $ref: "#/components/schemas/ReadOnlyWriteOnly" +components: + schemas: + BaseObject: + type: object + properties: + role: + type: string + firstName: + type: string + required: [role, firstName] + + TypedAdditionalProperties: + description: Has additional properties of type int + type: object + properties: + name: + type: string + id: + type: integer + optional: + type: string + required: [name, id] + additionalProperties: + type: integer + + NoAdditionalProperties: + description: Does not allow additional properties + type: object + properties: + name: + type: string + id: + type: integer + required: [name, id] + additionalProperties: false + + AnyAdditionalProperties: + description: Allows any additional property + type: object + properties: + name: + type: string + required: [name] + additionalProperties: true + + NestedAdditionalProperties: + description: Has anonymous field which has additional properties + type: object + properties: + name: + type: string + inner: + type: object + properties: + name: + type: string + required: [name] + additionalProperties: true + required: [inner, name] + additionalProperties: true + + RefAdditionalProperties: + description: Has additional properties with schema reference for dictionaries + type: object + additionalProperties: + $ref: "#/components/schemas/BaseObject" + + ArrayOfMaps: + description: Array of objects with additional properties + type: array + items: + type: object + additionalProperties: + $ref: "#/components/schemas/BaseObject" + + ReadOnlyWriteOnly: + type: object + properties: + readOnlyProp: + description: This property is required and readOnly + type: string + readOnly: true + writeOnlyProp: + type: integer + writeOnly: true + normalProp: + type: string + required: [readOnlyProp, writeOnlyProp, normalProp] diff --git a/internal/test/components/primitives/config.yaml b/internal/test/components/primitives/config.yaml new file mode 100644 index 0000000000..c59a95741b --- /dev/null +++ b/internal/test/components/primitives/config.yaml @@ -0,0 +1,5 @@ +# yaml-language-server: $schema=../../../../configuration-schema.json +package: primitives +generate: + models: true +output: primitives.gen.go diff --git a/internal/test/components/primitives/doc.go b/internal/test/components/primitives/doc.go new file mode 100644 index 0000000000..4649df49f2 --- /dev/null +++ b/internal/test/components/primitives/doc.go @@ -0,0 +1,3 @@ +package primitives + +//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml spec.yaml diff --git a/internal/test/components/primitives/primitives.gen.go b/internal/test/components/primitives/primitives.gen.go new file mode 100644 index 0000000000..ee73d13bc1 --- /dev/null +++ b/internal/test/components/primitives/primitives.gen.go @@ -0,0 +1,132 @@ +// Package primitives provides primitives to interact with the openapi HTTP API. +// +// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. +package primitives + +import ( + "time" + + openapi_types "github.com/oapi-codegen/runtime/types" +) + +// Defines values for EdgeCaseEnum. +const ( + EdgeCaseEnumBar EdgeCaseEnum = "Bar" + EdgeCaseEnumEmpty EdgeCaseEnum = "" + EdgeCaseEnumFoo EdgeCaseEnum = "Foo" + EdgeCaseEnumFoo1 EdgeCaseEnum = " Foo" + EdgeCaseEnumFoo2 EdgeCaseEnum = " Foo " + EdgeCaseEnumFooBar EdgeCaseEnum = "Foo Bar" + EdgeCaseEnumFooBar1 EdgeCaseEnum = "Foo-Bar" + EdgeCaseEnumN1 EdgeCaseEnum = "1" + EdgeCaseEnumN1Foo EdgeCaseEnum = "1Foo" + EdgeCaseEnumUnderscoreFoo EdgeCaseEnum = "_Foo_" +) + +// Valid indicates whether the value is a known member of the EdgeCaseEnum enum. +func (e EdgeCaseEnum) Valid() bool { + switch e { + case EdgeCaseEnumBar: + return true + case EdgeCaseEnumEmpty: + return true + case EdgeCaseEnumFoo: + return true + case EdgeCaseEnumFoo1: + return true + case EdgeCaseEnumFoo2: + return true + case EdgeCaseEnumFooBar: + return true + case EdgeCaseEnumFooBar1: + return true + case EdgeCaseEnumN1: + return true + case EdgeCaseEnumN1Foo: + return true + case EdgeCaseEnumUnderscoreFoo: + return true + default: + return false + } +} + +// Defines values for IntEnum. +const ( + IntEnumN1 IntEnum = 1 + IntEnumN2 IntEnum = 2 + IntEnumN3 IntEnum = 3 +) + +// Valid indicates whether the value is a known member of the IntEnum enum. +func (e IntEnum) Valid() bool { + switch e { + case IntEnumN1: + return true + case IntEnumN2: + return true + case IntEnumN3: + return true + default: + return false + } +} + +// Defines values for StringEnum. +const ( + Cat StringEnum = "cat" + Dog StringEnum = "dog" + Mouse StringEnum = "mouse" +) + +// Valid indicates whether the value is a known member of the StringEnum enum. +func (e StringEnum) Valid() bool { + switch e { + case Cat: + return true + case Dog: + return true + case Mouse: + return true + default: + return false + } +} + +// AliasedDate defines model for AliasedDate. +type AliasedDate = openapi_types.Date + +// AllFormats defines model for AllFormats. +type AllFormats struct { + ByteField []byte `json:"byteField"` + DateField openapi_types.Date `json:"dateField"` + DateTimeField time.Time `json:"dateTimeField"` + DoubleField float64 `json:"doubleField"` + EmailField openapi_types.Email `json:"emailField"` + FloatField float32 `json:"floatField"` + Int32Field int32 `json:"int32Field"` + Int64Field int64 `json:"int64Field"` + UuidField openapi_types.UUID `json:"uuidField"` +} + +// CustomFormatString defines model for CustomFormatString. +type CustomFormatString = string + +// EdgeCaseEnum Enum values with invalid Go identifiers +type EdgeCaseEnum string + +// IntEnum defines model for IntEnum. +type IntEnum int + +// Pet defines model for Pet. +type Pet struct { + Age *int32 `json:"age,omitempty"` + Born *AliasedDate `json:"born,omitempty"` + BornAt openapi_types.Date `json:"born_at"` + IsGood *bool `json:"is_good,omitempty"` + Name string `json:"name"` + Weight *float64 `json:"weight,omitempty"` +} + +// StringEnum defines model for StringEnum. +type StringEnum string diff --git a/internal/test/components/primitives/primitives_test.go b/internal/test/components/primitives/primitives_test.go new file mode 100644 index 0000000000..fd63994971 --- /dev/null +++ b/internal/test/components/primitives/primitives_test.go @@ -0,0 +1,167 @@ +package primitives + +import ( + "encoding/json" + "testing" + "time" + + "github.com/google/uuid" + openapi_types "github.com/oapi-codegen/runtime/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestPetTypeInstantiation(t *testing.T) { + age := int32(5) + weight := 12.5 + isGood := true + + pet := Pet{ + Name: "Fido", + Age: &age, + Weight: &weight, + IsGood: &isGood, + BornAt: openapi_types.Date{Time: time.Date(2020, 1, 15, 0, 0, 0, 0, time.UTC)}, + } + + assert.Equal(t, "Fido", pet.Name) + assert.Equal(t, int32(5), *pet.Age) + assert.Equal(t, 12.5, *pet.Weight) + assert.True(t, *pet.IsGood) +} + +func TestPetJSONRoundTrip(t *testing.T) { + input := `{"name":"Fido","age":5,"weight":12.5,"is_good":true,"born_at":"2020-01-15"}` + + var pet Pet + err := json.Unmarshal([]byte(input), &pet) + require.NoError(t, err) + + assert.Equal(t, "Fido", pet.Name) + assert.Equal(t, int32(5), *pet.Age) + assert.Equal(t, 12.5, *pet.Weight) + assert.True(t, *pet.IsGood) + assert.Equal(t, 2020, pet.BornAt.Time.Year()) + assert.Equal(t, time.January, pet.BornAt.Time.Month()) + assert.Equal(t, 15, pet.BornAt.Time.Day()) + + marshaled, err := json.Marshal(pet) + require.NoError(t, err) + + var roundTripped Pet + err = json.Unmarshal(marshaled, &roundTripped) + require.NoError(t, err) + assert.Equal(t, pet.Name, roundTripped.Name) + assert.Equal(t, *pet.Age, *roundTripped.Age) +} + +// From issue-579: aliased date types should unmarshal correctly. +func TestAliasedDateRoundTrip(t *testing.T) { + input := `{"name":"Fido","born":"2022-05-19","born_at":"2022-05-20"}` + + var pet Pet + err := json.Unmarshal([]byte(input), &pet) + require.NoError(t, err) + + assert.Equal(t, 2022, pet.Born.Time.Year()) + assert.Equal(t, time.May, pet.Born.Time.Month()) + assert.Equal(t, 19, pet.Born.Time.Day()) + + assert.Equal(t, 2022, pet.BornAt.Time.Year()) + assert.Equal(t, time.May, pet.BornAt.Time.Month()) + assert.Equal(t, 20, pet.BornAt.Time.Day()) +} + +func TestAllFormatsRoundTrip(t *testing.T) { + af := AllFormats{ + DateField: openapi_types.Date{Time: time.Date(2024, 6, 15, 0, 0, 0, 0, time.UTC)}, + DateTimeField: time.Date(2024, 6, 15, 10, 30, 0, 0, time.UTC), + UuidField: uuid.MustParse("550e8400-e29b-41d4-a716-446655440000"), + EmailField: "test@example.com", + Int32Field: 42, + Int64Field: 9999999999, + FloatField: 3.14, + DoubleField: 2.718281828, + ByteField: []byte("aGVsbG8="), + } + + data, err := json.Marshal(af) + require.NoError(t, err) + + var roundTripped AllFormats + err = json.Unmarshal(data, &roundTripped) + require.NoError(t, err) + + assert.Equal(t, af.Int32Field, roundTripped.Int32Field) + assert.Equal(t, af.Int64Field, roundTripped.Int64Field) + assert.InDelta(t, float64(af.FloatField), float64(roundTripped.FloatField), 0.001) + assert.Equal(t, af.DoubleField, roundTripped.DoubleField) + assert.Equal(t, af.EmailField, roundTripped.EmailField) +} + +func TestStringEnumValues(t *testing.T) { + assert.Equal(t, StringEnum("cat"), Cat) + assert.Equal(t, StringEnum("dog"), Dog) + assert.Equal(t, StringEnum("mouse"), Mouse) + + assert.True(t, Cat.Valid()) + assert.True(t, Dog.Valid()) + assert.True(t, Mouse.Valid()) + assert.False(t, StringEnum("fish").Valid()) +} + +func TestIntEnumValues(t *testing.T) { + assert.Equal(t, IntEnum(1), IntEnumN1) + assert.Equal(t, IntEnum(2), IntEnumN2) + assert.Equal(t, IntEnum(3), IntEnumN3) + + assert.True(t, IntEnumN1.Valid()) + assert.True(t, IntEnumN2.Valid()) + assert.True(t, IntEnumN3.Valid()) + assert.False(t, IntEnum(99).Valid()) +} + +// From issue-illegal_enum_names: enum values with invalid Go identifiers +// must be sanitized into valid const names. +func TestEdgeCaseEnumNames(t *testing.T) { + // The fact that these compile proves the names are valid Go identifiers. + // We verify the string values are correct. + assert.Equal(t, EdgeCaseEnum(""), EdgeCaseEnumEmpty) + assert.Equal(t, EdgeCaseEnum("Foo"), EdgeCaseEnumFoo) + assert.Equal(t, EdgeCaseEnum("Bar"), EdgeCaseEnumBar) + assert.Equal(t, EdgeCaseEnum("Foo Bar"), EdgeCaseEnumFooBar) + assert.Equal(t, EdgeCaseEnum("Foo-Bar"), EdgeCaseEnumFooBar1) + assert.Equal(t, EdgeCaseEnum("1Foo"), EdgeCaseEnumN1Foo) + assert.Equal(t, EdgeCaseEnum(" Foo"), EdgeCaseEnumFoo1) + assert.Equal(t, EdgeCaseEnum(" Foo "), EdgeCaseEnumFoo2) + assert.Equal(t, EdgeCaseEnum("_Foo_"), EdgeCaseEnumUnderscoreFoo) + assert.Equal(t, EdgeCaseEnum("1"), EdgeCaseEnumN1) + + // All edge case values should be valid. + assert.True(t, EdgeCaseEnumEmpty.Valid()) + assert.True(t, EdgeCaseEnumFooBar.Valid()) + assert.True(t, EdgeCaseEnumN1Foo.Valid()) +} + +func TestEnumJSONRoundTrip(t *testing.T) { + type wrapper struct { + S StringEnum `json:"s"` + I IntEnum `json:"i"` + E EdgeCaseEnum `json:"e"` + } + + w := wrapper{S: Dog, I: IntEnumN2, E: EdgeCaseEnumFooBar} + data, err := json.Marshal(w) + require.NoError(t, err) + + var roundTripped wrapper + err = json.Unmarshal(data, &roundTripped) + require.NoError(t, err) + assert.Equal(t, w, roundTripped) +} + +func TestCustomFormatString(t *testing.T) { + // CustomFormatString is a type alias for string. + var s CustomFormatString = "hello" + assert.Equal(t, "hello", s) +} diff --git a/internal/test/components/primitives/spec.yaml b/internal/test/components/primitives/spec.yaml new file mode 100644 index 0000000000..09af311787 --- /dev/null +++ b/internal/test/components/primitives/spec.yaml @@ -0,0 +1,126 @@ +openapi: "3.0.0" +info: + version: 1.0.0 + title: Primitive Types + description: Tests basic types, formats, date/time aliases, and enums +paths: + /ensure-everything-is-referenced: + get: + operationId: ensureEverythingIsReferenced + responses: + "200": + description: placeholder + content: + application/json: + schema: + type: object + properties: + pet: + $ref: "#/components/schemas/Pet" + aliasedDate: + $ref: "#/components/schemas/AliasedDate" + stringEnum: + $ref: "#/components/schemas/StringEnum" + intEnum: + $ref: "#/components/schemas/IntEnum" + edgeCaseEnum: + $ref: "#/components/schemas/EdgeCaseEnum" + customFormat: + $ref: "#/components/schemas/CustomFormatString" + allFormats: + $ref: "#/components/schemas/AllFormats" +components: + schemas: + AliasedDate: + type: string + format: date + + Pet: + type: object + required: + - name + - born_at + properties: + name: + type: string + age: + type: integer + format: int32 + weight: + type: number + format: double + is_good: + type: boolean + born: + $ref: "#/components/schemas/AliasedDate" + born_at: + type: string + format: date + + AllFormats: + type: object + required: + - dateField + - dateTimeField + - uuidField + - emailField + - int32Field + - int64Field + - floatField + - doubleField + - byteField + properties: + dateField: + type: string + format: date + dateTimeField: + type: string + format: date-time + uuidField: + type: string + format: uuid + emailField: + type: string + format: email + int32Field: + type: integer + format: int32 + int64Field: + type: integer + format: int64 + floatField: + type: number + format: float + doubleField: + type: number + format: double + byteField: + type: string + format: byte + + CustomFormatString: + type: string + format: custom + + StringEnum: + type: string + enum: [cat, dog, mouse] + + IntEnum: + type: integer + enum: [1, 2, 3] + + EdgeCaseEnum: + description: Enum values with invalid Go identifiers + type: string + enum: + - '' + - Foo + - Bar + - Foo Bar + - Foo-Bar + - 1Foo + - ' Foo' + - ' Foo ' + - _Foo_ + - "1" diff --git a/internal/test/issues/issue-1168/server.config.yaml b/internal/test/components/recursive/config.yaml similarity index 68% rename from internal/test/issues/issue-1168/server.config.yaml rename to internal/test/components/recursive/config.yaml index ff204a7c23..d500fabd51 100644 --- a/internal/test/issues/issue-1168/server.config.yaml +++ b/internal/test/components/recursive/config.yaml @@ -1,6 +1,5 @@ # yaml-language-server: $schema=../../../../configuration-schema.json -package: issue1168 -output: - api.gen.go +package: recursive generate: models: true +output: recursive.gen.go diff --git a/internal/test/externalref/petstore/doc.go b/internal/test/components/recursive/doc.go similarity index 85% rename from internal/test/externalref/petstore/doc.go rename to internal/test/components/recursive/doc.go index f05471ffbb..e99420089b 100644 --- a/internal/test/externalref/petstore/doc.go +++ b/internal/test/components/recursive/doc.go @@ -1,3 +1,3 @@ -package packagea +package recursive //go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml spec.yaml diff --git a/internal/test/issues/issue-936/api.gen.go b/internal/test/components/recursive/recursive.gen.go similarity index 95% rename from internal/test/issues/issue-936/api.gen.go rename to internal/test/components/recursive/recursive.gen.go index 6b7c0cf220..48d5515ada 100644 --- a/internal/test/issues/issue-936/api.gen.go +++ b/internal/test/components/recursive/recursive.gen.go @@ -1,7 +1,7 @@ -// Package issue936 provides primitives to interact with the openapi HTTP API. +// Package recursive provides primitives to interact with the openapi HTTP API. // // Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package issue936 +package recursive import ( "encoding/json" @@ -9,6 +9,19 @@ import ( "github.com/oapi-codegen/runtime" ) +// ArrayValue defines model for ArrayValue. +type ArrayValue = []Value + +// Document defines model for Document. +type Document struct { + Fields *map[string]Value `json:"fields,omitempty"` +} + +// FilterColumnIncludes defines model for FilterColumnIncludes. +type FilterColumnIncludes struct { + Includes *FilterPredicate `json:"$includes,omitempty"` +} + // FilterPredicate defines model for FilterPredicate. type FilterPredicate struct { union json.RawMessage @@ -69,6 +82,12 @@ type FilterValue1 = string // FilterValue2 defines model for . type FilterValue2 = bool +// Value defines model for Value. +type Value struct { + ArrayValue *ArrayValue `json:"arrayValue,omitempty"` + StringValue *string `json:"stringValue,omitempty"` +} + // AsFilterValue returns the union data inside the FilterPredicate as a FilterValue func (t FilterPredicate) AsFilterValue() (FilterValue, error) { var body FilterValue diff --git a/internal/test/components/recursive/recursive_test.go b/internal/test/components/recursive/recursive_test.go new file mode 100644 index 0000000000..942df06cc5 --- /dev/null +++ b/internal/test/components/recursive/recursive_test.go @@ -0,0 +1,135 @@ +package recursive + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// From issue-52: simple recursion (Document → Value → ArrayValue → Value). +func TestSimpleRecursiveTypes(t *testing.T) { + str := "hello" + inner := "world" + doc := Document{ + Fields: &map[string]Value{ + "greeting": { + StringValue: &str, + }, + "list": { + ArrayValue: &ArrayValue{ + {StringValue: &inner}, + }, + }, + }, + } + + data, err := json.Marshal(doc) + require.NoError(t, err) + + var roundTripped Document + err = json.Unmarshal(data, &roundTripped) + require.NoError(t, err) + + assert.NotNil(t, roundTripped.Fields) + fields := *roundTripped.Fields + assert.Equal(t, "hello", *fields["greeting"].StringValue) + assert.Len(t, *fields["list"].ArrayValue, 1) + assert.Equal(t, "world", *(*fields["list"].ArrayValue)[0].StringValue) +} + +func TestDeepRecursiveNesting(t *testing.T) { + // Build a deeply nested structure: Document → Value → ArrayValue → Value → ArrayValue → Value + deepStr := "deep" + midStr := "mid" + doc := Document{ + Fields: &map[string]Value{ + "level1": { + ArrayValue: &ArrayValue{ + { + ArrayValue: &ArrayValue{ + {StringValue: &deepStr}, + }, + StringValue: &midStr, + }, + }, + }, + }, + } + + data, err := json.Marshal(doc) + require.NoError(t, err) + + var roundTripped Document + err = json.Unmarshal(data, &roundTripped) + require.NoError(t, err) + + fields := *roundTripped.Fields + level1 := (*fields["level1"].ArrayValue)[0] + assert.Equal(t, "mid", *level1.StringValue) + level2 := (*level1.ArrayValue)[0] + assert.Equal(t, "deep", *level2.StringValue) +} + +// From issue-936: deep cyclic oneOf references (FilterPredicate → oneOf → FilterPredicateOp → FilterPredicate). +func TestFilterPredicateWithStringValue(t *testing.T) { + var fv FilterValue + err := fv.FromFilterValue1("test-string") + require.NoError(t, err) + + var fp FilterPredicate + err = fp.FromFilterValue(fv) + require.NoError(t, err) + + data, err := json.Marshal(fp) + require.NoError(t, err) + assert.Equal(t, `"test-string"`, string(data)) + + var roundTripped FilterPredicate + err = json.Unmarshal(data, &roundTripped) + require.NoError(t, err) + + gotValue, err := roundTripped.AsFilterValue() + require.NoError(t, err) + gotStr, err := gotValue.AsFilterValue1() + require.NoError(t, err) + assert.Equal(t, "test-string", gotStr) +} + +func TestFilterPredicateWithNumericValue(t *testing.T) { + var fv FilterValue + err := fv.FromFilterValue0(42.5) + require.NoError(t, err) + + var fp FilterPredicate + err = fp.FromFilterValue(fv) + require.NoError(t, err) + + data, err := json.Marshal(fp) + require.NoError(t, err) + assert.Equal(t, `42.5`, string(data)) +} + +func TestFilterColumnIncludesInstantiation(t *testing.T) { + // Verify we can instantiate the full recursive type hierarchy. + var fv FilterValue + err := fv.FromFilterValue2(true) + require.NoError(t, err) + + var fp FilterPredicate + err = fp.FromFilterValue(fv) + require.NoError(t, err) + + fci := FilterColumnIncludes{ + Includes: &fp, + } + + data, err := json.Marshal(fci) + require.NoError(t, err) + + var roundTripped FilterColumnIncludes + err = json.Unmarshal(data, &roundTripped) + require.NoError(t, err) + assert.NotNil(t, roundTripped.Includes) +} diff --git a/internal/test/components/recursive/spec.yaml b/internal/test/components/recursive/spec.yaml new file mode 100644 index 0000000000..d935e7b2c2 --- /dev/null +++ b/internal/test/components/recursive/spec.yaml @@ -0,0 +1,93 @@ +openapi: "3.0.2" +info: + version: 1.0.0 + title: Recursive Types + description: Tests recursive/cyclic schema references +paths: + /documents: + get: + operationId: getDocument + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: "#/components/schemas/Document" + /filters: + get: + operationId: getFilter + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: "#/components/schemas/FilterColumnIncludes" +components: + schemas: + # From issue-52: Document → Value → ArrayValue → Value (simple recursion) + Document: + type: object + properties: + fields: + type: object + additionalProperties: + $ref: "#/components/schemas/Value" + Value: + type: object + properties: + stringValue: + type: string + arrayValue: + $ref: "#/components/schemas/ArrayValue" + ArrayValue: + type: array + items: + $ref: "#/components/schemas/Value" + + # From issue-936: Deep cyclic oneOf references + FilterColumnIncludes: + type: object + properties: + $includes: + $ref: "#/components/schemas/FilterPredicate" + additionalProperties: false + FilterPredicate: + oneOf: + - $ref: "#/components/schemas/FilterValue" + - type: array + items: + $ref: "#/components/schemas/FilterPredicate" + - $ref: "#/components/schemas/FilterPredicateOp" + - $ref: "#/components/schemas/FilterPredicateRangeOp" + FilterPredicateOp: + type: object + properties: + $any: + oneOf: + - type: array + items: + $ref: "#/components/schemas/FilterPredicate" + $none: + oneOf: + - $ref: "#/components/schemas/FilterPredicate" + - type: array + items: + $ref: "#/components/schemas/FilterPredicate" + additionalProperties: false + FilterPredicateRangeOp: + type: object + properties: + $lt: + $ref: "#/components/schemas/FilterRangeValue" + additionalProperties: false + FilterRangeValue: + oneOf: + - type: number + - type: string + FilterValue: + oneOf: + - type: number + - type: string + - type: boolean diff --git a/internal/test/cookies/config.yaml b/internal/test/cookies/config.yaml deleted file mode 100644 index 2d1cbd4300..0000000000 --- a/internal/test/cookies/config.yaml +++ /dev/null @@ -1,6 +0,0 @@ -# yaml-language-server: $schema=../../../configuration-schema.json -package: cookies -generate: - chi-server: true - models: true -output: cookies.gen.go diff --git a/internal/test/cookies/cookies.gen.go b/internal/test/cookies/cookies.gen.go deleted file mode 100644 index 4e9b6139ec..0000000000 --- a/internal/test/cookies/cookies.gen.go +++ /dev/null @@ -1,215 +0,0 @@ -// Package cookies provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package cookies - -import ( - "fmt" - "net/http" - - "github.com/go-chi/chi/v5" - "github.com/oapi-codegen/runtime" -) - -// CookieParamsParams defines parameters for CookieParams. -type CookieParamsParams struct { - // AuthId Cookie parameter - AuthId *string `form:"authId,omitempty" json:"authId,omitempty"` - - // ServerId Another cookie parameter - ServerId *string `form:"serverId,omitempty" json:"serverId,omitempty"` -} - -// ServerInterface represents all server handlers. -type ServerInterface interface { - - // (GET /cookies) - CookieParams(w http.ResponseWriter, r *http.Request, params CookieParamsParams) -} - -// Unimplemented server implementation that returns http.StatusNotImplemented for each endpoint. - -type Unimplemented struct{} - -// (GET /cookies) -func (_ Unimplemented) CookieParams(w http.ResponseWriter, r *http.Request, params CookieParamsParams) { - w.WriteHeader(http.StatusNotImplemented) -} - -// ServerInterfaceWrapper converts contexts to parameters. -type ServerInterfaceWrapper struct { - Handler ServerInterface - HandlerMiddlewares []MiddlewareFunc - ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) -} - -type MiddlewareFunc func(http.Handler) http.Handler - -// CookieParams operation middleware -func (siw *ServerInterfaceWrapper) CookieParams(w http.ResponseWriter, r *http.Request) { - - var err error - - // Parameter object where we will unmarshal all parameters from the context - var params CookieParamsParams - - { - var cookie *http.Cookie - - if cookie, err = r.Cookie("authId"); err == nil { - var value string - err = runtime.BindStyledParameterWithOptions("simple", "authId", cookie.Value, &value, runtime.BindStyledParameterOptions{Explode: true, Required: false, Type: "string", Format: ""}) - if err != nil { - siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "authId", Err: err}) - return - } - params.AuthId = &value - - } - } - - { - var cookie *http.Cookie - - if cookie, err = r.Cookie("serverId"); err == nil { - var value string - err = runtime.BindStyledParameterWithOptions("simple", "serverId", cookie.Value, &value, runtime.BindStyledParameterOptions{Explode: true, Required: false, Type: "string", Format: ""}) - if err != nil { - siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "serverId", Err: err}) - return - } - params.ServerId = &value - - } - } - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.CookieParams(w, r, params) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -type UnescapedCookieParamError struct { - ParamName string - Err error -} - -func (e *UnescapedCookieParamError) Error() string { - return fmt.Sprintf("error unescaping cookie parameter '%s'", e.ParamName) -} - -func (e *UnescapedCookieParamError) Unwrap() error { - return e.Err -} - -type UnmarshalingParamError struct { - ParamName string - Err error -} - -func (e *UnmarshalingParamError) Error() string { - return fmt.Sprintf("Error unmarshaling parameter %s as JSON: %s", e.ParamName, e.Err.Error()) -} - -func (e *UnmarshalingParamError) Unwrap() error { - return e.Err -} - -type RequiredParamError struct { - ParamName string -} - -func (e *RequiredParamError) Error() string { - return fmt.Sprintf("Query argument %s is required, but not found", e.ParamName) -} - -type RequiredHeaderError struct { - ParamName string - Err error -} - -func (e *RequiredHeaderError) Error() string { - return fmt.Sprintf("Header parameter %s is required, but not found", e.ParamName) -} - -func (e *RequiredHeaderError) Unwrap() error { - return e.Err -} - -type InvalidParamFormatError struct { - ParamName string - Err error -} - -func (e *InvalidParamFormatError) Error() string { - return fmt.Sprintf("Invalid format for parameter %s: %s", e.ParamName, e.Err.Error()) -} - -func (e *InvalidParamFormatError) Unwrap() error { - return e.Err -} - -type TooManyValuesForParamError struct { - ParamName string - Count int -} - -func (e *TooManyValuesForParamError) Error() string { - return fmt.Sprintf("Expected one value for %s, got %d", e.ParamName, e.Count) -} - -// Handler creates http.Handler with routing matching OpenAPI spec. -func Handler(si ServerInterface) http.Handler { - return HandlerWithOptions(si, ChiServerOptions{}) -} - -type ChiServerOptions struct { - BaseURL string - BaseRouter chi.Router - Middlewares []MiddlewareFunc - ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) -} - -// HandlerFromMux creates http.Handler with routing matching OpenAPI spec based on the provided mux. -func HandlerFromMux(si ServerInterface, r chi.Router) http.Handler { - return HandlerWithOptions(si, ChiServerOptions{ - BaseRouter: r, - }) -} - -func HandlerFromMuxWithBaseURL(si ServerInterface, r chi.Router, baseURL string) http.Handler { - return HandlerWithOptions(si, ChiServerOptions{ - BaseURL: baseURL, - BaseRouter: r, - }) -} - -// HandlerWithOptions creates http.Handler with additional options -func HandlerWithOptions(si ServerInterface, options ChiServerOptions) http.Handler { - r := options.BaseRouter - - if r == nil { - r = chi.NewRouter() - } - if options.ErrorHandlerFunc == nil { - options.ErrorHandlerFunc = func(w http.ResponseWriter, r *http.Request, err error) { - http.Error(w, err.Error(), http.StatusBadRequest) - } - } - wrapper := ServerInterfaceWrapper{ - Handler: si, - HandlerMiddlewares: options.Middlewares, - ErrorHandlerFunc: options.ErrorHandlerFunc, - } - - r.Group(func(r chi.Router) { - r.Get(options.BaseURL+"/cookies", wrapper.CookieParams) - }) - - return r -} diff --git a/internal/test/cookies/generate.go b/internal/test/cookies/generate.go deleted file mode 100644 index 46a9a52676..0000000000 --- a/internal/test/cookies/generate.go +++ /dev/null @@ -1,3 +0,0 @@ -package cookies - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml spec.yaml diff --git a/internal/test/cookies/spec.yaml b/internal/test/cookies/spec.yaml deleted file mode 100644 index f30596224f..0000000000 --- a/internal/test/cookies/spec.yaml +++ /dev/null @@ -1,24 +0,0 @@ -openapi: "3.0.1" -info: - version: 1.0.0 - title: Cookie parameters -paths: - /cookies: - get: - operationId: cookieParams - parameters: - - name: authId - description: Cookie parameter - in: cookie - required: false - schema: - type: string - - name: serverId - description: Another cookie parameter - in: cookie - required: false - schema: - type: string - responses: - 204: - description: no content diff --git a/internal/test/extensions/x-order/config.yaml b/internal/test/extensions/x-order/config.yaml deleted file mode 100644 index 357489f37d..0000000000 --- a/internal/test/extensions/x-order/config.yaml +++ /dev/null @@ -1,7 +0,0 @@ -# yaml-language-server: $schema=../../../../configuration-schema.json -package: xorder -generate: - models: true -output: issue.gen.go -output-options: - skip-prune: true diff --git a/internal/test/extensions/x-order/issue.gen.go b/internal/test/extensions/x-order/issue.gen.go deleted file mode 100644 index c665ee8ad5..0000000000 --- a/internal/test/extensions/x-order/issue.gen.go +++ /dev/null @@ -1,27 +0,0 @@ -// Package xorder provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package xorder - -import ( - openapi_types "github.com/oapi-codegen/runtime/types" -) - -// DateInterval defines model for DateInterval. -type DateInterval struct { - Start *openapi_types.Date `json:"start,omitempty"` - End *openapi_types.Date `json:"end,omitempty"` -} - -// Port defines model for Port. -type Port = int - -// PortInterval defines model for PortInterval. -type PortInterval struct { - Start Port `json:"start"` - End Port `json:"end"` - VeryEnd *LowPriorityPort `json:"very_end,omitempty"` -} - -// LowPriorityPort defines model for LowPriorityPort. -type LowPriorityPort = int diff --git a/internal/test/extensions/x-order/spec.yaml b/internal/test/extensions/x-order/spec.yaml deleted file mode 100644 index edc52625da..0000000000 --- a/internal/test/extensions/x-order/spec.yaml +++ /dev/null @@ -1,34 +0,0 @@ -components: - schemas: - DateInterval: - type: object - required: - - name - properties: - end: - type: string - format: date - x-order: 2 - start: - type: string - format: date - x-order: 1 - Port: - type: integer - LowPriorityPort: - type: integer - x-order: 50 - PortInterval: - type: object - required: - - start - - end - properties: - end: - $ref: '#/components/schemas/Port' - x-order: 2 - very_end: - $ref: '#/components/schemas/LowPriorityPort' - start: - $ref: '#/components/schemas/Port' - x-order: 1 diff --git a/internal/test/issues/issue-2113/common/spec.yaml b/internal/test/externalref/common/spec.yaml similarity index 100% rename from internal/test/issues/issue-2113/common/spec.yaml rename to internal/test/externalref/common/spec.yaml diff --git a/internal/test/issues/issue-2113/config.api.yaml b/internal/test/externalref/config.api.yaml similarity index 66% rename from internal/test/issues/issue-2113/config.api.yaml rename to internal/test/externalref/config.api.yaml index 754af9fa49..23d4039fc6 100644 --- a/internal/test/issues/issue-2113/config.api.yaml +++ b/internal/test/externalref/config.api.yaml @@ -1,11 +1,11 @@ -# yaml-language-server: $schema=../../../../configuration-schema.json +# yaml-language-server: $schema=../../../configuration-schema.json package: api generate: chi-server: true strict-server: true models: true import-mapping: - ./common/spec.yaml: github.com/oapi-codegen/oapi-codegen/v2/internal/test/issues/issue-2113/gen/common + ./common/spec.yaml: github.com/oapi-codegen/oapi-codegen/v2/internal/test/externalref/gen/common output: gen/api/api.gen.go output-options: skip-prune: true diff --git a/internal/test/components/config.yaml b/internal/test/externalref/config.common.yaml similarity index 72% rename from internal/test/components/config.yaml rename to internal/test/externalref/config.common.yaml index 185203a501..631b4e068c 100644 --- a/internal/test/components/config.yaml +++ b/internal/test/externalref/config.common.yaml @@ -1,7 +1,7 @@ # yaml-language-server: $schema=../../../configuration-schema.json -package: components +package: common generate: models: true +output: gen/common/common.gen.go output-options: skip-prune: true -output: components.gen.go diff --git a/internal/test/externalref/doc.go b/internal/test/externalref/doc.go index c5aeaa5221..203a410e9b 100644 --- a/internal/test/externalref/doc.go +++ b/internal/test/externalref/doc.go @@ -1,3 +1,4 @@ package externalref -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=externalref.cfg.yaml spec.yaml +//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.common.yaml common/spec.yaml +//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.api.yaml spec.yaml diff --git a/internal/test/externalref/externalref.cfg.yaml b/internal/test/externalref/externalref.cfg.yaml deleted file mode 100644 index dd7a93d019..0000000000 --- a/internal/test/externalref/externalref.cfg.yaml +++ /dev/null @@ -1,12 +0,0 @@ -# yaml-language-server: $schema=../../../configuration-schema.json -package: externalref -generate: - models: true - embedded-spec: true -import-mapping: - ./packageA/spec.yaml: github.com/oapi-codegen/oapi-codegen/v2/internal/test/externalref/packageA - ./packageB/spec.yaml: package_b github.com/oapi-codegen/oapi-codegen/v2/internal/test/externalref/packageB - https://petstore3.swagger.io/api/v3/openapi.json: github.com/oapi-codegen/oapi-codegen/v2/internal/test/externalref/petstore -output: externalref.gen.go -output-options: - skip-prune: true diff --git a/internal/test/externalref/externalref.gen.go b/internal/test/externalref/externalref.gen.go deleted file mode 100644 index 158a922d02..0000000000 --- a/internal/test/externalref/externalref.gen.go +++ /dev/null @@ -1,130 +0,0 @@ -// Package externalref provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package externalref - -import ( - "bytes" - "compress/gzip" - "encoding/base64" - "fmt" - "net/url" - "path" - "strings" - - "github.com/getkin/kin-openapi/openapi3" - externalRef0 "github.com/oapi-codegen/oapi-codegen/v2/internal/test/externalref/packageA" - package_b "github.com/oapi-codegen/oapi-codegen/v2/internal/test/externalref/packageB" - externalRef1 "github.com/oapi-codegen/oapi-codegen/v2/internal/test/externalref/petstore" -) - -// Container defines model for Container. -type Container struct { - ObjectA *externalRef0.ObjectA `json:"object_a,omitempty"` - ObjectB *package_b.ObjectB `json:"object_b,omitempty"` - ObjectC *map[string]interface{} `json:"object_c,omitempty"` - Pet *externalRef1.Pet `json:"pet,omitempty"` -} - -// Base64 encoded, gzipped, json marshaled Swagger object -var swaggerSpec = []string{ - - "H4sIAAAAAAAC/6RUTW/bMAz9KwG3o9Bk6LCDb213Xw7bqSgMRmYcbbakSUzWoNB/Hyg1jROnSLJdDJof", - "D+890n4B7XrvLFmOUL1A1CvqMYcPzjIaS0FefHCeAhvKJbf4SZprlPhjoCVU8GG6B5q+okw96l/Y0l0d", - "Pen6W566g6R2AIsLAe6HAPcDAH0O4K0vKfDE59rRm3pzWztPVsI5MaSUFBzlH5CpdWE7dsY08qRn7H1H", - "UH1SsHShR4YKjOUvn0EBbz2VV2opCDGLPR2MwVfXxn1r5GBsC0LkNVNkgYLnvpPJggB6x+sE53lRf0hX", - "D4Rc4cub/qRGimf/KLlxbWtoLFqBXzl2P0JXDGbqc3DYduzEbmZoGoaA233nn4DeUwMVhzVJW2TkdcZu", - "KOpgPBtnBYt4UmoTYye8oklkF4Qq2XUP1SPgBk2Hi05ynmxTGEXXNfB0QhBje6jlCuu/Y4G4RFJSEOj3", - "2gRJPRZrhnY+nbsnn+9/dErC4Z3Lv2L11x43Y+kafvrYNEa2hN18QEbUH6PJHZ38G42EvMPvv39aaU/h", - "qHQphZQxjF26XDScPxxQsKEQy61mnmVNUMHtzexmJitHXglwSn8DAAD//xIv2MTwBQAA", -} - -// GetSwagger returns the content of the embedded swagger specification file -// or error if failed to decode -func decodeSpec() ([]byte, error) { - zipped, err := base64.StdEncoding.DecodeString(strings.Join(swaggerSpec, "")) - if err != nil { - return nil, fmt.Errorf("error base64 decoding spec: %w", err) - } - zr, err := gzip.NewReader(bytes.NewReader(zipped)) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - var buf bytes.Buffer - _, err = buf.ReadFrom(zr) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - - return buf.Bytes(), nil -} - -var rawSpec = decodeSpecCached() - -// a naive cached of a decoded swagger spec -func decodeSpecCached() func() ([]byte, error) { - data, err := decodeSpec() - return func() ([]byte, error) { - return data, err - } -} - -// Constructs a synthetic filesystem for resolving external references when loading openapi specifications. -func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { - res := make(map[string]func() ([]byte, error)) - if len(pathToFile) > 0 { - res[pathToFile] = rawSpec - } - - for rawPath, rawFunc := range externalRef0.PathToRawSpec(path.Join(path.Dir(pathToFile), "./packageA/spec.yaml")) { - if _, ok := res[rawPath]; ok { - // it is not possible to compare functions in golang, so always overwrite the old value - } - res[rawPath] = rawFunc - } - for rawPath, rawFunc := range package_b.PathToRawSpec(path.Join(path.Dir(pathToFile), "./packageB/spec.yaml")) { - if _, ok := res[rawPath]; ok { - // it is not possible to compare functions in golang, so always overwrite the old value - } - res[rawPath] = rawFunc - } - for rawPath, rawFunc := range externalRef1.PathToRawSpec(path.Join(path.Dir(pathToFile), "https://petstore3.swagger.io/api/v3/openapi.json")) { - if _, ok := res[rawPath]; ok { - // it is not possible to compare functions in golang, so always overwrite the old value - } - res[rawPath] = rawFunc - } - return res -} - -// GetSwagger returns the Swagger specification corresponding to the generated code -// in this file. The external references of Swagger specification are resolved. -// The logic of resolving external references is tightly connected to "import-mapping" feature. -// Externally referenced files must be embedded in the corresponding golang packages. -// Urls can be supported but this task was out of the scope. -func GetSwagger() (swagger *openapi3.T, err error) { - resolvePath := PathToRawSpec("") - - loader := openapi3.NewLoader() - loader.IsExternalRefsAllowed = true - loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() - pathToFile = path.Clean(pathToFile) - getSpec, ok := resolvePath[pathToFile] - if !ok { - err1 := fmt.Errorf("path not found: %s", pathToFile) - return nil, err1 - } - return getSpec() - } - var specData []byte - specData, err = rawSpec() - if err != nil { - return - } - swagger, err = loader.LoadFromData(specData) - if err != nil { - return - } - return -} diff --git a/internal/test/externalref/externalref_test.go b/internal/test/externalref/externalref_test.go new file mode 100644 index 0000000000..79ae749f72 --- /dev/null +++ b/internal/test/externalref/externalref_test.go @@ -0,0 +1,20 @@ +package externalref + +import ( + "testing" + + "github.com/oapi-codegen/oapi-codegen/v2/internal/test/externalref/gen/api" + "github.com/oapi-codegen/oapi-codegen/v2/internal/test/externalref/gen/common" +) + +// From issue-2113: verify that a $ref to an external components/responses +// object correctly qualifies the schema type with the external package import. +func TestExternalRefInResponse(t *testing.T) { + // This will fail to compile if the generated code uses ProblemDetails + // instead of common.ProblemDetails (via the externalRef alias) in the + // default response type. + _ = api.ListThingsdefaultJSONResponse{ + Body: common.ProblemDetails{Title: "err", Status: 500}, + StatusCode: 500, + } +} diff --git a/internal/test/issues/issue-2113/gen/api/api.gen.go b/internal/test/externalref/gen/api/api.gen.go similarity index 99% rename from internal/test/issues/issue-2113/gen/api/api.gen.go rename to internal/test/externalref/gen/api/api.gen.go index 6562a7f30d..17646501d0 100644 --- a/internal/test/issues/issue-2113/gen/api/api.gen.go +++ b/internal/test/externalref/gen/api/api.gen.go @@ -10,7 +10,7 @@ import ( "net/http" "github.com/go-chi/chi/v5" - externalRef0 "github.com/oapi-codegen/oapi-codegen/v2/internal/test/issues/issue-2113/gen/common" + externalRef0 "github.com/oapi-codegen/oapi-codegen/v2/internal/test/externalref/gen/common" strictnethttp "github.com/oapi-codegen/runtime/strictmiddleware/nethttp" ) diff --git a/internal/test/issues/issue-2113/gen/common/common.gen.go b/internal/test/externalref/gen/common/common.gen.go similarity index 100% rename from internal/test/issues/issue-2113/gen/common/common.gen.go rename to internal/test/externalref/gen/common/common.gen.go diff --git a/internal/test/externalref/imports_test.go b/internal/test/externalref/imports_test.go deleted file mode 100644 index 34fd0ec11e..0000000000 --- a/internal/test/externalref/imports_test.go +++ /dev/null @@ -1,32 +0,0 @@ -package externalref - -import ( - "testing" - - packageA "github.com/oapi-codegen/oapi-codegen/v2/internal/test/externalref/packageA" - packageB "github.com/oapi-codegen/oapi-codegen/v2/internal/test/externalref/packageB" - petstore "github.com/oapi-codegen/oapi-codegen/v2/internal/test/externalref/petstore" - "github.com/stretchr/testify/require" -) - -func TestParameters(t *testing.T) { - b := &packageB.ObjectB{} - _ = Container{ - ObjectA: &packageA.ObjectA{ObjectB: b}, - ObjectB: b, - } -} - -func TestGetSwagger(t *testing.T) { - _, err := packageB.GetSwagger() - require.Nil(t, err) - - _, err = packageA.GetSwagger() - require.Nil(t, err) - - _, err = petstore.GetSwagger() - require.Nil(t, err) - - _, err = GetSwagger() - require.Nil(t, err) -} diff --git a/internal/test/externalref/object_c.json b/internal/test/externalref/object_c.json deleted file mode 100644 index b85043d148..0000000000 --- a/internal/test/externalref/object_c.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "type": "object", - "properties": {}, - "additionalProperties": true -} diff --git a/internal/test/externalref/packageA/config.yaml b/internal/test/externalref/packageA/config.yaml deleted file mode 100644 index 6ee1a13699..0000000000 --- a/internal/test/externalref/packageA/config.yaml +++ /dev/null @@ -1,10 +0,0 @@ -# yaml-language-server: $schema=../../../../configuration-schema.json -package: packagea -generate: - models: true - embedded-spec: true -output-options: - skip-prune: true -import-mapping: - ../packageB/spec.yaml: github.com/oapi-codegen/oapi-codegen/v2/internal/test/externalref/packageB -output: externalref.gen.go diff --git a/internal/test/externalref/packageA/externalref.gen.go b/internal/test/externalref/packageA/externalref.gen.go deleted file mode 100644 index 582588326c..0000000000 --- a/internal/test/externalref/packageA/externalref.gen.go +++ /dev/null @@ -1,109 +0,0 @@ -// Package packagea provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package packagea - -import ( - "bytes" - "compress/gzip" - "encoding/base64" - "fmt" - "net/url" - "path" - "strings" - - "github.com/getkin/kin-openapi/openapi3" - externalRef0 "github.com/oapi-codegen/oapi-codegen/v2/internal/test/externalref/packageB" -) - -// ObjectA defines model for ObjectA. -type ObjectA struct { - Name *string `json:"name,omitempty"` - ObjectB *externalRef0.ObjectB `json:"object_b,omitempty"` -} - -// Base64 encoded, gzipped, json marshaled Swagger object -var swaggerSpec = []string{ - - "H4sIAAAAAAAC/4yOMcrDMAxG7/L9/xjI7q25QI8QHKMkbhNZ2OpQgu5e7BS6dOikBw896UBIuyQm1gJ3", - "oISVdt/wOt0o6KWi5CSUNVIT7HeqU59CcCiaIy+wDqltjFOV/5lmOPz1n37/jvfiw90vNIxFKIznnQFm", - "1uG7+vUFa43Ic4Ljx7Z1SELsJcIBNa5rOY29AgAA//84dUj5+QAAAA==", -} - -// GetSwagger returns the content of the embedded swagger specification file -// or error if failed to decode -func decodeSpec() ([]byte, error) { - zipped, err := base64.StdEncoding.DecodeString(strings.Join(swaggerSpec, "")) - if err != nil { - return nil, fmt.Errorf("error base64 decoding spec: %w", err) - } - zr, err := gzip.NewReader(bytes.NewReader(zipped)) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - var buf bytes.Buffer - _, err = buf.ReadFrom(zr) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - - return buf.Bytes(), nil -} - -var rawSpec = decodeSpecCached() - -// a naive cached of a decoded swagger spec -func decodeSpecCached() func() ([]byte, error) { - data, err := decodeSpec() - return func() ([]byte, error) { - return data, err - } -} - -// Constructs a synthetic filesystem for resolving external references when loading openapi specifications. -func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { - res := make(map[string]func() ([]byte, error)) - if len(pathToFile) > 0 { - res[pathToFile] = rawSpec - } - - for rawPath, rawFunc := range externalRef0.PathToRawSpec(path.Join(path.Dir(pathToFile), "../packageB/spec.yaml")) { - if _, ok := res[rawPath]; ok { - // it is not possible to compare functions in golang, so always overwrite the old value - } - res[rawPath] = rawFunc - } - return res -} - -// GetSwagger returns the Swagger specification corresponding to the generated code -// in this file. The external references of Swagger specification are resolved. -// The logic of resolving external references is tightly connected to "import-mapping" feature. -// Externally referenced files must be embedded in the corresponding golang packages. -// Urls can be supported but this task was out of the scope. -func GetSwagger() (swagger *openapi3.T, err error) { - resolvePath := PathToRawSpec("") - - loader := openapi3.NewLoader() - loader.IsExternalRefsAllowed = true - loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() - pathToFile = path.Clean(pathToFile) - getSpec, ok := resolvePath[pathToFile] - if !ok { - err1 := fmt.Errorf("path not found: %s", pathToFile) - return nil, err1 - } - return getSpec() - } - var specData []byte - specData, err = rawSpec() - if err != nil { - return - } - swagger, err = loader.LoadFromData(specData) - if err != nil { - return - } - return -} diff --git a/internal/test/externalref/packageA/spec.yaml b/internal/test/externalref/packageA/spec.yaml deleted file mode 100644 index b2386a097e..0000000000 --- a/internal/test/externalref/packageA/spec.yaml +++ /dev/null @@ -1,8 +0,0 @@ -components: - schemas: - ObjectA: - properties: - name: - type: string - object_b: - $ref: ../packageB/spec.yaml#/components/schemas/ObjectB \ No newline at end of file diff --git a/internal/test/externalref/packageB/config.yaml b/internal/test/externalref/packageB/config.yaml deleted file mode 100644 index 3dc9b7ce7b..0000000000 --- a/internal/test/externalref/packageB/config.yaml +++ /dev/null @@ -1,8 +0,0 @@ -# yaml-language-server: $schema=../../../../configuration-schema.json -package: packageb -generate: - models: true - embedded-spec: true -output-options: - skip-prune: true -output: externalref.gen.go diff --git a/internal/test/externalref/packageB/externalref.gen.go b/internal/test/externalref/packageB/externalref.gen.go deleted file mode 100644 index c3f879cfda..0000000000 --- a/internal/test/externalref/packageB/externalref.gen.go +++ /dev/null @@ -1,100 +0,0 @@ -// Package packageb provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package packageb - -import ( - "bytes" - "compress/gzip" - "encoding/base64" - "fmt" - "net/url" - "path" - "strings" - - "github.com/getkin/kin-openapi/openapi3" -) - -// ObjectB defines model for ObjectB. -type ObjectB struct { - Name *string `json:"name,omitempty"` -} - -// Base64 encoded, gzipped, json marshaled Swagger object -var swaggerSpec = []string{ - - "H4sIAAAAAAAC/yTJwQ0CMQxE0V7mnApypAFqCNHAGm1sKzYHtNreUZa5zJfegW7DTakZqAeibxztyvvj", - "zZ63lT7NOVN4gbbB9fl1oiJyir5wrhWIPg1VP/teYE5tLqhAgbfc4i/nLwAA//8neaWPdgAAAA==", -} - -// GetSwagger returns the content of the embedded swagger specification file -// or error if failed to decode -func decodeSpec() ([]byte, error) { - zipped, err := base64.StdEncoding.DecodeString(strings.Join(swaggerSpec, "")) - if err != nil { - return nil, fmt.Errorf("error base64 decoding spec: %w", err) - } - zr, err := gzip.NewReader(bytes.NewReader(zipped)) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - var buf bytes.Buffer - _, err = buf.ReadFrom(zr) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - - return buf.Bytes(), nil -} - -var rawSpec = decodeSpecCached() - -// a naive cached of a decoded swagger spec -func decodeSpecCached() func() ([]byte, error) { - data, err := decodeSpec() - return func() ([]byte, error) { - return data, err - } -} - -// Constructs a synthetic filesystem for resolving external references when loading openapi specifications. -func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { - res := make(map[string]func() ([]byte, error)) - if len(pathToFile) > 0 { - res[pathToFile] = rawSpec - } - - return res -} - -// GetSwagger returns the Swagger specification corresponding to the generated code -// in this file. The external references of Swagger specification are resolved. -// The logic of resolving external references is tightly connected to "import-mapping" feature. -// Externally referenced files must be embedded in the corresponding golang packages. -// Urls can be supported but this task was out of the scope. -func GetSwagger() (swagger *openapi3.T, err error) { - resolvePath := PathToRawSpec("") - - loader := openapi3.NewLoader() - loader.IsExternalRefsAllowed = true - loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() - pathToFile = path.Clean(pathToFile) - getSpec, ok := resolvePath[pathToFile] - if !ok { - err1 := fmt.Errorf("path not found: %s", pathToFile) - return nil, err1 - } - return getSpec() - } - var specData []byte - specData, err = rawSpec() - if err != nil { - return - } - swagger, err = loader.LoadFromData(specData) - if err != nil { - return - } - return -} diff --git a/internal/test/externalref/packageB/spec.yaml b/internal/test/externalref/packageB/spec.yaml deleted file mode 100644 index 6f90634711..0000000000 --- a/internal/test/externalref/packageB/spec.yaml +++ /dev/null @@ -1,6 +0,0 @@ -components: - schemas: - ObjectB: - properties: - name: - type: string diff --git a/internal/test/externalref/petstore/config.yaml b/internal/test/externalref/petstore/config.yaml deleted file mode 100644 index 6ee1a13699..0000000000 --- a/internal/test/externalref/petstore/config.yaml +++ /dev/null @@ -1,10 +0,0 @@ -# yaml-language-server: $schema=../../../../configuration-schema.json -package: packagea -generate: - models: true - embedded-spec: true -output-options: - skip-prune: true -import-mapping: - ../packageB/spec.yaml: github.com/oapi-codegen/oapi-codegen/v2/internal/test/externalref/packageB -output: externalref.gen.go diff --git a/internal/test/externalref/petstore/externalref.gen.go b/internal/test/externalref/petstore/externalref.gen.go deleted file mode 100644 index e8102f0d28..0000000000 --- a/internal/test/externalref/petstore/externalref.gen.go +++ /dev/null @@ -1,382 +0,0 @@ -// Package packagea provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package packagea - -import ( - "bytes" - "compress/gzip" - "encoding/base64" - "fmt" - "net/url" - "path" - "strings" - "time" - - "github.com/getkin/kin-openapi/openapi3" - externalRef0 "github.com/oapi-codegen/oapi-codegen/v2/internal/test/externalref/packageB" -) - -const ( - Api_keyScopes = "api_key.Scopes" - Petstore_authScopes = "petstore_auth.Scopes" -) - -// Defines values for OrderStatus. -const ( - Approved OrderStatus = "approved" - Delivered OrderStatus = "delivered" - Placed OrderStatus = "placed" -) - -// Valid indicates whether the value is a known member of the OrderStatus enum. -func (e OrderStatus) Valid() bool { - switch e { - case Approved: - return true - case Delivered: - return true - case Placed: - return true - default: - return false - } -} - -// Defines values for PetStatus. -const ( - PetStatusAvailable PetStatus = "available" - PetStatusPending PetStatus = "pending" - PetStatusSold PetStatus = "sold" -) - -// Valid indicates whether the value is a known member of the PetStatus enum. -func (e PetStatus) Valid() bool { - switch e { - case PetStatusAvailable: - return true - case PetStatusPending: - return true - case PetStatusSold: - return true - default: - return false - } -} - -// Defines values for FindPetsByStatusParamsStatus. -const ( - FindPetsByStatusParamsStatusAvailable FindPetsByStatusParamsStatus = "available" - FindPetsByStatusParamsStatusPending FindPetsByStatusParamsStatus = "pending" - FindPetsByStatusParamsStatusSold FindPetsByStatusParamsStatus = "sold" -) - -// Valid indicates whether the value is a known member of the FindPetsByStatusParamsStatus enum. -func (e FindPetsByStatusParamsStatus) Valid() bool { - switch e { - case FindPetsByStatusParamsStatusAvailable: - return true - case FindPetsByStatusParamsStatusPending: - return true - case FindPetsByStatusParamsStatusSold: - return true - default: - return false - } -} - -// Address defines model for Address. -type Address struct { - City *string `json:"city,omitempty"` - State *string `json:"state,omitempty"` - Street *string `json:"street,omitempty"` - Zip *string `json:"zip,omitempty"` -} - -// ApiResponse defines model for ApiResponse. -type ApiResponse struct { - Code *int32 `json:"code,omitempty"` - Message *string `json:"message,omitempty"` - Type *string `json:"type,omitempty"` -} - -// Category defines model for Category. -type Category struct { - Id *int64 `json:"id,omitempty"` - Name *string `json:"name,omitempty"` -} - -// Customer defines model for Customer. -type Customer struct { - Address *[]Address `json:"address,omitempty"` - Id *int64 `json:"id,omitempty"` - Username *string `json:"username,omitempty"` -} - -// Order defines model for Order. -type Order struct { - Complete *bool `json:"complete,omitempty"` - Id *int64 `json:"id,omitempty"` - PetId *int64 `json:"petId,omitempty"` - Quantity *int32 `json:"quantity,omitempty"` - ShipDate *time.Time `json:"shipDate,omitempty"` - - // Status Order Status - Status *OrderStatus `json:"status,omitempty"` -} - -// OrderStatus Order Status -type OrderStatus string - -// Pet defines model for Pet. -type Pet struct { - Category *Category `json:"category,omitempty"` - Id *int64 `json:"id,omitempty"` - Name string `json:"name"` - PhotoUrls []string `json:"photoUrls"` - - // Status pet status in the store - Status *PetStatus `json:"status,omitempty"` - Tags *[]Tag `json:"tags,omitempty"` -} - -// PetStatus pet status in the store -type PetStatus string - -// Tag defines model for Tag. -type Tag struct { - Id *int64 `json:"id,omitempty"` - Name *string `json:"name,omitempty"` -} - -// User defines model for User. -type User struct { - Email *string `json:"email,omitempty"` - FirstName *string `json:"firstName,omitempty"` - Id *int64 `json:"id,omitempty"` - LastName *string `json:"lastName,omitempty"` - Password *string `json:"password,omitempty"` - Phone *string `json:"phone,omitempty"` - - // UserStatus User Status - UserStatus *int32 `json:"userStatus,omitempty"` - Username *string `json:"username,omitempty"` -} - -// UserArray defines model for UserArray. -type UserArray = []User - -// FindPetsByStatusParams defines parameters for FindPetsByStatus. -type FindPetsByStatusParams struct { - // Status Status values that need to be considered for filter - Status *FindPetsByStatusParamsStatus `form:"status,omitempty" json:"status,omitempty"` -} - -// FindPetsByStatusParamsStatus defines parameters for FindPetsByStatus. -type FindPetsByStatusParamsStatus string - -// FindPetsByTagsParams defines parameters for FindPetsByTags. -type FindPetsByTagsParams struct { - // Tags Tags to filter by - Tags *[]string `form:"tags,omitempty" json:"tags,omitempty"` -} - -// DeletePetParams defines parameters for DeletePet. -type DeletePetParams struct { - ApiKey *string `json:"api_key,omitempty"` -} - -// UpdatePetWithFormParams defines parameters for UpdatePetWithForm. -type UpdatePetWithFormParams struct { - // Name Name of pet that needs to be updated - Name *string `form:"name,omitempty" json:"name,omitempty"` - - // Status Status of pet that needs to be updated - Status *string `form:"status,omitempty" json:"status,omitempty"` -} - -// UploadFileParams defines parameters for UploadFile. -type UploadFileParams struct { - // AdditionalMetadata Additional Metadata - AdditionalMetadata *string `form:"additionalMetadata,omitempty" json:"additionalMetadata,omitempty"` -} - -// CreateUsersWithListInputJSONBody defines parameters for CreateUsersWithListInput. -type CreateUsersWithListInputJSONBody = []User - -// LoginUserParams defines parameters for LoginUser. -type LoginUserParams struct { - // Username The user name for login - Username *string `form:"username,omitempty" json:"username,omitempty"` - - // Password The password for login in clear text - Password *string `form:"password,omitempty" json:"password,omitempty"` -} - -// AddPetJSONRequestBody defines body for AddPet for application/json ContentType. -type AddPetJSONRequestBody = Pet - -// AddPetFormdataRequestBody defines body for AddPet for application/x-www-form-urlencoded ContentType. -type AddPetFormdataRequestBody = Pet - -// UpdatePetJSONRequestBody defines body for UpdatePet for application/json ContentType. -type UpdatePetJSONRequestBody = Pet - -// UpdatePetFormdataRequestBody defines body for UpdatePet for application/x-www-form-urlencoded ContentType. -type UpdatePetFormdataRequestBody = Pet - -// PlaceOrderJSONRequestBody defines body for PlaceOrder for application/json ContentType. -type PlaceOrderJSONRequestBody = Order - -// PlaceOrderFormdataRequestBody defines body for PlaceOrder for application/x-www-form-urlencoded ContentType. -type PlaceOrderFormdataRequestBody = Order - -// CreateUserJSONRequestBody defines body for CreateUser for application/json ContentType. -type CreateUserJSONRequestBody = User - -// CreateUserFormdataRequestBody defines body for CreateUser for application/x-www-form-urlencoded ContentType. -type CreateUserFormdataRequestBody = User - -// CreateUsersWithListInputJSONRequestBody defines body for CreateUsersWithListInput for application/json ContentType. -type CreateUsersWithListInputJSONRequestBody = CreateUsersWithListInputJSONBody - -// UpdateUserJSONRequestBody defines body for UpdateUser for application/json ContentType. -type UpdateUserJSONRequestBody = User - -// UpdateUserFormdataRequestBody defines body for UpdateUser for application/x-www-form-urlencoded ContentType. -type UpdateUserFormdataRequestBody = User - -// Base64 encoded, gzipped, json marshaled Swagger object -var swaggerSpec = []string{ - - "H4sIAAAAAAAC/+xb/2/jNrL/V/jUB/QVcCwn2b69Gjig2c22yF26GzS7dz0kQUFLY4ldiVRJyo4b5H8/", - "DEnJ+mrLTpy7ot0fdrUSyRnOfOYr6QcvEGkmOHCtvOmDJ+HXHJR+I0IG5sUVaPwnEFwDN480yxIWUM0E", - "939RguM7FcSQUnz6Xwlzb+p94a/X9e1X5eNaj4+j2gr3abLrAo8jLwQVSJbhCt4UeSRi9gsEmuiYasIB", - "QkW0IDMgNAwhxGcdA1FaSPAeR94nBfJMSrraaW9MQ6q28YhLIwm9ysCbetRQ6WD6kilNxJzkCqTj3gjH", - "rYNkzsJQgjKPmRQZSO2UEjBtOId7mmYJkrmiiSBniRZeSVlpyXiErChNNdTHvz3rHijB6ns98tXpa3K5", - "0lrwrhm/saw+/JtXp5Pj9si1QNxWR57TPKepkZPbK448y9iPoDLBFXTsXYTm7VzIlGpv6jGuT0/WFBnX", - "EFkVpKAUjczoFuP2xcPOfH7xRQhzmidWWW+phkjIVZtNFtbkcjyqMfz/rzoZtjSq4jwXkdpDmkHBl2Ey", - "V1qkINtM0jXABmG7AGQT3j3KBGR9KWmWQehNtcwB2WlKZoJ/BokHTaUtojnEUb7aR0iFXHDoBxl2SQiF", - "kICuQmUmRAKUe11bGbSNDPRFY+I3f3n9+mTQ5F9zynXT/F+PhpiDill27jxBOTykGo40S6HPceRGDnXf", - "ZYRFru3XkQc8T73pjZclNIDQMw5eioV5DCFhC5AQenejitIqI3ZVmzCawnEuNjU0VjHJTVguTXdvPbah", - "GIooYp2SzGKhxSeZ1G2tPqy50WJOVSYNe2sZV5/GMtDEfiOMV2LhWnl0QVlCZwm+y4CHliMlEqO5tv+k", - "0XC/8ZFG3tA9PI5MEsIQMtMbK4uq/O624SNzWQYS7XHLOyh3V3RqakeZNKBFHlLKkjpmfhEx/9a8Hwci", - "7cLOnEml37fA9jcRd4bk/cCc0E4aNAXViWeq1FLIOinv+OT01dc98OcwcCx6+eseGKNUK36nJ7r2+L/u", - "8KFjMLra3RHlJtMzVgdBLpleXSPeXWjN2M+fwXghhpzHQENDpQiR7vvaKjL2d1i5+GCM82ea69jANRFL", - "i94U01NmU9Vcx0Ky30yyil5i6sVaZ2rq+8UCp2O1pFEEcsyEL3CCX8xCm1KByMBl/TSc4ixvap7JSuSS", - "mBcYwJmG4msqQjZfmU/oSMw4GgQi5y4zL0SGhE7sK7jXKPjkXAQdKv2O8ZCIXJNUSCB0ho/Xlm1v5OXl", - "xqa+v96NwTmfiyJ9p4GumBfKUgNNv61PqNP9GDNFmCKUKAMFglXENYqNXINcgCQzqiAkwrrLDxnws6sL", - "cjqeEJVBwOauThgT8i+Rk4ByMm9v5Za7vRCqyU1rH3f/13r11ZhcWJI6ZjIkTIM0hLBYwNfWlQsJI7KE", - "LxdA1JLpIF5XOSEoFiE3UmliAi0N4v+55QWbXCxJDElGMBikJg6bebi9ZQw6BkmY/lKR2Yqk9DPjEQli", - "yiNQawpzxplhimkFyZwIWXzD/Hx8yz9iIbakqxFZMh0TzDCQX8NAkyjjJAIOkiYjQnlI4D4TCogSKRSb", - "5rAkc6A6l2CA9+Hs+nR8y2/5NQ7KFczzhCSMf1bTW35Ebj7GVYVKyIRiWsiVFTgaScR0nM/Q5xbCP6IZ", - "K58LG/qqXE6JXAaW4cr+57jzKrGdKfizRMz8lCoN0lcy8FPKuC/B0lO+yIDTjI1XNE2+8kZewgJwlZHz", - "JWcZDWIgJ+NJ02KWy+WYmq9jISPfTVX+5cXbd++v3x2djCfjWKeJic4gU/VhjuBnAXRZnW+G+OizmDbO", - "swD3ldsLOaoaijfyFiCVtbfj8WR8/BoJuQ15U+90PBmjr86ojo1rQNdloqZQuu0qzsKQUAMFtIFaTW9W", - "tXaCuTUOxexwVGlorA7bxzhaLpdHGIWOcpkARzMI//OtkbcSqIaK1BrZ3zrVMtkXvrCFt1HHyWTyX9/8", - "uc6DAJRC+y8hgCh7Nfm6jaALvqAJCwnjWe7aLS50e9Obh2bkvanGvlElSt493o08lacpxTpjMy5tonxj", - "0tI7jO55B7I/ZaFREydwz5RGl4tLzVbkImxh2w7+E95tuQHXfzSQT/pBfnFOVI6MQGjHvmqPxbDFhSZz", - "kfOw12z+gevZJATuA7Cvn8t6urHfspzHkYkOPiZZb1brAiGCDnv6IU80w6TO1bwLmuSgTPIxA4LZBwsh", - "tKlJINKUEgUZlVRDSGz+r1pmh4kqxrmSOMYtSVPQIJURQENnNdJlY9r1pQPBFQtBQmhSiDlLtEl44T5L", - "TIcToTqytcOvOcjVunRQBfk1pIqe5LRWxu9V2qNynmQfgzoCBuetJvkWw3nCyi2LUvtYVBVNz4Z/xJUy", - "GRT6+1K5m9D/0TVfNmMfV9gJ8mPySZlpxyP8+8T8fWpTXDCWOd5gFYapLTaBY9AALNzJbDUM8dou3YGE", - "nr5+qfc/wdwLZk2jgyLZKa0bxw+mCf5ouSsa7HVknZv3Ns1pgGpLR2Ut5FZLpyv+MeOTHRsOgFiRrJe2", - "HftmIlEltLXD1kLiRt1gEvO8urHSVIR2BtdRtyv5EXQuuemRMB4l4ObW9fQ96CvQb1ZGQhut/+Icy3mX", - "I0uz9svJ+/eQ5qkXSvOamCqblTd3aCJPMP+ybDnvKn1cVd9TzvyT6fg7IdMdYNQ87c/NWuHhUNVyIO+p", - "bVINYacR1dzRxg7eyqWU+5HrSBu3pX4vWENbFDj/VCvgbMqCqiEh1XRbSPHzLBE0vEjdyX8f6HDQd8zm", - "xIOdlpXwC8LrLAxNn5Em5AfQ1AmgS720HFkZuEXVQ3oHItCgj5SWQNO6gyu3M2Ocyq4T+MdD1trVWyKD", - "fekzodViTBHTzEagdYHSdncZXwDX7kB6S5RNaYZgc2VGIELbcndn/gxUV/C9KAk8UdhrBF3VDi0HHK3V", - "D8r21kY1DtXkXYjI+ga7XwbdBZPt+lRVIMq7HZ1t5auEBkWL1Axt9o/qIjfD7XWRw/TfPpQXHJ6xA9ez", - "6C5JS7HEQa26JDI8NxoWo0osOXVzp2usbptJcQ+E/AfzT6tuaRxoCkks9UJIRMsVcdZCLs6VjWgmvye3", - "+WRyGpDjyWQyJmd8pWPGI0JnYgHmJRGScMHdbJyaJO60TNvDKJBSyLZnsAl/gdMBIQ4Rb0XSSizsVnvS", - "KieTlyyPhqS89o5SI+ltlEMky2UQU1VsvJm4FjjoKY/20fRfydeoUvMf1PCYfDAHrq5NWFdv2WxV4y7P", - "b7Y4vPDqUe4czOnxSyr3EA7jORzbi9Vjm8FpC6lh0EQXlatN4c1cdAjQ3/FkZaxZcDANmhhIIqII0E+a", - "e8htlNnzQ3dB5hDBzl6Xft5Y173mLoj4pLoBYcUR1i9tN8Bd9uIPKqHn2E1/UlZC0Z0f5+6GlAOf+e8a", - "e35gRmH9fsnUhgN8u5oiSeXuu/OREVsAt/GaFBcE+6CoCkoXJrzvD8wnXeg/ZBZ0OJ33nSRWULsnSAar", - "tQ9FiYgYr1RJdfVf4lfniDafMcQWrwRDmEnv7MLdZXN5KXCnRgzSKK5ArkmgGw0SoJJouNc9BMubk7s0", - "YnbFVvsq40Ygter2QZ5i5FrwhsOfjt7dZ0yCOjqbaxuO6kuYQ17GyaePb8kyBk60+AycgJ3ldSYUGy6n", - "P468n45+xO+XLGUduA1okmDBKElsLikmiVhCWMQ959C6k5jOItdIZWPgL6Dkl8hY5wE1e7kUkbIQZby4", - "LbJSGtLNxiHszZE+6xC5LuN0dzja2bANoyLXJMilBK4b6QJRoJRFQh/bD4VQNpZMT0pRbCo/1DMYp7Bb", - "gVNxEf1J8PZW6gDkbE8czQXoLUVNd7AedQPnezCoebN67y7a7ydAV0TYE2SkeFw7NiYHlOzvI+7uVUo8", - "Ey6+B23tdbZaR8YuhHTeTXuScdq2/hDjrOPqsHb5Ry9jOq7NuXBU/5nsswUSR7CnjDBtYLkocGFvMPs0", - "Y/7i1EONuQlNwu8WINcNs1zbnyNc2d79Dr862Pw7g+rPitrnM2briNbyCrSp13fkwPGP7BdN5+0cFWpq", - "NRcKJSi3rBN77Wcrd4//DgAA///gocX++z0AAA==", -} - -// GetSwagger returns the content of the embedded swagger specification file -// or error if failed to decode -func decodeSpec() ([]byte, error) { - zipped, err := base64.StdEncoding.DecodeString(strings.Join(swaggerSpec, "")) - if err != nil { - return nil, fmt.Errorf("error base64 decoding spec: %w", err) - } - zr, err := gzip.NewReader(bytes.NewReader(zipped)) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - var buf bytes.Buffer - _, err = buf.ReadFrom(zr) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - - return buf.Bytes(), nil -} - -var rawSpec = decodeSpecCached() - -// a naive cached of a decoded swagger spec -func decodeSpecCached() func() ([]byte, error) { - data, err := decodeSpec() - return func() ([]byte, error) { - return data, err - } -} - -// Constructs a synthetic filesystem for resolving external references when loading openapi specifications. -func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { - res := make(map[string]func() ([]byte, error)) - if len(pathToFile) > 0 { - res[pathToFile] = rawSpec - } - - for rawPath, rawFunc := range externalRef0.PathToRawSpec(path.Join(path.Dir(pathToFile), "../packageB/spec.yaml")) { - if _, ok := res[rawPath]; ok { - // it is not possible to compare functions in golang, so always overwrite the old value - } - res[rawPath] = rawFunc - } - return res -} - -// GetSwagger returns the Swagger specification corresponding to the generated code -// in this file. The external references of Swagger specification are resolved. -// The logic of resolving external references is tightly connected to "import-mapping" feature. -// Externally referenced files must be embedded in the corresponding golang packages. -// Urls can be supported but this task was out of the scope. -func GetSwagger() (swagger *openapi3.T, err error) { - resolvePath := PathToRawSpec("") - - loader := openapi3.NewLoader() - loader.IsExternalRefsAllowed = true - loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() - pathToFile = path.Clean(pathToFile) - getSpec, ok := resolvePath[pathToFile] - if !ok { - err1 := fmt.Errorf("path not found: %s", pathToFile) - return nil, err1 - } - return getSpec() - } - var specData []byte - specData, err = rawSpec() - if err != nil { - return - } - swagger, err = loader.LoadFromData(specData) - if err != nil { - return - } - return -} diff --git a/internal/test/externalref/petstore/spec.yaml b/internal/test/externalref/petstore/spec.yaml deleted file mode 100644 index 2d1dcd41d5..0000000000 --- a/internal/test/externalref/petstore/spec.yaml +++ /dev/null @@ -1 +0,0 @@ -{"openapi":"3.0.2","info":{"title":"Swagger Petstore - OpenAPI 3.0","description":"This is a sample Pet Store Server based on the OpenAPI 3.0 specification. You can find out more about\nSwagger at [http://swagger.io](http://swagger.io). In the third iteration of the pet store, we've switched to the design first approach!\nYou can now help us improve the API whether it's by making changes to the definition itself or to the code.\nThat way, with time, we can improve the API in general, and expose some of the new features in OAS3.\n\nSome useful links:\n- [The Pet Store repository](https://github.com/swagger-api/swagger-petstore)\n- [The source API definition for the Pet Store](https://github.com/swagger-api/swagger-petstore/blob/master/src/main/resources/openapi.yaml)","termsOfService":"http://swagger.io/terms/","contact":{"email":"apiteam@swagger.io"},"license":{"name":"Apache 2.0","url":"http://www.apache.org/licenses/LICENSE-2.0.html"},"version":"1.0.17"},"externalDocs":{"description":"Find out more about Swagger","url":"http://swagger.io"},"servers":[{"url":"/api/v3"}],"tags":[{"name":"pet","description":"Everything about your Pets","externalDocs":{"description":"Find out more","url":"http://swagger.io"}},{"name":"store","description":"Access to Petstore orders","externalDocs":{"description":"Find out more about our store","url":"http://swagger.io"}},{"name":"user","description":"Operations about user"}],"paths":{"/pet":{"put":{"tags":["pet"],"summary":"Update an existing pet","description":"Update an existing pet by Id","operationId":"updatePet","requestBody":{"description":"Update an existent pet in the store","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Pet"}},"application/xml":{"schema":{"$ref":"#/components/schemas/Pet"}},"application/x-www-form-urlencoded":{"schema":{"$ref":"#/components/schemas/Pet"}}},"required":true},"responses":{"200":{"description":"Successful operation","content":{"application/xml":{"schema":{"$ref":"#/components/schemas/Pet"}},"application/json":{"schema":{"$ref":"#/components/schemas/Pet"}}}},"400":{"description":"Invalid ID supplied"},"404":{"description":"Pet not found"},"405":{"description":"Validation exception"}},"security":[{"petstore_auth":["write:pets","read:pets"]}]},"post":{"tags":["pet"],"summary":"Add a new pet to the store","description":"Add a new pet to the store","operationId":"addPet","requestBody":{"description":"Create a new pet in the store","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Pet"}},"application/xml":{"schema":{"$ref":"#/components/schemas/Pet"}},"application/x-www-form-urlencoded":{"schema":{"$ref":"#/components/schemas/Pet"}}},"required":true},"responses":{"200":{"description":"Successful operation","content":{"application/xml":{"schema":{"$ref":"#/components/schemas/Pet"}},"application/json":{"schema":{"$ref":"#/components/schemas/Pet"}}}},"405":{"description":"Invalid input"}},"security":[{"petstore_auth":["write:pets","read:pets"]}]}},"/pet/findByStatus":{"get":{"tags":["pet"],"summary":"Finds Pets by status","description":"Multiple status values can be provided with comma separated strings","operationId":"findPetsByStatus","parameters":[{"name":"status","in":"query","description":"Status values that need to be considered for filter","required":false,"explode":true,"schema":{"type":"string","default":"available","enum":["available","pending","sold"]}}],"responses":{"200":{"description":"successful operation","content":{"application/xml":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/Pet"}}},"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/Pet"}}}}},"400":{"description":"Invalid status value"}},"security":[{"petstore_auth":["write:pets","read:pets"]}]}},"/pet/findByTags":{"get":{"tags":["pet"],"summary":"Finds Pets by tags","description":"Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.","operationId":"findPetsByTags","parameters":[{"name":"tags","in":"query","description":"Tags to filter by","required":false,"explode":true,"schema":{"type":"array","items":{"type":"string"}}}],"responses":{"200":{"description":"successful operation","content":{"application/xml":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/Pet"}}},"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/Pet"}}}}},"400":{"description":"Invalid tag value"}},"security":[{"petstore_auth":["write:pets","read:pets"]}]}},"/pet/{petId}":{"get":{"tags":["pet"],"summary":"Find pet by ID","description":"Returns a single pet","operationId":"getPetById","parameters":[{"name":"petId","in":"path","description":"ID of pet to return","required":true,"schema":{"type":"integer","format":"int64"}}],"responses":{"200":{"description":"successful operation","content":{"application/xml":{"schema":{"$ref":"#/components/schemas/Pet"}},"application/json":{"schema":{"$ref":"#/components/schemas/Pet"}}}},"400":{"description":"Invalid ID supplied"},"404":{"description":"Pet not found"}},"security":[{"api_key":[]},{"petstore_auth":["write:pets","read:pets"]}]},"post":{"tags":["pet"],"summary":"Updates a pet in the store with form data","description":"","operationId":"updatePetWithForm","parameters":[{"name":"petId","in":"path","description":"ID of pet that needs to be updated","required":true,"schema":{"type":"integer","format":"int64"}},{"name":"name","in":"query","description":"Name of pet that needs to be updated","schema":{"type":"string"}},{"name":"status","in":"query","description":"Status of pet that needs to be updated","schema":{"type":"string"}}],"responses":{"405":{"description":"Invalid input"}},"security":[{"petstore_auth":["write:pets","read:pets"]}]},"delete":{"tags":["pet"],"summary":"Deletes a pet","description":"","operationId":"deletePet","parameters":[{"name":"api_key","in":"header","description":"","required":false,"schema":{"type":"string"}},{"name":"petId","in":"path","description":"Pet id to delete","required":true,"schema":{"type":"integer","format":"int64"}}],"responses":{"400":{"description":"Invalid pet value"}},"security":[{"petstore_auth":["write:pets","read:pets"]}]}},"/pet/{petId}/uploadImage":{"post":{"tags":["pet"],"summary":"uploads an image","description":"","operationId":"uploadFile","parameters":[{"name":"petId","in":"path","description":"ID of pet to update","required":true,"schema":{"type":"integer","format":"int64"}},{"name":"additionalMetadata","in":"query","description":"Additional Metadata","required":false,"schema":{"type":"string"}}],"requestBody":{"content":{"application/octet-stream":{"schema":{"type":"string","format":"binary"}}}},"responses":{"200":{"description":"successful operation","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ApiResponse"}}}}},"security":[{"petstore_auth":["write:pets","read:pets"]}]}},"/store/inventory":{"get":{"tags":["store"],"summary":"Returns pet inventories by status","description":"Returns a map of status codes to quantities","operationId":"getInventory","responses":{"200":{"description":"successful operation","content":{"application/json":{"schema":{"type":"object","additionalProperties":{"type":"integer","format":"int32"}}}}}},"security":[{"api_key":[]}]}},"/store/order":{"post":{"tags":["store"],"summary":"Place an order for a pet","description":"Place a new order in the store","operationId":"placeOrder","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Order"}},"application/xml":{"schema":{"$ref":"#/components/schemas/Order"}},"application/x-www-form-urlencoded":{"schema":{"$ref":"#/components/schemas/Order"}}}},"responses":{"200":{"description":"successful operation","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Order"}}}},"405":{"description":"Invalid input"}}}},"/store/order/{orderId}":{"get":{"tags":["store"],"summary":"Find purchase order by ID","description":"For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions.","operationId":"getOrderById","parameters":[{"name":"orderId","in":"path","description":"ID of order that needs to be fetched","required":true,"schema":{"type":"integer","format":"int64"}}],"responses":{"200":{"description":"successful operation","content":{"application/xml":{"schema":{"$ref":"#/components/schemas/Order"}},"application/json":{"schema":{"$ref":"#/components/schemas/Order"}}}},"400":{"description":"Invalid ID supplied"},"404":{"description":"Order not found"}}},"delete":{"tags":["store"],"summary":"Delete purchase order by ID","description":"For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors","operationId":"deleteOrder","parameters":[{"name":"orderId","in":"path","description":"ID of the order that needs to be deleted","required":true,"schema":{"type":"integer","format":"int64"}}],"responses":{"400":{"description":"Invalid ID supplied"},"404":{"description":"Order not found"}}}},"/user":{"post":{"tags":["user"],"summary":"Create user","description":"This can only be done by the logged in user.","operationId":"createUser","requestBody":{"description":"Created user object","content":{"application/json":{"schema":{"$ref":"#/components/schemas/User"}},"application/xml":{"schema":{"$ref":"#/components/schemas/User"}},"application/x-www-form-urlencoded":{"schema":{"$ref":"#/components/schemas/User"}}}},"responses":{"default":{"description":"successful operation","content":{"application/json":{"schema":{"$ref":"#/components/schemas/User"}},"application/xml":{"schema":{"$ref":"#/components/schemas/User"}}}}}}},"/user/createWithList":{"post":{"tags":["user"],"summary":"Creates list of users with given input array","description":"Creates list of users with given input array","operationId":"createUsersWithListInput","requestBody":{"content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/User"}}}}},"responses":{"200":{"description":"Successful operation","content":{"application/xml":{"schema":{"$ref":"#/components/schemas/User"}},"application/json":{"schema":{"$ref":"#/components/schemas/User"}}}},"default":{"description":"successful operation"}}}},"/user/login":{"get":{"tags":["user"],"summary":"Logs user into the system","description":"","operationId":"loginUser","parameters":[{"name":"username","in":"query","description":"The user name for login","required":false,"schema":{"type":"string"}},{"name":"password","in":"query","description":"The password for login in clear text","required":false,"schema":{"type":"string"}}],"responses":{"200":{"description":"successful operation","headers":{"X-Rate-Limit":{"description":"calls per hour allowed by the user","schema":{"type":"integer","format":"int32"}},"X-Expires-After":{"description":"date in UTC when token expires","schema":{"type":"string","format":"date-time"}}},"content":{"application/xml":{"schema":{"type":"string"}},"application/json":{"schema":{"type":"string"}}}},"400":{"description":"Invalid username/password supplied"}}}},"/user/logout":{"get":{"tags":["user"],"summary":"Logs out current logged in user session","description":"","operationId":"logoutUser","parameters":[],"responses":{"default":{"description":"successful operation"}}}},"/user/{username}":{"get":{"tags":["user"],"summary":"Get user by user name","description":"","operationId":"getUserByName","parameters":[{"name":"username","in":"path","description":"The name that needs to be fetched. Use user1 for testing. ","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"successful operation","content":{"application/xml":{"schema":{"$ref":"#/components/schemas/User"}},"application/json":{"schema":{"$ref":"#/components/schemas/User"}}}},"400":{"description":"Invalid username supplied"},"404":{"description":"User not found"}}},"put":{"tags":["user"],"summary":"Update user","description":"This can only be done by the logged in user.","operationId":"updateUser","parameters":[{"name":"username","in":"path","description":"name that need to be deleted","required":true,"schema":{"type":"string"}}],"requestBody":{"description":"Update an existent user in the store","content":{"application/json":{"schema":{"$ref":"#/components/schemas/User"}},"application/xml":{"schema":{"$ref":"#/components/schemas/User"}},"application/x-www-form-urlencoded":{"schema":{"$ref":"#/components/schemas/User"}}}},"responses":{"default":{"description":"successful operation"}}},"delete":{"tags":["user"],"summary":"Delete user","description":"This can only be done by the logged in user.","operationId":"deleteUser","parameters":[{"name":"username","in":"path","description":"The name that needs to be deleted","required":true,"schema":{"type":"string"}}],"responses":{"400":{"description":"Invalid username supplied"},"404":{"description":"User not found"}}}}},"components":{"schemas":{"Order":{"type":"object","properties":{"id":{"type":"integer","format":"int64","example":10},"petId":{"type":"integer","format":"int64","example":198772},"quantity":{"type":"integer","format":"int32","example":7},"shipDate":{"type":"string","format":"date-time"},"status":{"type":"string","description":"Order Status","example":"approved","enum":["placed","approved","delivered"]},"complete":{"type":"boolean"}},"xml":{"name":"order"}},"Customer":{"type":"object","properties":{"id":{"type":"integer","format":"int64","example":100000},"username":{"type":"string","example":"fehguy"},"address":{"type":"array","xml":{"name":"addresses","wrapped":true},"items":{"$ref":"#/components/schemas/Address"}}},"xml":{"name":"customer"}},"Address":{"type":"object","properties":{"street":{"type":"string","example":"437 Lytton"},"city":{"type":"string","example":"Palo Alto"},"state":{"type":"string","example":"CA"},"zip":{"type":"string","example":"94301"}},"xml":{"name":"address"}},"Category":{"type":"object","properties":{"id":{"type":"integer","format":"int64","example":1},"name":{"type":"string","example":"Dogs"}},"xml":{"name":"category"}},"User":{"type":"object","properties":{"id":{"type":"integer","format":"int64","example":10},"username":{"type":"string","example":"theUser"},"firstName":{"type":"string","example":"John"},"lastName":{"type":"string","example":"James"},"email":{"type":"string","example":"john@email.com"},"password":{"type":"string","example":"12345"},"phone":{"type":"string","example":"12345"},"userStatus":{"type":"integer","description":"User Status","format":"int32","example":1}},"xml":{"name":"user"}},"Tag":{"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"}},"xml":{"name":"tag"}},"Pet":{"required":["name","photoUrls"],"type":"object","properties":{"id":{"type":"integer","format":"int64","example":10},"name":{"type":"string","example":"doggie"},"category":{"$ref":"#/components/schemas/Category"},"photoUrls":{"type":"array","xml":{"wrapped":true},"items":{"type":"string","xml":{"name":"photoUrl"}}},"tags":{"type":"array","xml":{"wrapped":true},"items":{"$ref":"#/components/schemas/Tag"}},"status":{"type":"string","description":"pet status in the store","enum":["available","pending","sold"]}},"xml":{"name":"pet"}},"ApiResponse":{"type":"object","properties":{"code":{"type":"integer","format":"int32"},"type":{"type":"string"},"message":{"type":"string"}},"xml":{"name":"##default"}}},"requestBodies":{"Pet":{"description":"Pet object that needs to be added to the store","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Pet"}},"application/xml":{"schema":{"$ref":"#/components/schemas/Pet"}}}},"UserArray":{"description":"List of user object","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/User"}}}}}},"securitySchemes":{"petstore_auth":{"type":"oauth2","flows":{"implicit":{"authorizationUrl":"https://petstore3.swagger.io/oauth/authorize","scopes":{"write:pets":"modify pets in your account","read:pets":"read your pets"}}}},"api_key":{"type":"apiKey","name":"api_key","in":"header"}}}} \ No newline at end of file diff --git a/internal/test/externalref/spec.yaml b/internal/test/externalref/spec.yaml index 8f924b75c4..9f4f50d95d 100644 --- a/internal/test/externalref/spec.yaml +++ b/internal/test/externalref/spec.yaml @@ -1,15 +1,21 @@ -openapi: "3.0.0" -info: { } -paths: { } -components: - schemas: - Container: - properties: - object_a: - $ref: ./packageA/spec.yaml#/components/schemas/ObjectA - object_b: - $ref: ./packageB/spec.yaml#/components/schemas/ObjectB - object_c: - $ref: ./object_c.json - pet: - $ref: https://petstore3.swagger.io/api/v3/openapi.json#/components/schemas/Pet +openapi: "3.0.4" +info: + title: API + version: "0.0.1" +paths: + /things: + get: + operationId: listThings + responses: + "200": + description: OK + content: + application/json: + schema: + type: array + items: + type: string + "400": + $ref: "./common/spec.yaml#/components/responses/StandardError" + default: + $ref: "./common/spec.yaml#/components/responses/StandardError" diff --git a/internal/test/filter/doc.go b/internal/test/filter/doc.go deleted file mode 100644 index a9051b1015..0000000000 --- a/internal/test/filter/doc.go +++ /dev/null @@ -1,4 +0,0 @@ -package client - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --package=filtertags --generate=server -o tags/server.gen.go -include-tags included-tag1,included-tag2 server.yaml -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --package=filteroperations --generate=server -o operations/server.gen.go -include-operation-ids included-operation1,included-operation2 server.yaml diff --git a/internal/test/filter/operations/server.gen.go b/internal/test/filter/operations/server.gen.go deleted file mode 100644 index 49fc69b5e5..0000000000 --- a/internal/test/filter/operations/server.gen.go +++ /dev/null @@ -1,74 +0,0 @@ -// Package filteroperations provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package filteroperations - -import ( - "github.com/labstack/echo/v4" -) - -// ServerInterface represents all server handlers. -type ServerInterface interface { - - // (GET /included1) - IncludedOperation1(ctx echo.Context) error - - // (GET /included2) - IncludedOperation2(ctx echo.Context) error -} - -// ServerInterfaceWrapper converts echo contexts to parameters. -type ServerInterfaceWrapper struct { - Handler ServerInterface -} - -// IncludedOperation1 converts echo context to params. -func (w *ServerInterfaceWrapper) IncludedOperation1(ctx echo.Context) error { - var err error - - // Invoke the callback with all the unmarshaled arguments - err = w.Handler.IncludedOperation1(ctx) - return err -} - -// IncludedOperation2 converts echo context to params. -func (w *ServerInterfaceWrapper) IncludedOperation2(ctx echo.Context) error { - var err error - - // Invoke the callback with all the unmarshaled arguments - err = w.Handler.IncludedOperation2(ctx) - return err -} - -// This is a simple interface which specifies echo.Route addition functions which -// are present on both echo.Echo and echo.Group, since we want to allow using -// either of them for path registration -type EchoRouter interface { - CONNECT(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - DELETE(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - GET(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - HEAD(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - OPTIONS(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - PATCH(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - POST(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - PUT(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - TRACE(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route -} - -// RegisterHandlers adds each server route to the EchoRouter. -func RegisterHandlers(router EchoRouter, si ServerInterface) { - RegisterHandlersWithBaseURL(router, si, "") -} - -// Registers handlers, and prepends BaseURL to the paths, so that the paths -// can be served under a prefix. -func RegisterHandlersWithBaseURL(router EchoRouter, si ServerInterface, baseURL string) { - - wrapper := ServerInterfaceWrapper{ - Handler: si, - } - - router.GET(baseURL+"/included1", wrapper.IncludedOperation1) - router.GET(baseURL+"/included2", wrapper.IncludedOperation2) - -} diff --git a/internal/test/filter/operations/server_test.go b/internal/test/filter/operations/server_test.go deleted file mode 100644 index 2dc33642b3..0000000000 --- a/internal/test/filter/operations/server_test.go +++ /dev/null @@ -1,26 +0,0 @@ -package filteroperations - -import ( - "testing" - - "github.com/labstack/echo/v4" - "github.com/stretchr/testify/assert" -) - -type server struct{} - -func (s server) IncludedOperation1(ctx echo.Context) error { - return nil -} - -func (s server) IncludedOperation2(ctx echo.Context) error { - return nil -} - -func TestServer(t *testing.T) { - assert := assert.New(t) - - var s ServerInterface = server{} - assert.NoError(s.IncludedOperation1(nil)) - assert.NoError(s.IncludedOperation2(nil)) -} diff --git a/internal/test/filter/server.yaml b/internal/test/filter/server.yaml deleted file mode 100644 index 63e0a536ad..0000000000 --- a/internal/test/filter/server.yaml +++ /dev/null @@ -1,48 +0,0 @@ -openapi: "3.0.1" -info: - version: 1.0.0 - title: Test Server - license: - name: MIT - description: | - This tests whether filtering works correctly -paths: - /included1: - get: - operationId: included-operation1 - tags: - - included-tag1 - responses: - 200: - application/json: - schema: - $ref: '#/components/schemas/SchemaObject' - /filtered: - get: - operationId: filtered-operation - tags: - - filtered-tag - responses: - 200: - application/json: - schema: - $ref: '#/components/schemas/SchemaObject' - /included2: - get: - operationId: included-operation2 - tags: - - included-tag2 - responses: - 200: - application/json: - schema: - $ref: '#/components/schemas/SchemaObject' - -components: - schemas: - SchemaObject: - properties: - firstName: - type: string - required: - - firstName diff --git a/internal/test/filter/tags/server.gen.go b/internal/test/filter/tags/server.gen.go deleted file mode 100644 index 8137c0f39c..0000000000 --- a/internal/test/filter/tags/server.gen.go +++ /dev/null @@ -1,74 +0,0 @@ -// Package filtertags provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package filtertags - -import ( - "github.com/labstack/echo/v4" -) - -// ServerInterface represents all server handlers. -type ServerInterface interface { - - // (GET /included1) - IncludedOperation1(ctx echo.Context) error - - // (GET /included2) - IncludedOperation2(ctx echo.Context) error -} - -// ServerInterfaceWrapper converts echo contexts to parameters. -type ServerInterfaceWrapper struct { - Handler ServerInterface -} - -// IncludedOperation1 converts echo context to params. -func (w *ServerInterfaceWrapper) IncludedOperation1(ctx echo.Context) error { - var err error - - // Invoke the callback with all the unmarshaled arguments - err = w.Handler.IncludedOperation1(ctx) - return err -} - -// IncludedOperation2 converts echo context to params. -func (w *ServerInterfaceWrapper) IncludedOperation2(ctx echo.Context) error { - var err error - - // Invoke the callback with all the unmarshaled arguments - err = w.Handler.IncludedOperation2(ctx) - return err -} - -// This is a simple interface which specifies echo.Route addition functions which -// are present on both echo.Echo and echo.Group, since we want to allow using -// either of them for path registration -type EchoRouter interface { - CONNECT(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - DELETE(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - GET(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - HEAD(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - OPTIONS(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - PATCH(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - POST(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - PUT(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - TRACE(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route -} - -// RegisterHandlers adds each server route to the EchoRouter. -func RegisterHandlers(router EchoRouter, si ServerInterface) { - RegisterHandlersWithBaseURL(router, si, "") -} - -// Registers handlers, and prepends BaseURL to the paths, so that the paths -// can be served under a prefix. -func RegisterHandlersWithBaseURL(router EchoRouter, si ServerInterface, baseURL string) { - - wrapper := ServerInterfaceWrapper{ - Handler: si, - } - - router.GET(baseURL+"/included1", wrapper.IncludedOperation1) - router.GET(baseURL+"/included2", wrapper.IncludedOperation2) - -} diff --git a/internal/test/filter/tags/server_test.go b/internal/test/filter/tags/server_test.go deleted file mode 100644 index 1f466269cf..0000000000 --- a/internal/test/filter/tags/server_test.go +++ /dev/null @@ -1,26 +0,0 @@ -package filtertags - -import ( - "testing" - - "github.com/labstack/echo/v4" - "github.com/stretchr/testify/assert" -) - -type server struct{} - -func (s server) IncludedOperation1(ctx echo.Context) error { - return nil -} - -func (s server) IncludedOperation2(ctx echo.Context) error { - return nil -} - -func TestServer(t *testing.T) { - assert := assert.New(t) - - var s ServerInterface = server{} - assert.NoError(s.IncludedOperation1(nil)) - assert.NoError(s.IncludedOperation2(nil)) -} diff --git a/internal/test/go.mod b/internal/test/go.mod index 6f70f67ca3..29cc0cffe4 100644 --- a/internal/test/go.mod +++ b/internal/test/go.mod @@ -5,110 +5,52 @@ go 1.24.3 replace github.com/oapi-codegen/oapi-codegen/v2 => ../../ require ( - github.com/getkin/kin-openapi v0.133.0 - github.com/gin-gonic/gin v1.11.0 github.com/go-chi/chi/v5 v5.2.5 - github.com/gofiber/fiber/v2 v2.52.12 github.com/google/uuid v1.6.0 - github.com/gorilla/mux v1.8.1 - github.com/kataras/iris/v12 v12.2.11 github.com/labstack/echo/v4 v4.15.1 github.com/oapi-codegen/nullable v1.1.0 github.com/oapi-codegen/oapi-codegen/v2 v2.0.0-00010101000000-000000000000 github.com/oapi-codegen/runtime v1.2.0 - github.com/oapi-codegen/testutil v1.1.0 github.com/stretchr/testify v1.11.1 - gopkg.in/yaml.v2 v2.4.0 ) require ( - github.com/BurntSushi/toml v1.3.2 // indirect - github.com/CloudyKit/fastprinter v0.0.0-20200109182630-33d98a066a53 // indirect - github.com/CloudyKit/jet/v6 v6.2.0 // indirect - github.com/Joker/jade v1.1.3 // indirect - github.com/Shopify/goreferrer v0.0.0-20220729165902-8cddb4f5de06 // indirect - github.com/andybalholm/brotli v1.1.0 // indirect github.com/apapsch/go-jsonmerge/v2 v2.0.0 // indirect - github.com/aymerick/douceur v0.2.0 // indirect - github.com/bytedance/sonic v1.14.0 // indirect - github.com/bytedance/sonic/loader v0.3.0 // indirect - github.com/cloudwego/base64x v0.1.6 // indirect github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect github.com/dprotaso/go-yit v0.0.0-20220510233725-9ba8df137936 // indirect - github.com/fatih/structs v1.1.0 // indirect - github.com/flosch/pongo2/v4 v4.0.2 // indirect - github.com/gabriel-vasile/mimetype v1.4.8 // indirect - github.com/gin-contrib/sse v1.1.0 // indirect + github.com/fsnotify/fsnotify v1.7.0 // indirect + github.com/getkin/kin-openapi v0.133.0 // indirect github.com/go-openapi/jsonpointer v0.22.4 // indirect github.com/go-openapi/swag/jsonname v0.25.4 // indirect - github.com/go-playground/locales v0.14.1 // indirect - github.com/go-playground/universal-translator v0.18.1 // indirect - github.com/go-playground/validator/v10 v10.27.0 // indirect - github.com/goccy/go-json v0.10.2 // indirect - github.com/goccy/go-yaml v1.18.0 // indirect - github.com/golang/snappy v0.0.4 // indirect - github.com/gomarkdown/markdown v0.0.0-20240328165702-4d01890c35c0 // indirect - github.com/gorilla/css v1.0.0 // indirect - github.com/iris-contrib/schema v0.0.6 // indirect + github.com/google/go-cmp v0.7.0 // indirect github.com/josharian/intern v1.0.0 // indirect - github.com/json-iterator/go v1.1.12 // indirect - github.com/kataras/blocks v0.0.8 // indirect - github.com/kataras/golog v0.1.11 // indirect - github.com/kataras/pio v0.0.13 // indirect - github.com/kataras/sitemap v0.0.6 // indirect - github.com/kataras/tunnel v0.0.4 // indirect - github.com/klauspost/compress v1.17.9 // indirect - github.com/klauspost/cpuid/v2 v2.3.0 // indirect github.com/labstack/gommon v0.4.2 // indirect - github.com/leodido/go-urn v1.4.0 // indirect - github.com/mailgun/raymond/v2 v2.0.48 // indirect github.com/mailru/easyjson v0.9.1 // indirect github.com/mattn/go-colorable v0.1.14 // indirect github.com/mattn/go-isatty v0.0.20 // indirect - github.com/mattn/go-runewidth v0.0.16 // indirect - github.com/microcosm-cc/bluemonday v1.0.26 // indirect - github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect - github.com/modern-go/reflect2 v1.0.2 // indirect github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 // indirect + github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e // indirect + github.com/nxadm/tail v1.4.11 // indirect github.com/oasdiff/yaml v0.0.0-20250309154309-f31be36b4037 // indirect github.com/oasdiff/yaml3 v0.0.0-20250309153720-d2182401db90 // indirect - github.com/pelletier/go-toml/v2 v2.2.4 // indirect github.com/perimeterx/marshmallow v1.1.5 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect - github.com/quic-go/qpack v0.5.1 // indirect - github.com/quic-go/quic-go v0.54.0 // indirect - github.com/rivo/uniseg v0.2.0 // indirect - github.com/russross/blackfriday/v2 v2.1.0 // indirect - github.com/schollz/closestmatch v2.1.0+incompatible // indirect - github.com/sirupsen/logrus v1.9.1 // indirect github.com/speakeasy-api/jsonpath v0.6.0 // indirect github.com/speakeasy-api/openapi-overlay v0.10.3 // indirect github.com/stretchr/objx v0.5.2 // indirect - github.com/tdewolff/minify/v2 v2.20.19 // indirect - github.com/tdewolff/parse/v2 v2.7.12 // indirect - github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/ugorji/go/codec v1.3.0 // indirect github.com/valyala/bytebufferpool v1.0.0 // indirect - github.com/valyala/fasthttp v1.51.0 // indirect github.com/valyala/fasttemplate v1.2.2 // indirect - github.com/valyala/tcplisten v1.0.0 // indirect - github.com/vmihailenco/msgpack/v5 v5.4.1 // indirect - github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect github.com/vmware-labs/yaml-jsonpath v0.3.2 // indirect github.com/woodsbury/decimal128 v1.4.0 // indirect - github.com/yosssi/ace v0.0.5 // indirect - go.uber.org/mock v0.5.0 // indirect - golang.org/x/arch v0.20.0 // indirect golang.org/x/crypto v0.48.0 // indirect - golang.org/x/exp v0.0.0-20240404231335-c0f41cb1a7a0 // indirect golang.org/x/mod v0.33.0 // indirect golang.org/x/net v0.50.0 // indirect golang.org/x/sync v0.19.0 // indirect golang.org/x/sys v0.41.0 // indirect golang.org/x/text v0.34.0 // indirect - golang.org/x/time v0.14.0 // indirect golang.org/x/tools v0.42.0 // indirect - google.golang.org/protobuf v1.36.9 // indirect - gopkg.in/ini.v1 v1.67.0 // indirect + gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b // indirect + gopkg.in/yaml.v2 v2.4.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/internal/test/go.sum b/internal/test/go.sum index d4d3ba66ee..cb259807d5 100644 --- a/internal/test/go.sum +++ b/internal/test/go.sum @@ -1,34 +1,10 @@ -github.com/BurntSushi/toml v1.3.2 h1:o7IhLm0Msx3BaB+n3Ag7L8EVlByGnpq14C4YWiu/gL8= -github.com/BurntSushi/toml v1.3.2/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= -github.com/CloudyKit/fastprinter v0.0.0-20200109182630-33d98a066a53 h1:sR+/8Yb4slttB4vD+b9btVEnWgL3Q00OBTzVT8B9C0c= -github.com/CloudyKit/fastprinter v0.0.0-20200109182630-33d98a066a53/go.mod h1:+3IMCy2vIlbG1XG/0ggNQv0SvxCAIpPM5b1nCz56Xno= -github.com/CloudyKit/jet/v6 v6.2.0 h1:EpcZ6SR9n28BUGtNJSvlBqf90IpjeFr36Tizxhn/oME= -github.com/CloudyKit/jet/v6 v6.2.0/go.mod h1:d3ypHeIRNo2+XyqnGA8s+aphtcVpjP5hPwP/Lzo7Ro4= -github.com/Joker/hpp v1.0.0 h1:65+iuJYdRXv/XyN62C1uEmmOx3432rNG/rKlX6V7Kkc= -github.com/Joker/hpp v1.0.0/go.mod h1:8x5n+M1Hp5hC0g8okX3sR3vFQwynaX/UgSOM9MeBKzY= -github.com/Joker/jade v1.1.3 h1:Qbeh12Vq6BxURXT1qZBRHsDxeURB8ztcL6f3EXSGeHk= -github.com/Joker/jade v1.1.3/go.mod h1:T+2WLyt7VH6Lp0TRxQrUYEs64nRc83wkMQrfeIQKduM= github.com/RaveNoX/go-jsoncommentstrip v1.0.0/go.mod h1:78ihd09MekBnJnxpICcwzCMzGrKSKYe4AqU6PDYYpjk= -github.com/Shopify/goreferrer v0.0.0-20220729165902-8cddb4f5de06 h1:KkH3I3sJuOLP3TjA/dfr4NAY8bghDwnXiU7cTKxQqo0= -github.com/Shopify/goreferrer v0.0.0-20220729165902-8cddb4f5de06/go.mod h1:7erjKLwalezA0k99cWs5L11HWOAPNjdUZ6RxH1BXbbM= -github.com/ajg/form v1.5.1 h1:t9c7v8JUKu/XxOGBU0yjNpaMloxGEJhUkqFRq0ibGeU= -github.com/ajg/form v1.5.1/go.mod h1:uL1WgH+h2mgNtvBq0339dVnzXdBETtL2LeUXaIv25UY= -github.com/andybalholm/brotli v1.1.0 h1:eLKJA0d02Lf0mVpIDgYnqXcUn0GqVmEFny3VuID1U3M= -github.com/andybalholm/brotli v1.1.0/go.mod h1:sms7XGricyQI9K10gOSf56VKKWS4oLer58Q+mhRPtnY= github.com/apapsch/go-jsonmerge/v2 v2.0.0 h1:axGnT1gRIfimI7gJifB699GoE/oq+F2MU7Dml6nw9rQ= github.com/apapsch/go-jsonmerge/v2 v2.0.0/go.mod h1:lvDnEdqiQrp0O42VQGgmlKpxL1AP2+08jFMw88y4klk= -github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk= -github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4= github.com/bmatcuk/doublestar v1.1.1/go.mod h1:UD6OnuiIn0yFxxA2le/rnRU1G4RaI4UvFv1sNto9p6w= -github.com/bytedance/sonic v1.14.0 h1:/OfKt8HFw0kh2rj8N0F6C/qPGRESq0BbaNZgcNXXzQQ= -github.com/bytedance/sonic v1.14.0/go.mod h1:WoEbx8WTcFJfzCe0hbmyTGrfjt8PzNEBdxlNUO24NhA= -github.com/bytedance/sonic/loader v0.3.0 h1:dskwH8edlzNMctoruo8FPTJDF3vLtDT0sXZwvZJyqeA= -github.com/bytedance/sonic/loader v0.3.0/go.mod h1:N8A3vUdtUebEY2/VQC0MyhYeKUFosQU6FxH2JmUe6VI= github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= -github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M= -github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= @@ -36,24 +12,13 @@ github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8Yc github.com/dprotaso/go-yit v0.0.0-20191028211022-135eb7262960/go.mod h1:9HQzr9D/0PGwMEbC3d5AB7oi67+h4TsQqItC1GVYG58= github.com/dprotaso/go-yit v0.0.0-20220510233725-9ba8df137936 h1:PRxIJD8XjimM5aTknUK9w6DHLDox2r2M3DI4i2pnd3w= github.com/dprotaso/go-yit v0.0.0-20220510233725-9ba8df137936/go.mod h1:ttYvX5qlB+mlV1okblJqcSMtR4c52UKxDiX9GRBS8+Q= -github.com/fatih/color v1.15.0 h1:kOqh6YHBtK8aywxGerMG2Eq3H6Qgoqeo13Bk2Mv/nBs= -github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBDUSsw= -github.com/fatih/structs v1.1.0 h1:Q7juDM0QtcnhCpeyLGQKyg4TOIghuNXrkL32pHAUMxo= -github.com/fatih/structs v1.1.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M= -github.com/flosch/pongo2/v4 v4.0.2 h1:gv+5Pe3vaSVmiJvh/BZa82b7/00YUGm0PIyVVLop0Hw= -github.com/flosch/pongo2/v4 v4.0.2/go.mod h1:B5ObFANs/36VwxxlgKpdchIJHMvHB562PW+BWPhwZD8= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= +github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA= github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM= -github.com/gabriel-vasile/mimetype v1.4.8 h1:FfZ3gj38NjllZIeJAmMhr+qKL8Wu+nOoI3GqacKw1NM= -github.com/gabriel-vasile/mimetype v1.4.8/go.mod h1:ByKUIKGjh1ODkGM1asKUbQZOLGrPjydw3hYPU2YU9t8= github.com/getkin/kin-openapi v0.133.0 h1:pJdmNohVIJ97r4AUFtEXRXwESr8b0bD721u/Tz6k8PQ= github.com/getkin/kin-openapi v0.133.0/go.mod h1:boAciF6cXk5FhPqe/NQeBTeenbjqU4LhWBf09ILVvWE= -github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w= -github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM= -github.com/gin-gonic/gin v1.11.0 h1:OW/6PLjyusp2PPXtyxKHU0RbX6I/l28FTdDlae5ueWk= -github.com/gin-gonic/gin v1.11.0/go.mod h1:+iq/FyxlGzII0KHiBGjuNn4UNENUlKbGlNmc+W50Dls= github.com/go-chi/chi/v5 v5.2.5 h1:Eg4myHZBjyvJmAFjFvWgrqDTXFyOzjj7YIm3L3mu6Ug= github.com/go-chi/chi/v5 v5.2.5/go.mod h1:X7Gx4mteadT3eDOMTsXzmI4/rwUpOwBHLpAfupzFJP0= github.com/go-openapi/jsonpointer v0.22.4 h1:dZtK82WlNpVLDW2jlA1YCiVJFVqkED1MegOUy9kR5T4= @@ -62,25 +27,9 @@ github.com/go-openapi/swag/jsonname v0.25.4 h1:bZH0+MsS03MbnwBXYhuTttMOqk+5KcQ98 github.com/go-openapi/swag/jsonname v0.25.4/go.mod h1:GPVEk9CWVhNvWhZgrnvRA6utbAltopbKwDu8mXNUMag= github.com/go-openapi/testify/v2 v2.0.2 h1:X999g3jeLcoY8qctY/c/Z8iBHTbwLz7R2WXd6Ub6wls= github.com/go-openapi/testify/v2 v2.0.2/go.mod h1:HCPmvFFnheKK2BuwSA0TbbdxJ3I16pjwMkYkP4Ywn54= -github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= -github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= -github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= -github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= -github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= -github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= -github.com/go-playground/validator/v10 v10.27.0 h1:w8+XrWVMhGkxOaaowyKH35gFydVHOvC0/uWoy2Fzwn4= -github.com/go-playground/validator/v10 v10.27.0/go.mod h1:I5QpIEbmr8On7W0TktmJAumgzX4CA1XNl4ZmDuVHKKo= github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE= github.com/go-test/deep v1.0.8 h1:TDsG77qcSprGbC6vTN8OuXp5g+J+b5Pcguhf7Zt61VM= github.com/go-test/deep v1.0.8/go.mod h1:5C2ZWiW0ErCdrYzpqxLbTX7MG14M9iiw8DgHncVwcsE= -github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y= -github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8= -github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU= -github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= -github.com/goccy/go-yaml v1.18.0 h1:8W7wMFS12Pcas7KU+VVkaiCng+kG8QiFeFwzFb+rwuw= -github.com/goccy/go-yaml v1.18.0/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA= -github.com/gofiber/fiber/v2 v2.52.12 h1:0LdToKclcPOj8PktUdIKo9BUohjjwfnQl42Dhw8/WUw= -github.com/gofiber/fiber/v2 v2.52.12/go.mod h1:YEcBbO/FB+5M1IZNBP9FO3J9281zgPAreiI1oqg8nDw= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= @@ -90,57 +39,20 @@ github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvq github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= -github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM= -github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= -github.com/gomarkdown/markdown v0.0.0-20240328165702-4d01890c35c0 h1:4gjrh/PN2MuWCCElk8/I4OCKRKWCCo2zEct3VKCbibU= -github.com/gomarkdown/markdown v0.0.0-20240328165702-4d01890c35c0/go.mod h1:JDGcbDT52eL4fju3sZ4TeHGsQwhG9nbDV21aMyhwPoA= github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= -github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8= -github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU= -github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/gorilla/css v1.0.0 h1:BQqNyPTi50JCFMTw/b67hByjMVXZRwGha6wxVGkeihY= -github.com/gorilla/css v1.0.0/go.mod h1:Dn721qIggHpt4+EFCcTLTU/vk5ySda2ReITrtgBl60c= -github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY= -github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ= -github.com/gorilla/websocket v1.5.1 h1:gmztn0JnHVt9JZquRuzLw3g4wouNVzKL15iLr/zn/QY= -github.com/gorilla/websocket v1.5.1/go.mod h1:x3kM2JMyaluk02fnUJpQuwD2dCS5NDG2ZHL0uE0tcaY= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= -github.com/imkira/go-interpol v1.1.0 h1:KIiKr0VSG2CUW1hl1jpiyuzuJeKUUpC8iM1AIE7N1Vk= -github.com/imkira/go-interpol v1.1.0/go.mod h1:z0h2/2T3XF8kyEPpRgJ3kmNv+C43p+I/CoI+jC3w2iA= -github.com/iris-contrib/httpexpect/v2 v2.15.2 h1:T9THsdP1woyAqKHwjkEsbCnMefsAFvk8iJJKokcJ3Go= -github.com/iris-contrib/httpexpect/v2 v2.15.2/go.mod h1:JLDgIqnFy5loDSUv1OA2j0mb6p/rDhiCqigP22Uq9xE= -github.com/iris-contrib/schema v0.0.6 h1:CPSBLyx2e91H2yJzPuhGuifVRnZBBJ3pCOMbOvPZaTw= -github.com/iris-contrib/schema v0.0.6/go.mod h1:iYszG0IOsuIsfzjymw1kMzTL8YQcCWlm65f3wX8J5iA= github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= -github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= -github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/juju/gnuflag v0.0.0-20171113085948-2ce1bb71843d/go.mod h1:2PavIy+JPciBPrBUjwbNvtwB6RQlve+hkpll6QSNmOE= -github.com/kataras/blocks v0.0.8 h1:MrpVhoFTCR2v1iOOfGng5VJSILKeZZI+7NGfxEh3SUM= -github.com/kataras/blocks v0.0.8/go.mod h1:9Jm5zx6BB+06NwA+OhTbHW1xkMOYxahnqTN5DveZ2Yg= -github.com/kataras/golog v0.1.11 h1:dGkcCVsIpqiAMWTlebn/ZULHxFvfG4K43LF1cNWSh20= -github.com/kataras/golog v0.1.11/go.mod h1:mAkt1vbPowFUuUGvexyQ5NFW6djEgGyxQBIARJ0AH4A= -github.com/kataras/iris/v12 v12.2.11 h1:sGgo43rMPfzDft8rjVhPs6L3qDJy3TbBrMD/zGL1pzk= -github.com/kataras/iris/v12 v12.2.11/go.mod h1:uMAeX8OqG9vqdhyrIPv8Lajo/wXTtAF43wchP9WHt2w= -github.com/kataras/pio v0.0.13 h1:x0rXVX0fviDTXOOLOmr4MUxOabu1InVSTu5itF8CXCM= -github.com/kataras/pio v0.0.13/go.mod h1:k3HNuSw+eJ8Pm2lA4lRhg3DiCjVgHlP8hmXApSej3oM= -github.com/kataras/sitemap v0.0.6 h1:w71CRMMKYMJh6LR2wTgnk5hSgjVNB9KL60n5e2KHvLY= -github.com/kataras/sitemap v0.0.6/go.mod h1:dW4dOCNs896OR1HmG+dMLdT7JjDk7mYBzoIRwuj5jA4= -github.com/kataras/tunnel v0.0.4 h1:sCAqWuJV7nPzGrlb0os3j49lk2JhILT0rID38NHNLpA= -github.com/kataras/tunnel v0.0.4/go.mod h1:9FkU4LaeifdMWqZu7o20ojmW4B7hdhv2CMLwfnHGpYw= -github.com/klauspost/compress v1.17.9 h1:6KIumPrER1LHsvBVuDa0r5xaG0Es51mhhB9BQB2qeMA= -github.com/klauspost/compress v1.17.9/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw= -github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y= -github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= @@ -149,27 +61,12 @@ github.com/labstack/echo/v4 v4.15.1 h1:S9keusg26gZpjMmPqB5hOEvNKnmd1lNmcHrbbH2ln github.com/labstack/echo/v4 v4.15.1/go.mod h1:xmw1clThob0BSVRX1CRQkGQ/vjwcpOMjQZSZa9fKA/c= github.com/labstack/gommon v0.4.2 h1:F8qTUNXgG1+6WQmqoUWnz8WiEU60mXVVw0P4ht1WRA0= github.com/labstack/gommon v0.4.2/go.mod h1:QlUFxVM+SNXhDL/Z7YhocGIBYOiwB0mXm1+1bAPHPyU= -github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= -github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= -github.com/mailgun/raymond/v2 v2.0.48 h1:5dmlB680ZkFG2RN/0lvTAghrSxIESeu9/2aeDqACtjw= -github.com/mailgun/raymond/v2 v2.0.48/go.mod h1:lsgvL50kgt1ylcFJYZiULi5fjPBkkhNfj4KA0W54Z18= github.com/mailru/easyjson v0.9.1 h1:LbtsOm5WAswyWbvTEOqhypdPeZzHavpZx96/n553mR8= github.com/mailru/easyjson v0.9.1/go.mod h1:1+xMtQp2MRNVL/V1bOzuP3aP8VNwRW55fQUto+XFtTU= github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE= github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= -github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc= -github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= -github.com/microcosm-cc/bluemonday v1.0.26 h1:xbqSvqzQMeEHCqMi64VAs4d8uy6Mequs3rQ0k/Khz58= -github.com/microcosm-cc/bluemonday v1.0.26/go.mod h1:JyzOCs9gkyQyjs+6h10UEVSe02CGwkhd72Xdqh78TWs= -github.com/mitchellh/go-wordwrap v1.0.1 h1:TLuKupo69TCn6TQSyGxwI1EblZZEsQ0vMlAFQflz0v0= -github.com/mitchellh/go-wordwrap v1.0.1/go.mod h1:R62XHJLzvMFRBbcrT7m7WgmE1eOyTSsCt+hzestvNj0= -github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= -github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= -github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= -github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= -github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 h1:RWengNIwukTxcDr9M+97sNutRR1RKhG96O6jWumTTnw= github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826/go.mod h1:TaXosZuwdSHYgviHp1DAtfrULt5eUgsSMsZf+YrPgl8= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs= @@ -182,8 +79,6 @@ github.com/oapi-codegen/nullable v1.1.0 h1:eAh8JVc5430VtYVnq00Hrbpag9PFRGWLjxR1/ github.com/oapi-codegen/nullable v1.1.0/go.mod h1:KUZ3vUzkmEKY90ksAmit2+5juDIhIZhfDl+0PwOQlFY= github.com/oapi-codegen/runtime v1.2.0 h1:RvKc1CVS1QeKSNzO97FBQbSMZyQ8s6rZd+LpmzwHMP4= github.com/oapi-codegen/runtime v1.2.0/go.mod h1:Y7ZhmmlE8ikZOmuHRRndiIm7nf3xcVv+YMweKgG1DT0= -github.com/oapi-codegen/testutil v1.1.0 h1:EufqpNg43acR3qzr3ObhXmWg3Sl2kwtRnUN5GYY4d5g= -github.com/oapi-codegen/testutil v1.1.0/go.mod h1:ttCaYbHvJtHuiyeBF0tPIX+4uhEPTeizXKx28okijLw= github.com/oasdiff/yaml v0.0.0-20250309154309-f31be36b4037 h1:G7ERwszslrBzRxj//JalHPu/3yz+De2J+4aLtSRlHiY= github.com/oasdiff/yaml v0.0.0-20250309154309-f31be36b4037/go.mod h1:2bpvgLBZEtENV5scfDFEtB/5+1M4hkQhDQrccEJ/qGw= github.com/oasdiff/yaml3 v0.0.0-20250309153720-d2182401db90 h1:bQx3WeLcUWy+RletIKwUIt4x3t8n2SxavmoclizMb8c= @@ -200,123 +95,57 @@ github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1y github.com/onsi/gomega v1.17.0/go.mod h1:HnhC7FXeEQY45zxNK3PPoIUhzk/80Xly9PcubAlGdZY= github.com/onsi/gomega v1.19.0 h1:4ieX6qQjPP/BfC3mpsAtIGGlxTWPeA3Inl/7DtXw1tw= github.com/onsi/gomega v1.19.0/go.mod h1:LY+I3pBVzYsTBU1AnDwOSxaYi9WoWiqgwooUqq9yPro= -github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= -github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= github.com/perimeterx/marshmallow v1.1.5 h1:a2LALqQ1BlHM8PZblsDdidgv1mWi1DgC2UmX50IvK2s= github.com/perimeterx/marshmallow v1.1.5/go.mod h1:dsXbUu8CRzfYP5a87xpp0xq9S3u0Vchtcl8we9tYaXw= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/quic-go/qpack v0.5.1 h1:giqksBPnT/HDtZ6VhtFKgoLOWmlyo9Ei6u9PqzIMbhI= -github.com/quic-go/qpack v0.5.1/go.mod h1:+PC4XFrEskIVkcLzpEkbLqq1uCoxPhQuvK5rH1ZgaEg= -github.com/quic-go/quic-go v0.54.0 h1:6s1YB9QotYI6Ospeiguknbp2Znb/jZYjZLRXn9kMQBg= -github.com/quic-go/quic-go v0.54.0/go.mod h1:e68ZEaCdyviluZmy44P6Iey98v/Wfz6HCjQEm+l8zTY= -github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY= -github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= -github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= -github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= -github.com/sanity-io/litter v1.5.5 h1:iE+sBxPBzoK6uaEP5Lt3fHNgpKcHXc/A2HGETy0uJQo= -github.com/sanity-io/litter v1.5.5/go.mod h1:9gzJgR2i4ZpjZHsKvUXIRQVk7P+yM3e+jAF7bU2UI5U= -github.com/schollz/closestmatch v2.1.0+incompatible h1:Uel2GXEpJqOWBrlyI+oY9LTiyyjYS17cCYRqP13/SHk= -github.com/schollz/closestmatch v2.1.0+incompatible/go.mod h1:RtP1ddjLong6gTkbtmuhtR2uUrrJOpYzYRvbcPAid+g= github.com/sergi/go-diff v1.1.0 h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0= github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= -github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= -github.com/sirupsen/logrus v1.9.1 h1:Ou41VVR3nMWWmTiEUnj0OlsgOSCUFgsPAOl6jRIcVtQ= -github.com/sirupsen/logrus v1.9.1/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= github.com/speakeasy-api/jsonpath v0.6.0 h1:IhtFOV9EbXplhyRqsVhHoBmmYjblIRh5D1/g8DHMXJ8= github.com/speakeasy-api/jsonpath v0.6.0/go.mod h1:ymb2iSkyOycmzKwbEAYPJV/yi2rSmvBCLZJcyD+VVWw= github.com/speakeasy-api/openapi-overlay v0.10.3 h1:70een4vwHyslIp796vM+ox6VISClhtXsCjrQNhxwvWs= github.com/speakeasy-api/openapi-overlay v0.10.3/go.mod h1:RJjV0jbUHqXLS0/Mxv5XE7LAnJHqHw+01RDdpoGqiyY= github.com/spkg/bom v0.0.0-20160624110644-59b7046e48ad/go.mod h1:qLr4V1qq6nMqFKkMo8ZTx3f+BZEkzsRUY10Xsm2mwU0= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= -github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= -github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= -github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= -github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= -github.com/tdewolff/minify/v2 v2.20.19 h1:tX0SR0LUrIqGoLjXnkIzRSIbKJ7PaNnSENLD4CyH6Xo= -github.com/tdewolff/minify/v2 v2.20.19/go.mod h1:ulkFoeAVWMLEyjuDz1ZIWOA31g5aWOawCFRp9R/MudM= -github.com/tdewolff/parse/v2 v2.7.12 h1:tgavkHc2ZDEQVKy1oWxwIyh5bP4F5fEh/JmBwPP/3LQ= -github.com/tdewolff/parse/v2 v2.7.12/go.mod h1:3FbJWZp3XT9OWVN3Hmfp0p/a08v4h8J9W1aghka0soA= -github.com/tdewolff/test v1.0.11-0.20231101010635-f1265d231d52/go.mod h1:6DAvZliBAAnD7rhVgwaM7DE5/d9NMOAJ09SqYqeK4QE= -github.com/tdewolff/test v1.0.11-0.20240106005702-7de5f7df4739 h1:IkjBCtQOOjIn03u/dMQK9g+Iw9ewps4mCl1nB8Sscbo= -github.com/tdewolff/test v1.0.11-0.20240106005702-7de5f7df4739/go.mod h1:XPuWBzvdUzhCuxWO1ojpXsyzsA5bFoS3tO/Q3kFuTG8= -github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= -github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= github.com/ugorji/go/codec v1.3.0 h1:Qd2W2sQawAfG8XSvzwhBeoGq71zXOC/Q1E9y/wUcsUA= github.com/ugorji/go/codec v1.3.0/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4= github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= -github.com/valyala/fasthttp v1.51.0 h1:8b30A5JlZ6C7AS81RsWjYMQmrZG6feChmgAolCl1SqA= -github.com/valyala/fasthttp v1.51.0/go.mod h1:oI2XroL+lI7vdXyYoQk03bXBThfFl2cVdIA3Xl7cH8g= github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo= github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ= -github.com/valyala/tcplisten v1.0.0 h1:rBHj/Xf+E1tRGZyWIWwJDiRY0zc1Js+CV5DqwacVSA8= -github.com/valyala/tcplisten v1.0.0/go.mod h1:T0xQ8SeCZGxckz9qRXTfG43PvQ/mcWh7FwZEA7Ioqkc= -github.com/vmihailenco/msgpack/v5 v5.4.1 h1:cQriyiUvjTwOHg8QZaPihLWeRAAVoCpE00IUPn0Bjt8= -github.com/vmihailenco/msgpack/v5 v5.4.1/go.mod h1:GaZTsDaehaPpQVyxrf5mtQlH+pc21PIudVV/E3rRQok= -github.com/vmihailenco/tagparser/v2 v2.0.0 h1:y09buUbR+b5aycVFQs/g70pqKVZNBmxwAhO7/IwNM9g= -github.com/vmihailenco/tagparser/v2 v2.0.0/go.mod h1:Wri+At7QHww0WTrCBeu4J6bNtoV6mEfg5OIWRZA9qds= github.com/vmware-labs/yaml-jsonpath v0.3.2 h1:/5QKeCBGdsInyDCyVNLbXyilb61MXGi9NP674f9Hobk= github.com/vmware-labs/yaml-jsonpath v0.3.2/go.mod h1:U6whw1z03QyqgWdgXxvVnQ90zN1BWz5V+51Ewf8k+rQ= github.com/woodsbury/decimal128 v1.4.0 h1:xJATj7lLu4f2oObouMt2tgGiElE5gO6mSWUjQsBgUlc= github.com/woodsbury/decimal128 v1.4.0/go.mod h1:BP46FUrVjVhdTbKT+XuQh2xfQaGki9LMIRJSFuh6THU= -github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f h1:J9EGpcZtP0E/raorCMxlFGSTBrsSlaDGf3jU/qvAE2c= -github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= -github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHovont7NscjpAxXsDA8S8BMYve8Y5+7cuRE7R0= -github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ= -github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17UxZ74= -github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y= -github.com/yalp/jsonpath v0.0.0-20180802001716-5cc68e5049a0 h1:6fRhSjgLCkTD3JnJxvaJ4Sj+TYblw757bqYgZaOq5ZY= -github.com/yalp/jsonpath v0.0.0-20180802001716-5cc68e5049a0/go.mod h1:/LWChgwKmvncFJFHJ7Gvn9wZArjbV5/FppcK2fKk/tI= -github.com/yosssi/ace v0.0.5 h1:tUkIP/BLdKqrlrPwcmH0shwEEhTRHoGnc1wFIWmaBUA= -github.com/yosssi/ace v0.0.5/go.mod h1:ALfIzm2vT7t5ZE7uoIZqF3TQ7SAOyupFZnkrF5id+K0= -github.com/yudai/gojsondiff v1.0.0 h1:27cbfqXLVEJ1o8I6v3y9lg8Ydm53EKqHXAOMxEGlCOA= -github.com/yudai/gojsondiff v1.0.0/go.mod h1:AY32+k2cwILAkW1fbgxQ5mUmMiZFgLIV+FBNExI05xg= -github.com/yudai/golcs v0.0.0-20170316035057-ecda9a501e82 h1:BHyfKlQyqbsFN5p3IfnEUduWvb9is428/nNb5L3U01M= -github.com/yudai/golcs v0.0.0-20170316035057-ecda9a501e82/go.mod h1:lgjkn3NuSvDfVJdfcVVdX+jpBxNmX4rDAzaS45IcYoM= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/yuin/goldmark v1.4.1/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= -go.uber.org/mock v0.5.0 h1:KAMbZvZPyBPWgD14IrIQ38QCyjwpvVVV6K/bHl1IwQU= -go.uber.org/mock v0.5.0/go.mod h1:ge71pBPLYDk7QIi1LupWxdAykm7KIEFchiOqd6z7qMM= -golang.org/x/arch v0.20.0 h1:dx1zTU0MAE98U+TQ8BLl7XsJbgze2WnNKF/8tGp/Q6c= -golang.org/x/arch v0.20.0/go.mod h1:bdwinDaKcfZUGpH09BB7ZmOfhalA8lQdzl62l8gGWsk= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts= golang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos= -golang.org/x/exp v0.0.0-20240404231335-c0f41cb1a7a0 h1:985EYyeCOxTpcgOTJpflJUwOeEz0CQOdPt73OzpE9F8= -golang.org/x/exp v0.0.0-20240404231335-c0f41cb1a7a0/go.mod h1:/lliqkxwWAhPjf5oSOIJup2XcqJaw8RGS6k3TGEc7GI= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.5.1/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro= golang.org/x/mod v0.33.0 h1:tHFzIWbBifEmbwtGz65eaWyGiGZatSrT9prnU8DbVL8= golang.org/x/mod v0.33.0/go.mod h1:swjeQEj+6r7fODbD2cqrnje9PnziFuw4bmLbBZFrQ5w= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20190327091125-710a502c58a2/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT/9KSuxbyM7479/AVlXFRxuMCk= -golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/net v0.50.0 h1:ucWh9eiCGyDR3vtzso0WMQinm2Dnt8cFMuQa9K33J60= golang.org/x/net v0.50.0/go.mod h1:UgoSli3F/pBgdJBHCTc+tp3gmrU4XswgGRgtnwWTfyM= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4= golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= @@ -324,7 +153,6 @@ golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5h golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -333,9 +161,8 @@ golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k= golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= @@ -347,12 +174,9 @@ golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk= golang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA= -golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI= -golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.1.9/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= golang.org/x/tools v0.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k= golang.org/x/tools v0.42.0/go.mod h1:Ma6lCIwGZvHK6XtgbswSoWroEkhugApmsXyrUmBhfr0= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -367,15 +191,11 @@ google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzi google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= -google.golang.org/protobuf v1.36.9 h1:w2gp2mA27hUeUzj9Ex9FBjsBm40zfaDtEWow293U7Iw= -google.golang.org/protobuf v1.36.9/go.mod h1:fuxRtAxBytpl4zzqUh6/eyUujkJdNiuEkXntxiD/uRU= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b h1:QRR6H1YWRnHb4Y/HeNFCTJLFVxaq6wH4YuVdsUOr75U= gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= -gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA= -gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= @@ -388,5 +208,3 @@ gopkg.in/yaml.v3 v3.0.0-20191026110619-0b21df46bc1d/go.mod h1:K4uyk7z7BCEPqu6E+C gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -moul.io/http2curl/v2 v2.3.0 h1:9r3JfDzWPcbIklMOs2TnIFzDYvfAZvjeavG6EzP7jYs= -moul.io/http2curl/v2 v2.3.0/go.mod h1:RW4hyBjTWSYDOxapodpNEtX0g5Eb16sxklBqmd2RHcE= diff --git a/internal/test/issues/issue-1039/client-config.yaml b/internal/test/issues/issue-1039/client-config.yaml deleted file mode 100644 index a117c7c745..0000000000 --- a/internal/test/issues/issue-1039/client-config.yaml +++ /dev/null @@ -1,5 +0,0 @@ -# yaml-language-server: $schema=../../../../configuration-schema.json -package: issue1039 -generate: - client: true -output: client.gen.go diff --git a/internal/test/issues/issue-1039/client.gen.go b/internal/test/issues/issue-1039/client.gen.go deleted file mode 100644 index 3114f29862..0000000000 --- a/internal/test/issues/issue-1039/client.gen.go +++ /dev/null @@ -1,261 +0,0 @@ -// Package issue1039 provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package issue1039 - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "io" - "net/http" - "net/url" - "strings" -) - -// RequestEditorFn is the function signature for the RequestEditor callback function -type RequestEditorFn func(ctx context.Context, req *http.Request) error - -// Doer performs HTTP requests. -// -// The standard http.Client implements this interface. -type HttpRequestDoer interface { - Do(req *http.Request) (*http.Response, error) -} - -// Client which conforms to the OpenAPI3 specification for this service. -type Client struct { - // The endpoint of the server conforming to this interface, with scheme, - // https://api.deepmap.com for example. This can contain a path relative - // to the server, such as https://api.deepmap.com/dev-test, and all the - // paths in the swagger spec will be appended to the server. - Server string - - // Doer for performing requests, typically a *http.Client with any - // customized settings, such as certificate chains. - Client HttpRequestDoer - - // A list of callbacks for modifying requests which are generated before sending over - // the network. - RequestEditors []RequestEditorFn -} - -// ClientOption allows setting custom parameters during construction -type ClientOption func(*Client) error - -// Creates a new Client, with reasonable defaults -func NewClient(server string, opts ...ClientOption) (*Client, error) { - // create a client with sane default values - client := Client{ - Server: server, - } - // mutate client and add all optional params - for _, o := range opts { - if err := o(&client); err != nil { - return nil, err - } - } - // ensure the server URL always has a trailing slash - if !strings.HasSuffix(client.Server, "/") { - client.Server += "/" - } - // create httpClient, if not already present - if client.Client == nil { - client.Client = &http.Client{} - } - return &client, nil -} - -// WithHTTPClient allows overriding the default Doer, which is -// automatically created using http.Client. This is useful for tests. -func WithHTTPClient(doer HttpRequestDoer) ClientOption { - return func(c *Client) error { - c.Client = doer - return nil - } -} - -// WithRequestEditorFn allows setting up a callback function, which will be -// called right before sending the request. This can be used to mutate the request. -func WithRequestEditorFn(fn RequestEditorFn) ClientOption { - return func(c *Client) error { - c.RequestEditors = append(c.RequestEditors, fn) - return nil - } -} - -// The interface specification for the client above. -type ClientInterface interface { - // ExamplePatchWithBody request with any body - ExamplePatchWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) - - ExamplePatch(ctx context.Context, body ExamplePatchJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) -} - -func (c *Client) ExamplePatchWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewExamplePatchRequestWithBody(c.Server, contentType, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) ExamplePatch(ctx context.Context, body ExamplePatchJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewExamplePatchRequest(c.Server, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -// NewExamplePatchRequest calls the generic ExamplePatch builder with application/json body -func NewExamplePatchRequest(server string, body ExamplePatchJSONRequestBody) (*http.Request, error) { - var bodyReader io.Reader - buf, err := json.Marshal(body) - if err != nil { - return nil, err - } - bodyReader = bytes.NewReader(buf) - return NewExamplePatchRequestWithBody(server, "application/json", bodyReader) -} - -// NewExamplePatchRequestWithBody generates requests for ExamplePatch with any type of body -func NewExamplePatchRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/example") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("PATCH", queryURL.String(), body) - if err != nil { - return nil, err - } - - req.Header.Add("Content-Type", contentType) - - return req, nil -} - -func (c *Client) applyEditors(ctx context.Context, req *http.Request, additionalEditors []RequestEditorFn) error { - for _, r := range c.RequestEditors { - if err := r(ctx, req); err != nil { - return err - } - } - for _, r := range additionalEditors { - if err := r(ctx, req); err != nil { - return err - } - } - return nil -} - -// ClientWithResponses builds on ClientInterface to offer response payloads -type ClientWithResponses struct { - ClientInterface -} - -// NewClientWithResponses creates a new ClientWithResponses, which wraps -// Client with return type handling -func NewClientWithResponses(server string, opts ...ClientOption) (*ClientWithResponses, error) { - client, err := NewClient(server, opts...) - if err != nil { - return nil, err - } - return &ClientWithResponses{client}, nil -} - -// WithBaseURL overrides the baseURL. -func WithBaseURL(baseURL string) ClientOption { - return func(c *Client) error { - newBaseURL, err := url.Parse(baseURL) - if err != nil { - return err - } - c.Server = newBaseURL.String() - return nil - } -} - -// ClientWithResponsesInterface is the interface specification for the client with responses above. -type ClientWithResponsesInterface interface { - // ExamplePatchWithBodyWithResponse request with any body - ExamplePatchWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*ExamplePatchResponse, error) - - ExamplePatchWithResponse(ctx context.Context, body ExamplePatchJSONRequestBody, reqEditors ...RequestEditorFn) (*ExamplePatchResponse, error) -} - -type ExamplePatchResponse struct { - Body []byte - HTTPResponse *http.Response -} - -// Status returns HTTPResponse.Status -func (r ExamplePatchResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r ExamplePatchResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -// ExamplePatchWithBodyWithResponse request with arbitrary body returning *ExamplePatchResponse -func (c *ClientWithResponses) ExamplePatchWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*ExamplePatchResponse, error) { - rsp, err := c.ExamplePatchWithBody(ctx, contentType, body, reqEditors...) - if err != nil { - return nil, err - } - return ParseExamplePatchResponse(rsp) -} - -func (c *ClientWithResponses) ExamplePatchWithResponse(ctx context.Context, body ExamplePatchJSONRequestBody, reqEditors ...RequestEditorFn) (*ExamplePatchResponse, error) { - rsp, err := c.ExamplePatch(ctx, body, reqEditors...) - if err != nil { - return nil, err - } - return ParseExamplePatchResponse(rsp) -} - -// ParseExamplePatchResponse parses an HTTP response from a ExamplePatchWithResponse call -func ParseExamplePatchResponse(rsp *http.Response) (*ExamplePatchResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &ExamplePatchResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - return response, nil -} diff --git a/internal/test/issues/issue-1039/defaultbehaviour/defaultbehaviour_test.go b/internal/test/issues/issue-1039/defaultbehaviour/defaultbehaviour_test.go deleted file mode 100644 index d49813ccf2..0000000000 --- a/internal/test/issues/issue-1039/defaultbehaviour/defaultbehaviour_test.go +++ /dev/null @@ -1,54 +0,0 @@ -package defaultbehaviour - -import ( - "encoding/json" - "testing" - - "github.com/stretchr/testify/require" -) - -func ptr[T any](v T) *T { - return &v -} - -func TestNullableDisabled(t *testing.T) { - // include all fields in patch request - patchReq := PatchRequest{ - ComplexRequiredNullable: &ComplexRequiredNullable{ - Name: ptr("test-name"), - }, - SimpleOptionalNonNullable: ptr(SimpleOptionalNonNullable("bar")), - ComplexOptionalNullable: &ComplexOptionalNullable{ - AliasName: ptr("foo-alias"), - Name: ptr("foo"), - }, - SimpleOptionalNullable: ptr(SimpleOptionalNullable(10)), - SimpleRequiredNullable: ptr(SimpleRequiredNullable(5)), - } - - expected := []byte(`{"complex_optional_nullable":{"alias_name":"foo-alias","name":"foo"},"complex_required_nullable":{"name":"test-name"},"simple_optional_non_nullable":"bar","simple_optional_nullable":10,"simple_required_nullable":5}`) - - actual, err := json.Marshal(patchReq) - require.NoError(t, err) - require.Equal(t, string(expected), string(actual)) - - // omit some fields - patchReq = PatchRequest{ - ComplexRequiredNullable: &ComplexRequiredNullable{ - Name: ptr("test-name"), - }, - // SimpleOptionalNonNullable is omitted - ComplexOptionalNullable: &ComplexOptionalNullable{ - AliasName: ptr("test-alias-name"), - Name: ptr("test-name"), - }, - SimpleOptionalNullable: ptr(SimpleOptionalNullable(10)), - // SimpleRequiredNullable is omitted - } - - expected = []byte(`{"complex_optional_nullable":{"alias_name":"test-alias-name","name":"test-name"},"complex_required_nullable":{"name":"test-name"},"simple_optional_nullable":10,"simple_required_nullable":null}`) - - actual, err = json.Marshal(patchReq) - require.NoError(t, err) - require.Equal(t, string(expected), string(actual)) -} diff --git a/internal/test/issues/issue-1039/defaultbehaviour/types.gen.go b/internal/test/issues/issue-1039/defaultbehaviour/types.gen.go deleted file mode 100644 index 5ed98d88f1..0000000000 --- a/internal/test/issues/issue-1039/defaultbehaviour/types.gen.go +++ /dev/null @@ -1,49 +0,0 @@ -// Package defaultbehaviour provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package defaultbehaviour - -// PatchRequest A request to patch an existing user object. -type PatchRequest struct { - // ComplexOptionalNullable Complex, optional and nullable - ComplexOptionalNullable *ComplexOptionalNullable `json:"complex_optional_nullable,omitempty"` - - // ComplexRequiredNullable Complex required and nullable - ComplexRequiredNullable *ComplexRequiredNullable `json:"complex_required_nullable"` - - // SimpleOptionalNonNullable Simple optional and non nullable - SimpleOptionalNonNullable *SimpleOptionalNonNullable `json:"simple_optional_non_nullable,omitempty"` - - // SimpleOptionalNullable Simple optional and nullable - SimpleOptionalNullable *SimpleOptionalNullable `json:"simple_optional_nullable,omitempty"` - - // SimpleRequiredNullable Simple required and nullable - SimpleRequiredNullable *SimpleRequiredNullable `json:"simple_required_nullable"` -} - -// ComplexOptionalNullable Complex, optional and nullable -type ComplexOptionalNullable struct { - // AliasName Optional and nullable - AliasName *string `json:"alias_name,omitempty"` - - // Name Optional and non nullable - Name *string `json:"name,omitempty"` -} - -// ComplexRequiredNullable Complex required and nullable -type ComplexRequiredNullable struct { - // Name Optional and non nullable - Name *string `json:"name,omitempty"` -} - -// SimpleOptionalNonNullable Simple optional and non nullable -type SimpleOptionalNonNullable = string - -// SimpleOptionalNullable Simple optional and nullable -type SimpleOptionalNullable = int - -// SimpleRequiredNullable Simple required and nullable -type SimpleRequiredNullable = int - -// ExamplePatchJSONRequestBody defines body for ExamplePatch for application/json ContentType. -type ExamplePatchJSONRequestBody = PatchRequest diff --git a/internal/test/issues/issue-1039/doc.go b/internal/test/issues/issue-1039/doc.go deleted file mode 100644 index 2997380aaf..0000000000 --- a/internal/test/issues/issue-1039/doc.go +++ /dev/null @@ -1,6 +0,0 @@ -package issue1039 - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=types-config.yaml spec.yaml -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=type-config-defaultbehaviour.yaml spec.yaml -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=client-config.yaml spec.yaml -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=server-config.yaml spec.yaml diff --git a/internal/test/issues/issue-1039/issue_test.go b/internal/test/issues/issue-1039/issue_test.go deleted file mode 100644 index 1cd390c315..0000000000 --- a/internal/test/issues/issue-1039/issue_test.go +++ /dev/null @@ -1,197 +0,0 @@ -package issue1039 - -import ( - _ "embed" - "encoding/json" - "testing" - - "github.com/oapi-codegen/nullable" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func ptr[T any](v T) *T { - return &v -} - -func TestNullableTypesMarshal(t *testing.T) { - // include all fields in patch request - patchReq := PatchRequest{ - ComplexRequiredNullable: nullable.NewNullableWithValue(ComplexRequiredNullable{ - Name: ptr("test-name"), - }), - SimpleOptionalNonNullable: ptr(SimpleOptionalNonNullable("bar")), - ComplexOptionalNullable: nullable.NewNullableWithValue(ComplexOptionalNullable{ - AliasName: nullable.NewNullableWithValue("foo-alias"), - Name: ptr("foo"), - }), - SimpleOptionalNullable: nullable.NewNullableWithValue(10), - SimpleRequiredNullable: nullable.NewNullableWithValue(5), - } - - expected := []byte(`{"complex_optional_nullable":{"alias_name":"foo-alias","name":"foo"},"complex_required_nullable":{"name":"test-name"},"simple_optional_non_nullable":"bar","simple_optional_nullable":10,"simple_required_nullable":5}`) - - actual, err := json.Marshal(patchReq) - require.NoError(t, err) - require.Equal(t, string(expected), string(actual)) - - // omit some fields - patchReq = PatchRequest{ - ComplexRequiredNullable: nullable.NewNullableWithValue(ComplexRequiredNullable{ - Name: ptr("test-name"), - }), - // SimpleOptionalNonNullable is omitted - ComplexOptionalNullable: nullable.NewNullableWithValue(ComplexOptionalNullable{ - AliasName: nullable.NewNullableWithValue("test-alias-name"), - Name: ptr("test-name"), - }), - SimpleOptionalNullable: nullable.NewNullableWithValue(10), - // SimpleRequiredNullable is omitted - } - - expected = []byte(`{"complex_optional_nullable":{"alias_name":"test-alias-name","name":"test-name"},"complex_required_nullable":{"name":"test-name"},"simple_optional_nullable":10,"simple_required_nullable":0}`) - - actual, err = json.Marshal(patchReq) - require.NoError(t, err) - require.Equal(t, string(expected), string(actual)) -} - -func TestNullableTypesUnmarshal(t *testing.T) { - type testCase struct { - name string - json []byte - assert func(t *testing.T, obj PatchRequest) - } - tests := []testCase{ - { - name: "when empty json is provided", - json: []byte(`{}`), - assert: func(t *testing.T, obj PatchRequest) { - t.Helper() - - // check for nullable fields - assert.Falsef(t, obj.SimpleRequiredNullable.IsSpecified(), "SimpleRequiredNullable field should not be set") - assert.Falsef(t, obj.SimpleRequiredNullable.IsNull(), "SimpleRequiredNullable field should not be null") - - assert.Falsef(t, obj.SimpleOptionalNullable.IsSpecified(), "SimpleOptionalNullable field should not be set") - assert.Falsef(t, obj.SimpleOptionalNullable.IsNull(), "SimpleOptionalNullable field should not be null") - - assert.Falsef(t, obj.ComplexOptionalNullable.IsSpecified(), "ComplexOptionalNullable field should not be set") - assert.Falsef(t, obj.ComplexOptionalNullable.IsNull(), "ComplexOptionalNullable field should not be null") - - assert.Falsef(t, obj.ComplexRequiredNullable.IsSpecified(), "ComplexRequiredNullable field should not be set") - assert.Falsef(t, obj.ComplexRequiredNullable.IsNull(), "ComplexRequiredNullable field should not be null") - - // check for non-nullable field - assert.Nilf(t, obj.SimpleOptionalNonNullable, "SimpleOptionalNonNullable field should be nil") - }, - }, - - { - name: "when only empty complex_optional_nullable is provided", - json: []byte(`{"complex_optional_nullable":{}}`), - assert: func(t *testing.T, obj PatchRequest) { - t.Helper() - // check for nullable field - assert.Truef(t, obj.ComplexOptionalNullable.IsSpecified(), "ComplexOptionalNullable field should be set") - assert.Falsef(t, obj.ComplexOptionalNullable.IsNull(), "ComplexOptionalNullable field should not be null") - - // other simple nullable fields should not be set and should not be null - assert.Falsef(t, obj.SimpleRequiredNullable.IsSpecified(), "SimpleRequiredNullable field should not be set") - assert.Falsef(t, obj.SimpleRequiredNullable.IsNull(), "SimpleRequiredNullable field should not be null") - - assert.Falsef(t, obj.SimpleOptionalNullable.IsSpecified(), "SimpleOptionalNullable field should not be set") - assert.Falsef(t, obj.SimpleOptionalNullable.IsNull(), "SimpleOptionalNullable field should not be null") - - // other complex nullable fields should not be set and should not be null - assert.Falsef(t, obj.ComplexRequiredNullable.IsSpecified(), "ComplexRequiredNullable field should not be set") - assert.Falsef(t, obj.ComplexRequiredNullable.IsNull(), "ComplexRequiredNullable field should not be null") - - // other non-nullable field should have its zero value - assert.Nilf(t, obj.SimpleOptionalNonNullable, "SimpleOptionalNonNullable field should be nil") - - }, - }, - - { - name: "when only complex_optional_nullable with its `name` child field is provided", - json: []byte(`{"complex_optional_nullable":{"name":"test-name"}}`), - assert: func(t *testing.T, obj PatchRequest) { - t.Helper() - - assert.Truef(t, obj.ComplexOptionalNullable.IsSpecified(), "ComplexOptionalNullable field should be set") - assert.Falsef(t, obj.ComplexOptionalNullable.IsNull(), "ComplexOptionalNullable field should not be null") - - gotComplexObj, err := obj.ComplexOptionalNullable.Get() - require.NoError(t, err) - assert.Equalf(t, "test-name", string(*gotComplexObj.Name), "name should be test-name") - - assert.Falsef(t, gotComplexObj.AliasName.IsSpecified(), "child field `alias name` should not be specified") - assert.Falsef(t, gotComplexObj.AliasName.IsNull(), "child field `alias name` should not be null") - }, - }, - - { - name: "when only complex_optional_nullable child fields `name` and `alias name` are provided with non-zero and null values respectively", - json: []byte(`{"complex_optional_nullable":{"name":"test-name","alias_name":null}}`), - assert: func(t *testing.T, obj PatchRequest) { - t.Helper() - - assert.Truef(t, obj.ComplexOptionalNullable.IsSpecified(), "ComplexOptionalNullable field should be set") - assert.Falsef(t, obj.ComplexOptionalNullable.IsNull(), "ComplexOptionalNullable field should not be null") - - gotComplexObj, err := obj.ComplexOptionalNullable.Get() - require.NoError(t, err) - assert.Equalf(t, "test-name", string(*gotComplexObj.Name), "name should be test-name") - - assert.Truef(t, gotComplexObj.AliasName.IsSpecified(), "child field `alias name` should be set") - assert.Truef(t, gotComplexObj.AliasName.IsNull(), "child field `alias name` should be null") - }, - }, - - { - name: "when simple_required_nullable is null ", - json: []byte(`{"simple_required_nullable":null}`), - assert: func(t *testing.T, obj PatchRequest) { - t.Helper() - - assert.Truef(t, obj.SimpleRequiredNullable.IsSpecified(), "SimpleRequiredNullable field should be set") - assert.Truef(t, obj.SimpleRequiredNullable.IsNull(), "SimpleRequiredNullable field should be null") - }, - }, - - { - name: "when simple_required_nullable is null and organization has non zero value", - json: []byte(`{"complex_optional_nullable":{"name":"foo","alias_name":"bar"},"simple_required_nullable":null}`), - assert: func(t *testing.T, obj PatchRequest) { - t.Helper() - - assert.Truef(t, obj.SimpleRequiredNullable.IsSpecified(), "SimpleRequiredNullable field should be set") - assert.Truef(t, obj.SimpleRequiredNullable.IsNull(), "SimpleRequiredNullable field should be null") - - assert.Truef(t, obj.ComplexOptionalNullable.IsSpecified(), "ComplexOptionalNullable field should be set") - assert.Falsef(t, obj.ComplexOptionalNullable.IsNull(), "ComplexOptionalNullable field should not be null") - - gotComplexObj, err := obj.ComplexOptionalNullable.Get() - require.NoError(t, err) - assert.Equalf(t, "foo", string(*gotComplexObj.Name), "child field `name` should be foo") - - assert.Truef(t, gotComplexObj.AliasName.IsSpecified(), "child field `alias name` should be set") - assert.Falsef(t, gotComplexObj.AliasName.IsNull(), "child field `alias name` should not be null") - - gotAliasName, err := gotComplexObj.AliasName.Get() - require.NoError(t, err) - assert.Equalf(t, "bar", gotAliasName, "child field `alias name` should be bar") - }, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - var obj PatchRequest - err := json.Unmarshal(tt.json, &obj) - require.NoError(t, err) - - tt.assert(t, obj) - }) - } -} diff --git a/internal/test/issues/issue-1039/server-config.yaml b/internal/test/issues/issue-1039/server-config.yaml deleted file mode 100644 index e1e7879932..0000000000 --- a/internal/test/issues/issue-1039/server-config.yaml +++ /dev/null @@ -1,5 +0,0 @@ -# yaml-language-server: $schema=../../../../configuration-schema.json -package: issue1039 -generate: - chi-server: true -output: server.gen.go diff --git a/internal/test/issues/issue-1039/server.gen.go b/internal/test/issues/issue-1039/server.gen.go deleted file mode 100644 index a39f95dae7..0000000000 --- a/internal/test/issues/issue-1039/server.gen.go +++ /dev/null @@ -1,170 +0,0 @@ -// Package issue1039 provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package issue1039 - -import ( - "fmt" - "net/http" - - "github.com/go-chi/chi/v5" -) - -// ServerInterface represents all server handlers. -type ServerInterface interface { - - // (PATCH /example) - ExamplePatch(w http.ResponseWriter, r *http.Request) -} - -// Unimplemented server implementation that returns http.StatusNotImplemented for each endpoint. - -type Unimplemented struct{} - -// (PATCH /example) -func (_ Unimplemented) ExamplePatch(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusNotImplemented) -} - -// ServerInterfaceWrapper converts contexts to parameters. -type ServerInterfaceWrapper struct { - Handler ServerInterface - HandlerMiddlewares []MiddlewareFunc - ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) -} - -type MiddlewareFunc func(http.Handler) http.Handler - -// ExamplePatch operation middleware -func (siw *ServerInterfaceWrapper) ExamplePatch(w http.ResponseWriter, r *http.Request) { - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.ExamplePatch(w, r) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -type UnescapedCookieParamError struct { - ParamName string - Err error -} - -func (e *UnescapedCookieParamError) Error() string { - return fmt.Sprintf("error unescaping cookie parameter '%s'", e.ParamName) -} - -func (e *UnescapedCookieParamError) Unwrap() error { - return e.Err -} - -type UnmarshalingParamError struct { - ParamName string - Err error -} - -func (e *UnmarshalingParamError) Error() string { - return fmt.Sprintf("Error unmarshaling parameter %s as JSON: %s", e.ParamName, e.Err.Error()) -} - -func (e *UnmarshalingParamError) Unwrap() error { - return e.Err -} - -type RequiredParamError struct { - ParamName string -} - -func (e *RequiredParamError) Error() string { - return fmt.Sprintf("Query argument %s is required, but not found", e.ParamName) -} - -type RequiredHeaderError struct { - ParamName string - Err error -} - -func (e *RequiredHeaderError) Error() string { - return fmt.Sprintf("Header parameter %s is required, but not found", e.ParamName) -} - -func (e *RequiredHeaderError) Unwrap() error { - return e.Err -} - -type InvalidParamFormatError struct { - ParamName string - Err error -} - -func (e *InvalidParamFormatError) Error() string { - return fmt.Sprintf("Invalid format for parameter %s: %s", e.ParamName, e.Err.Error()) -} - -func (e *InvalidParamFormatError) Unwrap() error { - return e.Err -} - -type TooManyValuesForParamError struct { - ParamName string - Count int -} - -func (e *TooManyValuesForParamError) Error() string { - return fmt.Sprintf("Expected one value for %s, got %d", e.ParamName, e.Count) -} - -// Handler creates http.Handler with routing matching OpenAPI spec. -func Handler(si ServerInterface) http.Handler { - return HandlerWithOptions(si, ChiServerOptions{}) -} - -type ChiServerOptions struct { - BaseURL string - BaseRouter chi.Router - Middlewares []MiddlewareFunc - ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) -} - -// HandlerFromMux creates http.Handler with routing matching OpenAPI spec based on the provided mux. -func HandlerFromMux(si ServerInterface, r chi.Router) http.Handler { - return HandlerWithOptions(si, ChiServerOptions{ - BaseRouter: r, - }) -} - -func HandlerFromMuxWithBaseURL(si ServerInterface, r chi.Router, baseURL string) http.Handler { - return HandlerWithOptions(si, ChiServerOptions{ - BaseURL: baseURL, - BaseRouter: r, - }) -} - -// HandlerWithOptions creates http.Handler with additional options -func HandlerWithOptions(si ServerInterface, options ChiServerOptions) http.Handler { - r := options.BaseRouter - - if r == nil { - r = chi.NewRouter() - } - if options.ErrorHandlerFunc == nil { - options.ErrorHandlerFunc = func(w http.ResponseWriter, r *http.Request, err error) { - http.Error(w, err.Error(), http.StatusBadRequest) - } - } - wrapper := ServerInterfaceWrapper{ - Handler: si, - HandlerMiddlewares: options.Middlewares, - ErrorHandlerFunc: options.ErrorHandlerFunc, - } - - r.Group(func(r chi.Router) { - r.Patch(options.BaseURL+"/example", wrapper.ExamplePatch) - }) - - return r -} diff --git a/internal/test/issues/issue-1039/type-config-defaultbehaviour.yaml b/internal/test/issues/issue-1039/type-config-defaultbehaviour.yaml deleted file mode 100644 index 2b07679083..0000000000 --- a/internal/test/issues/issue-1039/type-config-defaultbehaviour.yaml +++ /dev/null @@ -1,5 +0,0 @@ -# yaml-language-server: $schema=../../../../configuration-schema.json -package: defaultbehaviour -generate: - models: true -output: defaultbehaviour/types.gen.go diff --git a/internal/test/issues/issue-1087/api.gen.go b/internal/test/issues/issue-1087/api.gen.go deleted file mode 100644 index 3c408cc8f9..0000000000 --- a/internal/test/issues/issue-1087/api.gen.go +++ /dev/null @@ -1,452 +0,0 @@ -// Package issue1087 provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package issue1087 - -import ( - "context" - "encoding/json" - "fmt" - "io" - "net/http" - "net/url" - "strings" - - "github.com/go-chi/chi/v5" - externalRef0 "github.com/oapi-codegen/oapi-codegen/v2/internal/test/issues/issue-1087/deps" -) - -// Thing defines model for Thing. -type Thing struct { - // Name just a name - Name string `json:"name"` -} - -// ThingList Object containing list of Things -type ThingList struct { - Keys []Thing `json:"keys"` -} - -// N404 defines model for 404. -type N404 = externalRef0.Error - -// ThingResponse Object containing list of Things -type ThingResponse = ThingList - -// RequestEditorFn is the function signature for the RequestEditor callback function -type RequestEditorFn func(ctx context.Context, req *http.Request) error - -// Doer performs HTTP requests. -// -// The standard http.Client implements this interface. -type HttpRequestDoer interface { - Do(req *http.Request) (*http.Response, error) -} - -// Client which conforms to the OpenAPI3 specification for this service. -type Client struct { - // The endpoint of the server conforming to this interface, with scheme, - // https://api.deepmap.com for example. This can contain a path relative - // to the server, such as https://api.deepmap.com/dev-test, and all the - // paths in the swagger spec will be appended to the server. - Server string - - // Doer for performing requests, typically a *http.Client with any - // customized settings, such as certificate chains. - Client HttpRequestDoer - - // A list of callbacks for modifying requests which are generated before sending over - // the network. - RequestEditors []RequestEditorFn -} - -// ClientOption allows setting custom parameters during construction -type ClientOption func(*Client) error - -// Creates a new Client, with reasonable defaults -func NewClient(server string, opts ...ClientOption) (*Client, error) { - // create a client with sane default values - client := Client{ - Server: server, - } - // mutate client and add all optional params - for _, o := range opts { - if err := o(&client); err != nil { - return nil, err - } - } - // ensure the server URL always has a trailing slash - if !strings.HasSuffix(client.Server, "/") { - client.Server += "/" - } - // create httpClient, if not already present - if client.Client == nil { - client.Client = &http.Client{} - } - return &client, nil -} - -// WithHTTPClient allows overriding the default Doer, which is -// automatically created using http.Client. This is useful for tests. -func WithHTTPClient(doer HttpRequestDoer) ClientOption { - return func(c *Client) error { - c.Client = doer - return nil - } -} - -// WithRequestEditorFn allows setting up a callback function, which will be -// called right before sending the request. This can be used to mutate the request. -func WithRequestEditorFn(fn RequestEditorFn) ClientOption { - return func(c *Client) error { - c.RequestEditors = append(c.RequestEditors, fn) - return nil - } -} - -// The interface specification for the client above. -type ClientInterface interface { - // GetThings request - GetThings(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) -} - -func (c *Client) GetThings(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewGetThingsRequest(c.Server) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -// NewGetThingsRequest generates requests for GetThings -func NewGetThingsRequest(server string) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/api/my/path") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -func (c *Client) applyEditors(ctx context.Context, req *http.Request, additionalEditors []RequestEditorFn) error { - for _, r := range c.RequestEditors { - if err := r(ctx, req); err != nil { - return err - } - } - for _, r := range additionalEditors { - if err := r(ctx, req); err != nil { - return err - } - } - return nil -} - -// ClientWithResponses builds on ClientInterface to offer response payloads -type ClientWithResponses struct { - ClientInterface -} - -// NewClientWithResponses creates a new ClientWithResponses, which wraps -// Client with return type handling -func NewClientWithResponses(server string, opts ...ClientOption) (*ClientWithResponses, error) { - client, err := NewClient(server, opts...) - if err != nil { - return nil, err - } - return &ClientWithResponses{client}, nil -} - -// WithBaseURL overrides the baseURL. -func WithBaseURL(baseURL string) ClientOption { - return func(c *Client) error { - newBaseURL, err := url.Parse(baseURL) - if err != nil { - return err - } - c.Server = newBaseURL.String() - return nil - } -} - -// ClientWithResponsesInterface is the interface specification for the client with responses above. -type ClientWithResponsesInterface interface { - // GetThingsWithResponse request - GetThingsWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*GetThingsResponse, error) -} - -type GetThingsResponse struct { - Body []byte - HTTPResponse *http.Response - JSON200 *ThingResponse - JSON401 *externalRef0.N401 - JSON403 *externalRef0.N403 - JSON404 *N404 - JSON500 *externalRef0.DefaultError -} - -// Status returns HTTPResponse.Status -func (r GetThingsResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r GetThingsResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -// GetThingsWithResponse request returning *GetThingsResponse -func (c *ClientWithResponses) GetThingsWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*GetThingsResponse, error) { - rsp, err := c.GetThings(ctx, reqEditors...) - if err != nil { - return nil, err - } - return ParseGetThingsResponse(rsp) -} - -// ParseGetThingsResponse parses an HTTP response from a GetThingsWithResponse call -func ParseGetThingsResponse(rsp *http.Response) (*GetThingsResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &GetThingsResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest ThingResponse - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON200 = &dest - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: - var dest externalRef0.N401 - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON401 = &dest - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: - var dest externalRef0.N403 - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON403 = &dest - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: - var dest N404 - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON404 = &dest - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: - var dest externalRef0.DefaultError - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON500 = &dest - - case rsp.StatusCode == 401: - // Content-type (text/plain) unsupported - - case rsp.StatusCode == 403: - // Content-type (text/plain) unsupported - - } - - return response, nil -} - -// ServerInterface represents all server handlers. -type ServerInterface interface { - // list things - // (GET /api/my/path) - GetThings(w http.ResponseWriter, r *http.Request) -} - -// Unimplemented server implementation that returns http.StatusNotImplemented for each endpoint. - -type Unimplemented struct{} - -// list things -// (GET /api/my/path) -func (_ Unimplemented) GetThings(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusNotImplemented) -} - -// ServerInterfaceWrapper converts contexts to parameters. -type ServerInterfaceWrapper struct { - Handler ServerInterface - HandlerMiddlewares []MiddlewareFunc - ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) -} - -type MiddlewareFunc func(http.Handler) http.Handler - -// GetThings operation middleware -func (siw *ServerInterfaceWrapper) GetThings(w http.ResponseWriter, r *http.Request) { - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.GetThings(w, r) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -type UnescapedCookieParamError struct { - ParamName string - Err error -} - -func (e *UnescapedCookieParamError) Error() string { - return fmt.Sprintf("error unescaping cookie parameter '%s'", e.ParamName) -} - -func (e *UnescapedCookieParamError) Unwrap() error { - return e.Err -} - -type UnmarshalingParamError struct { - ParamName string - Err error -} - -func (e *UnmarshalingParamError) Error() string { - return fmt.Sprintf("Error unmarshaling parameter %s as JSON: %s", e.ParamName, e.Err.Error()) -} - -func (e *UnmarshalingParamError) Unwrap() error { - return e.Err -} - -type RequiredParamError struct { - ParamName string -} - -func (e *RequiredParamError) Error() string { - return fmt.Sprintf("Query argument %s is required, but not found", e.ParamName) -} - -type RequiredHeaderError struct { - ParamName string - Err error -} - -func (e *RequiredHeaderError) Error() string { - return fmt.Sprintf("Header parameter %s is required, but not found", e.ParamName) -} - -func (e *RequiredHeaderError) Unwrap() error { - return e.Err -} - -type InvalidParamFormatError struct { - ParamName string - Err error -} - -func (e *InvalidParamFormatError) Error() string { - return fmt.Sprintf("Invalid format for parameter %s: %s", e.ParamName, e.Err.Error()) -} - -func (e *InvalidParamFormatError) Unwrap() error { - return e.Err -} - -type TooManyValuesForParamError struct { - ParamName string - Count int -} - -func (e *TooManyValuesForParamError) Error() string { - return fmt.Sprintf("Expected one value for %s, got %d", e.ParamName, e.Count) -} - -// Handler creates http.Handler with routing matching OpenAPI spec. -func Handler(si ServerInterface) http.Handler { - return HandlerWithOptions(si, ChiServerOptions{}) -} - -type ChiServerOptions struct { - BaseURL string - BaseRouter chi.Router - Middlewares []MiddlewareFunc - ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) -} - -// HandlerFromMux creates http.Handler with routing matching OpenAPI spec based on the provided mux. -func HandlerFromMux(si ServerInterface, r chi.Router) http.Handler { - return HandlerWithOptions(si, ChiServerOptions{ - BaseRouter: r, - }) -} - -func HandlerFromMuxWithBaseURL(si ServerInterface, r chi.Router, baseURL string) http.Handler { - return HandlerWithOptions(si, ChiServerOptions{ - BaseURL: baseURL, - BaseRouter: r, - }) -} - -// HandlerWithOptions creates http.Handler with additional options -func HandlerWithOptions(si ServerInterface, options ChiServerOptions) http.Handler { - r := options.BaseRouter - - if r == nil { - r = chi.NewRouter() - } - if options.ErrorHandlerFunc == nil { - options.ErrorHandlerFunc = func(w http.ResponseWriter, r *http.Request, err error) { - http.Error(w, err.Error(), http.StatusBadRequest) - } - } - wrapper := ServerInterfaceWrapper{ - Handler: si, - HandlerMiddlewares: options.Middlewares, - ErrorHandlerFunc: options.ErrorHandlerFunc, - } - - r.Group(func(r chi.Router) { - r.Get(options.BaseURL+"/api/my/path", wrapper.GetThings) - }) - - return r -} diff --git a/internal/test/issues/issue-1087/deps/deps.gen.go b/internal/test/issues/issue-1087/deps/deps.gen.go deleted file mode 100644 index 8066ab2b57..0000000000 --- a/internal/test/issues/issue-1087/deps/deps.gen.go +++ /dev/null @@ -1,138 +0,0 @@ -// Package deps provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package deps - -import ( - "bytes" - "compress/gzip" - "encoding/base64" - "fmt" - "net/url" - "path" - "strings" - - "github.com/getkin/kin-openapi/openapi3" -) - -// BaseError defines model for BaseError. -type BaseError struct { - // Code The underlying http status code - Code int32 `json:"code"` - - // Domain The domain where the error is originating from as defined by the service - Domain string `json:"domain"` - - // Message A simple message in english describing the error and can be returned to the consumer - Message string `json:"message"` - - // Metadata Any additional details to be conveyed as determined by the service. If present, will return map of key value pairs - Metadata *map[string]string `json:"metadata,omitempty"` -} - -// Error defines model for Error. -type Error = BaseError - -// N401 defines model for 401. -type N401 = Error - -// N403 defines model for 403. -type N403 = Error - -// N410 defines model for 410. -type N410 = Error - -// DefaultError defines model for DefaultError. -type DefaultError = Error - -// Base64 encoded, gzipped, json marshaled Swagger object -var swaggerSpec = []string{ - - "H4sIAAAAAAAC/7SV34/jNBDH/5WR4TFq0+siobwVDtAiAacDnk6rlRtPmjmcsc+edLes+r8jO2nTH6tb", - "7qR9ahPPeL7zmR95UrXrvGNkiap6UgGjdxwxP9yUi/RTOxZkSX+195ZqLeR4/jE6Tu/wUXfe4mBpUFU3", - "5aJQxnWaWFVq1UurCtVhjHqDqlK3vNWWDOheWmQZr1OFCqjzlQeL+9W5xb5QsW6x0ynUtwEbValv5pP+", - "+XAa5z+F4ILa7wsl+Chzb7OSpxPvo2b164MARcBHTwGNKpTsfHofJRBv1D7dYjDWgXwWUam/OSl3gf5F", - "M4NbNkkfRpBWC/jgtmTQQB3QJO3axnQ/O4GcVMriplx+Hdfl57iu6hpjhLfIlBM54hwO7seDV6F4GftF", - "iD+7sCZjkK8IBvzUYxSoNSdoa4QJd4a3KL8K3qI8gXcG7hfHeMorP78KpjHSi3TeY+2CAXZgHW8wgN5q", - "snpts6632OjeyhD4ZRRflsaVljEaYDKAw36AxgXQvBteRyAGaRFW724zivHWFPQHHfEo1QfnMQgN+2Wo", - "zNNFwL9ahJ4NBrsj3kAr4iGKlj5CdigmoN+VZaEaFzotqlLEsnwz4SUW3GBIxA51fy7UcAYPLQbMOQyJ", - "UgQXaEOsJalogutARzDYEKOB9S7bRgxbqs80qesCnzTbpYIVREp+MFokkMgbS7GFwXKdwk+6NJs0Gmku", - "Akofkhhx2aB2HPsOw5ma1QZPRsmmKZVWMyy+f16naKMld4s2hpJKbd+dVe3K6SIj3sHkCgZFk41J4zpL", - "3OIOzYBSMHTP0JzBbQM+YESWAh7I2jFV6LQH18A/uEvLtEfwmkI8zffYYrvfdZdknj6moqb1kjf9/pi+", - "W3/EWnLfHk+rD2pstrF3phreXTkW6tjg2to/GlV9+PywTTOxvysuhuKwhq47ZTjJQwDRY00N1Yfaj+hO", - "26OPQ2tQ/g41A2J81HX64MUeZ/Bn63prsi3Tpx7hgaQlBg3HpKdGep+j3/84ULlcYf8P3XHJXjNMVxA3", - "LncYSQ75mzNoU3m3GOJA4c2snJWJuPPI2pOq1HJWzpaqUF5Lmwim9YMhueQ69MGqSs3V/m7/XwAAAP//", - "TAbhS+0IAAA=", -} - -// GetSwagger returns the content of the embedded swagger specification file -// or error if failed to decode -func decodeSpec() ([]byte, error) { - zipped, err := base64.StdEncoding.DecodeString(strings.Join(swaggerSpec, "")) - if err != nil { - return nil, fmt.Errorf("error base64 decoding spec: %w", err) - } - zr, err := gzip.NewReader(bytes.NewReader(zipped)) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - var buf bytes.Buffer - _, err = buf.ReadFrom(zr) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - - return buf.Bytes(), nil -} - -var rawSpec = decodeSpecCached() - -// a naive cached of a decoded swagger spec -func decodeSpecCached() func() ([]byte, error) { - data, err := decodeSpec() - return func() ([]byte, error) { - return data, err - } -} - -// Constructs a synthetic filesystem for resolving external references when loading openapi specifications. -func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { - res := make(map[string]func() ([]byte, error)) - if len(pathToFile) > 0 { - res[pathToFile] = rawSpec - } - - return res -} - -// GetSwagger returns the Swagger specification corresponding to the generated code -// in this file. The external references of Swagger specification are resolved. -// The logic of resolving external references is tightly connected to "import-mapping" feature. -// Externally referenced files must be embedded in the corresponding golang packages. -// Urls can be supported but this task was out of the scope. -func GetSwagger() (swagger *openapi3.T, err error) { - resolvePath := PathToRawSpec("") - - loader := openapi3.NewLoader() - loader.IsExternalRefsAllowed = true - loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() - pathToFile = path.Clean(pathToFile) - getSpec, ok := resolvePath[pathToFile] - if !ok { - err1 := fmt.Errorf("path not found: %s", pathToFile) - return nil, err1 - } - return getSpec() - } - var specData []byte - specData, err = rawSpec() - if err != nil { - return - } - swagger, err = loader.LoadFromData(specData) - if err != nil { - return - } - return -} diff --git a/internal/test/issues/issue-1087/deps/doc.go b/internal/test/issues/issue-1087/deps/doc.go deleted file mode 100644 index 0684d56cae..0000000000 --- a/internal/test/issues/issue-1087/deps/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -package deps - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml my-deps.json diff --git a/internal/test/issues/issue-1087/deps/my-deps.json b/internal/test/issues/issue-1087/deps/my-deps.json deleted file mode 100644 index 57674e1212..0000000000 --- a/internal/test/issues/issue-1087/deps/my-deps.json +++ /dev/null @@ -1,153 +0,0 @@ -{ - "openapi": "3.0.3", - "info": { - "title": "Models", - "description": "", - "version": "2.0.0" - }, - "servers": [ - { - "url": "/" - } - ], - "paths": {}, - "components": { - "responses": { - "DefaultError": { - "description": "Default error response for any errors in the API", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Error" - } - } - } - }, - "403": { - "description": "Forbidden. Indicates that request cannot be authorized", - "content": { - "text/plain": { - "schema": { - "type": "string", - "example": "Access Denied" - } - }, - "application/json": { - "schema": { - "$ref": "#/components/schemas/Error" - }, - "example": { - "code": 403, - "domain": "Auth", - "message": "Access Denied", - "reason": "Access_Denied" - } - } - } - }, - "401": { - "description": "Unauthorized. Indicates that provided credentials is not valid", - "content": { - "text/plain": { - "schema": { - "type": "string", - "example": "Jwt is expired" - } - }, - "application/json": { - "schema": { - "$ref": "#/components/schemas/Error" - }, - "example": { - "code": 401, - "domain": "Auth", - "message": "Invalid authentication", - "reason": "Invalid_Authentication" - } - } - } - }, - "410": { - "description": "Record no longer available", - "content": { - "text/plain": { - "schema": { - "type": "string", - "example": "Gone" - } - }, - "application/json": { - "schema": { - "$ref": "#/components/schemas/Error" - }, - "example": { - "code": 410, - "domain": "", - "message": "Gone", - "reason": "Gone" - } - } - } - } - }, - "schemas": { - "Error": { - "allOf": [ - { - "$ref": "#/components/schemas/BaseError" - } - ], - "required": [ - "code", - "domain", - "message", - "reason" - ], - "type": "object", - "properties": { - "reason": { - "type": "string", - "description": "A reason code specific to the service and can be used to identify the exact issue. Should be unique within a domain", - "example": "Reason_Code" - } - } - }, - "BaseError": { - "required": [ - "code", - "domain", - "message" - ], - "type": "object", - "properties": { - "code": { - "type": "integer", - "description": "The underlying http status code", - "format": "int32", - "example": 500 - }, - "message": { - "type": "string", - "description": "A simple message in english describing the error and can be returned to the consumer", - "example": "Age cannot be less than 18" - }, - "domain": { - "type": "string", - "description": "The domain where the error is originating from as defined by the service", - "example": "" - }, - "metadata": { - "type": "object", - "additionalProperties": { - "type": "string" - }, - "description": "Any additional details to be conveyed as determined by the service. If present, will return map of key value pairs", - "example": { - "propertyName": "propertyName is required" - } - } - } - } - } - } -} diff --git a/internal/test/issues/issue-1087/doc.go b/internal/test/issues/issue-1087/doc.go deleted file mode 100644 index 2ad8db520c..0000000000 --- a/internal/test/issues/issue-1087/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -package issue1087 - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=server.config.yaml spec.yaml diff --git a/internal/test/issues/issue-1087/server.config.yaml b/internal/test/issues/issue-1087/server.config.yaml deleted file mode 100644 index 6d795c05d7..0000000000 --- a/internal/test/issues/issue-1087/server.config.yaml +++ /dev/null @@ -1,11 +0,0 @@ -# yaml-language-server: $schema=../../../../configuration-schema.json -package: issue1087 -output: - api.gen.go -generate: - chi-server: true - models: true - embedded-spec: false - client: true -import-mapping: - ./deps/my-deps.json: github.com/oapi-codegen/oapi-codegen/v2/internal/test/issues/issue-1087/deps diff --git a/internal/test/issues/issue-1087/spec.yaml b/internal/test/issues/issue-1087/spec.yaml deleted file mode 100644 index 5686be9b56..0000000000 --- a/internal/test/issues/issue-1087/spec.yaml +++ /dev/null @@ -1,109 +0,0 @@ -openapi: 3.0.3 -info: - title: test - description: "The API for Test" - version: 2.0.0 -servers: - - url: http://localhost:8000 -tags: - - name: Tag - description: Foo Bar -paths: - /api/my/path: - get: - tags: - - Tag - summary: list things - description: my list of things - operationId: getThings - responses: - 200: - $ref: "#/components/responses/ThingResponse" - 304: - $ref: "#/components/responses/304" - 401: - $ref: "./deps/my-deps.json#/components/responses/401" - 403: - $ref: "./deps/my-deps.json#/components/responses/403" - 404: - $ref: "#/components/responses/404" - 500: - $ref: "./deps/my-deps.json#/components/responses/DefaultError" -components: - securitySchemes: - bearerAuthWebhook: - type: http - scheme: bearer - bearerFormat: JWT - description: The JWT access token. - responses: - Empty: - description: No content - ThingResponse: - description: List of Things - content: - application/json: - schema: - $ref: "#/components/schemas/ThingList" - 304: - description: Response when client should use cached results - headers: - Cache-Control: - description: defines TTL of resource in seconds, indicates that the response can be stored in caches, and indicates that the response can be stored only in a private cache - example: "max-age: 86400, must-revalidate, private" - schema: - type: string - ETag: - description: "indicate the current version of the resource" - schema: - type: string - 404: - description: Not Found. Resource could not be found - content: - application/json: - schema: - $ref: "./deps/my-deps.json#/components/schemas/Error" - example: - code: 404 - domain: "Foo" - message: "Not Found. Subscription could not be found" - reason: "Not_Found" - 409: - description: Conflict. Resource already exists - content: - application/json: - schema: - $ref: "./deps/my-deps.json#/components/schemas/Error" - example: - code: 404 - domain: "Webhook" - message: "Conflict. Resource already exists" - reason: "Conflict" - 410: - description: Gone. Record no longer available - content: - application/json: - schema: - $ref: "./deps/my-deps.json#/components/schemas/Error" - example: - code: 403 - domain: "" - message: "Gone" - reason: "Already deleted" - schemas: - Thing: - type: object - properties: - name: - type: string - description: just a name - required: [ name] - ThingList: - type: object - description: Object containing list of Things - properties: - keys: - type: array - items: - $ref: "#/components/schemas/Thing" - required: [ keys ] diff --git a/internal/test/issues/issue-1093/api/child/child.gen.go b/internal/test/issues/issue-1093/api/child/child.gen.go deleted file mode 100644 index 203fad36e8..0000000000 --- a/internal/test/issues/issue-1093/api/child/child.gen.go +++ /dev/null @@ -1,230 +0,0 @@ -// Package api provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package api - -import ( - "bytes" - "compress/gzip" - "context" - "encoding/base64" - "encoding/json" - "fmt" - "net/http" - "net/url" - "path" - "strings" - - "github.com/getkin/kin-openapi/openapi3" - "github.com/gin-gonic/gin" - externalRef0 "github.com/oapi-codegen/oapi-codegen/v2/internal/test/issues/issue-1093/api/parent" - strictgin "github.com/oapi-codegen/runtime/strictmiddleware/gin" -) - -// ServerInterface represents all server handlers. -type ServerInterface interface { - - // (GET /pets) - GetPets(c *gin.Context) -} - -// ServerInterfaceWrapper converts contexts to parameters. -type ServerInterfaceWrapper struct { - Handler ServerInterface - HandlerMiddlewares []MiddlewareFunc - ErrorHandler func(*gin.Context, error, int) -} - -type MiddlewareFunc func(c *gin.Context) - -// GetPets operation middleware -func (siw *ServerInterfaceWrapper) GetPets(c *gin.Context) { - - for _, middleware := range siw.HandlerMiddlewares { - middleware(c) - if c.IsAborted() { - return - } - } - - siw.Handler.GetPets(c) -} - -// GinServerOptions provides options for the Gin server. -type GinServerOptions struct { - BaseURL string - Middlewares []MiddlewareFunc - ErrorHandler func(*gin.Context, error, int) -} - -// RegisterHandlers creates http.Handler with routing matching OpenAPI spec. -func RegisterHandlers(router gin.IRouter, si ServerInterface) { - RegisterHandlersWithOptions(router, si, GinServerOptions{}) -} - -// RegisterHandlersWithOptions creates http.Handler with additional options -func RegisterHandlersWithOptions(router gin.IRouter, si ServerInterface, options GinServerOptions) { - errorHandler := options.ErrorHandler - if errorHandler == nil { - errorHandler = func(c *gin.Context, err error, statusCode int) { - c.JSON(statusCode, gin.H{"msg": err.Error()}) - } - } - - wrapper := ServerInterfaceWrapper{ - Handler: si, - HandlerMiddlewares: options.Middlewares, - ErrorHandler: errorHandler, - } - - router.GET(options.BaseURL+"/pets", wrapper.GetPets) -} - -type GetPetsRequestObject struct { -} - -type GetPetsResponseObject interface { - VisitGetPetsResponse(w http.ResponseWriter) error -} - -type GetPets200JSONResponse externalRef0.Pet - -func (response GetPets200JSONResponse) VisitGetPetsResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(200) - - return json.NewEncoder(w).Encode(response) -} - -// StrictServerInterface represents all server handlers. -type StrictServerInterface interface { - - // (GET /pets) - GetPets(ctx context.Context, request GetPetsRequestObject) (GetPetsResponseObject, error) -} - -type StrictHandlerFunc = strictgin.StrictGinHandlerFunc -type StrictMiddlewareFunc = strictgin.StrictGinMiddlewareFunc - -func NewStrictHandler(ssi StrictServerInterface, middlewares []StrictMiddlewareFunc) ServerInterface { - return &strictHandler{ssi: ssi, middlewares: middlewares} -} - -type strictHandler struct { - ssi StrictServerInterface - middlewares []StrictMiddlewareFunc -} - -// GetPets operation middleware -func (sh *strictHandler) GetPets(ctx *gin.Context) { - var request GetPetsRequestObject - - handler := func(ctx *gin.Context, request interface{}) (interface{}, error) { - return sh.ssi.GetPets(ctx, request.(GetPetsRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "GetPets") - } - - response, err := handler(ctx, request) - - if err != nil { - ctx.Error(err) - ctx.Status(http.StatusInternalServerError) - } else if validResponse, ok := response.(GetPetsResponseObject); ok { - if err := validResponse.VisitGetPetsResponse(ctx.Writer); err != nil { - ctx.Error(err) - } - } else if response != nil { - ctx.Error(fmt.Errorf("unexpected response type: %T", response)) - } -} - -// Base64 encoded, gzipped, json marshaled Swagger object -var swaggerSpec = []string{ - - "H4sIAAAAAAAC/2xRwW7bMAz9FYHb0Yi97aYfGHYLht7SoFBlOlZgSyxJFwgC/3tBuUEaoCeR9uPj43tX", - "iGWmkjGrgL+CxBHnUEsKjFlf9qi140LImrD+y2FGe/VCCB5EOeUTrA1oOH3zfW2A8W1JjD34wzZ9bG6o", - "8nrGqLAaLOWhGEGPEjmRppLBw9OYxMUxTb0TwujSTIVV3Fx6nMQNXGanI7pNcsVAA5p0Mv46CA28I8vG", - "92vXmdhCmAMl8PBn1+06aICCjvXAlnAz5LSd/6jnP+rCWRyh3pfLRRStDFr7RZDdGMSFGFHEaXnOUJdy", - "MJ5/PXj4i7q3TWaQUMmy+fu76+yJJSvmKiAQTSnWwfYspuIWllU/GQfw8KO9p9l+Rtl+ybFa/HhKcLJU", - "fcMyuZsGAxpUkM008IcrLDyBh3Yzcz2uHwEAAP//SKTQrDoCAAA=", -} - -// GetSwagger returns the content of the embedded swagger specification file -// or error if failed to decode -func decodeSpec() ([]byte, error) { - zipped, err := base64.StdEncoding.DecodeString(strings.Join(swaggerSpec, "")) - if err != nil { - return nil, fmt.Errorf("error base64 decoding spec: %w", err) - } - zr, err := gzip.NewReader(bytes.NewReader(zipped)) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - var buf bytes.Buffer - _, err = buf.ReadFrom(zr) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - - return buf.Bytes(), nil -} - -var rawSpec = decodeSpecCached() - -// a naive cached of a decoded swagger spec -func decodeSpecCached() func() ([]byte, error) { - data, err := decodeSpec() - return func() ([]byte, error) { - return data, err - } -} - -// Constructs a synthetic filesystem for resolving external references when loading openapi specifications. -func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { - res := make(map[string]func() ([]byte, error)) - if len(pathToFile) > 0 { - res[pathToFile] = rawSpec - } - - for rawPath, rawFunc := range externalRef0.PathToRawSpec(path.Join(path.Dir(pathToFile), "parent.api.yaml")) { - if _, ok := res[rawPath]; ok { - // it is not possible to compare functions in golang, so always overwrite the old value - } - res[rawPath] = rawFunc - } - return res -} - -// GetSwagger returns the Swagger specification corresponding to the generated code -// in this file. The external references of Swagger specification are resolved. -// The logic of resolving external references is tightly connected to "import-mapping" feature. -// Externally referenced files must be embedded in the corresponding golang packages. -// Urls can be supported but this task was out of the scope. -func GetSwagger() (swagger *openapi3.T, err error) { - resolvePath := PathToRawSpec("") - - loader := openapi3.NewLoader() - loader.IsExternalRefsAllowed = true - loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() - pathToFile = path.Clean(pathToFile) - getSpec, ok := resolvePath[pathToFile] - if !ok { - err1 := fmt.Errorf("path not found: %s", pathToFile) - return nil, err1 - } - return getSpec() - } - var specData []byte - specData, err = rawSpec() - if err != nil { - return - } - swagger, err = loader.LoadFromData(specData) - if err != nil { - return - } - return -} diff --git a/internal/test/issues/issue-1093/api/parent/parent.gen.go b/internal/test/issues/issue-1093/api/parent/parent.gen.go deleted file mode 100644 index 916772b07d..0000000000 --- a/internal/test/issues/issue-1093/api/parent/parent.gen.go +++ /dev/null @@ -1,229 +0,0 @@ -// Package api provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package api - -import ( - "bytes" - "compress/gzip" - "context" - "encoding/base64" - "encoding/json" - "fmt" - "net/http" - "net/url" - "path" - "strings" - - "github.com/getkin/kin-openapi/openapi3" - "github.com/gin-gonic/gin" - strictgin "github.com/oapi-codegen/runtime/strictmiddleware/gin" -) - -// Pet defines model for Pet. -type Pet struct { - Name string `json:"name"` - Tag *string `json:"tag,omitempty"` -} - -// ServerInterface represents all server handlers. -type ServerInterface interface { - - // (GET /pets) - GetPets(c *gin.Context) -} - -// ServerInterfaceWrapper converts contexts to parameters. -type ServerInterfaceWrapper struct { - Handler ServerInterface - HandlerMiddlewares []MiddlewareFunc - ErrorHandler func(*gin.Context, error, int) -} - -type MiddlewareFunc func(c *gin.Context) - -// GetPets operation middleware -func (siw *ServerInterfaceWrapper) GetPets(c *gin.Context) { - - for _, middleware := range siw.HandlerMiddlewares { - middleware(c) - if c.IsAborted() { - return - } - } - - siw.Handler.GetPets(c) -} - -// GinServerOptions provides options for the Gin server. -type GinServerOptions struct { - BaseURL string - Middlewares []MiddlewareFunc - ErrorHandler func(*gin.Context, error, int) -} - -// RegisterHandlers creates http.Handler with routing matching OpenAPI spec. -func RegisterHandlers(router gin.IRouter, si ServerInterface) { - RegisterHandlersWithOptions(router, si, GinServerOptions{}) -} - -// RegisterHandlersWithOptions creates http.Handler with additional options -func RegisterHandlersWithOptions(router gin.IRouter, si ServerInterface, options GinServerOptions) { - errorHandler := options.ErrorHandler - if errorHandler == nil { - errorHandler = func(c *gin.Context, err error, statusCode int) { - c.JSON(statusCode, gin.H{"msg": err.Error()}) - } - } - - wrapper := ServerInterfaceWrapper{ - Handler: si, - HandlerMiddlewares: options.Middlewares, - ErrorHandler: errorHandler, - } - - router.GET(options.BaseURL+"/pets", wrapper.GetPets) -} - -type GetPetsRequestObject struct { -} - -type GetPetsResponseObject interface { - VisitGetPetsResponse(w http.ResponseWriter) error -} - -type GetPets200JSONResponse Pet - -func (response GetPets200JSONResponse) VisitGetPetsResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(200) - - return json.NewEncoder(w).Encode(response) -} - -// StrictServerInterface represents all server handlers. -type StrictServerInterface interface { - - // (GET /pets) - GetPets(ctx context.Context, request GetPetsRequestObject) (GetPetsResponseObject, error) -} - -type StrictHandlerFunc = strictgin.StrictGinHandlerFunc -type StrictMiddlewareFunc = strictgin.StrictGinMiddlewareFunc - -func NewStrictHandler(ssi StrictServerInterface, middlewares []StrictMiddlewareFunc) ServerInterface { - return &strictHandler{ssi: ssi, middlewares: middlewares} -} - -type strictHandler struct { - ssi StrictServerInterface - middlewares []StrictMiddlewareFunc -} - -// GetPets operation middleware -func (sh *strictHandler) GetPets(ctx *gin.Context) { - var request GetPetsRequestObject - - handler := func(ctx *gin.Context, request interface{}) (interface{}, error) { - return sh.ssi.GetPets(ctx, request.(GetPetsRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "GetPets") - } - - response, err := handler(ctx, request) - - if err != nil { - ctx.Error(err) - ctx.Status(http.StatusInternalServerError) - } else if validResponse, ok := response.(GetPetsResponseObject); ok { - if err := validResponse.VisitGetPetsResponse(ctx.Writer); err != nil { - ctx.Error(err) - } - } else if response != nil { - ctx.Error(fmt.Errorf("unexpected response type: %T", response)) - } -} - -// Base64 encoded, gzipped, json marshaled Swagger object -var swaggerSpec = []string{ - - "H4sIAAAAAAAC/2xRwa7TMBD8FWvhGDUBbv4BxO0JcXv04Dqb2lViL7sbUBXl39E6rVAlTru2xjPjmQ1i", - "XagWLCrgN5CYcAltfUO1QVwJWTO2yxIWtKl3QvAgyrlcYe9Aw/U/93sHjL/WzDiCfz9en7snql5uGBV2", - "g+UyVSMYUSJn0lwLePiRsjgKjEWdEEaXgriljjiL+5NyTC4wurxQZcXRXe5OE7qY8jw2PHSgWWcTO1ig", - "g9/IcrB/Og1mvRKWQBk8fDkNpwE6oKCpfbcnPHK5HmG8uvuOunIRR6hu4ro0cbmLoq1B23kV5GY7xIgi", - "TuvPAk2Ug/F8G8HDV9Q3U7K4hGqRI+3Pw2Aj1qLm3W8QiOYc28P+Jubi2ZltHxkn8PCh/1dq/2i0tzpb", - "0q9/CE7WZmxaZ/cUN6BBBdnSAv++wcozeOgfMe7n/W8AAAD///mNvoM7AgAA", -} - -// GetSwagger returns the content of the embedded swagger specification file -// or error if failed to decode -func decodeSpec() ([]byte, error) { - zipped, err := base64.StdEncoding.DecodeString(strings.Join(swaggerSpec, "")) - if err != nil { - return nil, fmt.Errorf("error base64 decoding spec: %w", err) - } - zr, err := gzip.NewReader(bytes.NewReader(zipped)) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - var buf bytes.Buffer - _, err = buf.ReadFrom(zr) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - - return buf.Bytes(), nil -} - -var rawSpec = decodeSpecCached() - -// a naive cached of a decoded swagger spec -func decodeSpecCached() func() ([]byte, error) { - data, err := decodeSpec() - return func() ([]byte, error) { - return data, err - } -} - -// Constructs a synthetic filesystem for resolving external references when loading openapi specifications. -func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { - res := make(map[string]func() ([]byte, error)) - if len(pathToFile) > 0 { - res[pathToFile] = rawSpec - } - - return res -} - -// GetSwagger returns the Swagger specification corresponding to the generated code -// in this file. The external references of Swagger specification are resolved. -// The logic of resolving external references is tightly connected to "import-mapping" feature. -// Externally referenced files must be embedded in the corresponding golang packages. -// Urls can be supported but this task was out of the scope. -func GetSwagger() (swagger *openapi3.T, err error) { - resolvePath := PathToRawSpec("") - - loader := openapi3.NewLoader() - loader.IsExternalRefsAllowed = true - loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() - pathToFile = path.Clean(pathToFile) - getSpec, ok := resolvePath[pathToFile] - if !ok { - err1 := fmt.Errorf("path not found: %s", pathToFile) - return nil, err1 - } - return getSpec() - } - var specData []byte - specData, err = rawSpec() - if err != nil { - return - } - swagger, err = loader.LoadFromData(specData) - if err != nil { - return - } - return -} diff --git a/internal/test/issues/issue-1093/child.api.yaml b/internal/test/issues/issue-1093/child.api.yaml deleted file mode 100644 index c373c1ec2a..0000000000 --- a/internal/test/issues/issue-1093/child.api.yaml +++ /dev/null @@ -1,21 +0,0 @@ -# child.api.yaml -openapi: 3.0.0 -info: - description: >- - This child spec imports models from the parent spec - title: child - version: "1.0" -servers: - - url: /child -paths: - /pets: - get: - description: | - Returns pet from the system that the user has access to - responses: - '200': - description: a successful response - content: - application/json: - schema: - $ref: "parent.api.yaml#/components/schemas/Pet" \ No newline at end of file diff --git a/internal/test/issues/issue-1093/child.cfg.yaml b/internal/test/issues/issue-1093/child.cfg.yaml deleted file mode 100644 index 4efb750c1e..0000000000 --- a/internal/test/issues/issue-1093/child.cfg.yaml +++ /dev/null @@ -1,11 +0,0 @@ -# yaml-language-server: $schema=../../../../configuration-schema.json -# child.yaml -package: api -generate: - gin-server: true - embedded-spec: true - strict-server: true - models: true -import-mapping: - parent.api.yaml: github.com/oapi-codegen/oapi-codegen/v2/internal/test/issues/issue-1093/api/parent -output: api/child/child.gen.go diff --git a/internal/test/issues/issue-1093/doc.go b/internal/test/issues/issue-1093/doc.go deleted file mode 100644 index 6996cdd2d8..0000000000 --- a/internal/test/issues/issue-1093/doc.go +++ /dev/null @@ -1,6 +0,0 @@ -// This is an example of how to reference models of one api specification from another. -// See https://github.com/oapi-codegen/oapi-codegen/issues/1093 -package issue1093 - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config parent.cfg.yaml parent.api.yaml -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config child.cfg.yaml child.api.yaml diff --git a/internal/test/issues/issue-1093/issue_test.go b/internal/test/issues/issue-1093/issue_test.go deleted file mode 100644 index 990de85384..0000000000 --- a/internal/test/issues/issue-1093/issue_test.go +++ /dev/null @@ -1,38 +0,0 @@ -package issue1093 - -import ( - _ "embed" - "testing" - - "github.com/getkin/kin-openapi/openapi3" - "github.com/stretchr/testify/require" - - "github.com/oapi-codegen/oapi-codegen/v2/pkg/codegen" -) - -//go:embed child.api.yaml -var spec []byte - -func TestIssue(t *testing.T) { - loader := openapi3.NewLoader() - loader.IsExternalRefsAllowed = true - - swagger, err := loader.LoadFromData(spec) - require.NoError(t, err) - - opts := codegen.Configuration{ - PackageName: "issue1093", - Generate: codegen.GenerateOptions{ - GinServer: true, - Strict: true, - Models: true, - EmbeddedSpec: true, - }, - ImportMapping: map[string]string{ - "parent.api.yaml": "github.com/oapi-codegen/oapi-codegen/v2/internal/test/issues/issue-1093/api/parent", - }, - } - - _, err = codegen.Generate(swagger, opts) - require.NoError(t, err) -} diff --git a/internal/test/issues/issue-1093/parent.api.yaml b/internal/test/issues/issue-1093/parent.api.yaml deleted file mode 100644 index 95687168a9..0000000000 --- a/internal/test/issues/issue-1093/parent.api.yaml +++ /dev/null @@ -1,32 +0,0 @@ -# parent.api.yaml -openapi: 3.0.0 -info: - description: >- - This parent spec has models which are imported by the child spec - title: parent - version: "1.0" -servers: - - url: /parent -paths: - /pets: - get: - description: | - Returns pet from the system that the user has access to - responses: - '200': - description: a successful response - content: - application/json: - schema: - $ref: "#/components/schemas/Pet" -components: - schemas: - Pet: - type: object - required: - - name - properties: - name: - type: string - tag: - type: string \ No newline at end of file diff --git a/internal/test/issues/issue-1093/parent.cfg.yaml b/internal/test/issues/issue-1093/parent.cfg.yaml deleted file mode 100644 index ef00a99d61..0000000000 --- a/internal/test/issues/issue-1093/parent.cfg.yaml +++ /dev/null @@ -1,10 +0,0 @@ -# yaml-language-server: $schema=../../../../configuration-schema.json -package: api -generate: - gin-server: true - embedded-spec: true - strict-server: true - models: true -output: api/parent/parent.gen.go -output-options: - skip-prune: true diff --git a/internal/test/issues/issue-1127/api.gen.go b/internal/test/issues/issue-1127/api.gen.go deleted file mode 100644 index d3fa8e4293..0000000000 --- a/internal/test/issues/issue-1127/api.gen.go +++ /dev/null @@ -1,18 +0,0 @@ -// Package issue1127 provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package issue1127 - -// Whatever defines model for Whatever. -type Whatever struct { - SomeProperty *string `json:"someProperty,omitempty"` -} - -// CreateWhateverApplicationWildcardPlusJSONRequestBody defines body for CreateWhatever for application/*+json ContentType. -type CreateWhateverApplicationWildcardPlusJSONRequestBody = Whatever - -// CreateWhateverJSONRequestBody defines body for CreateWhatever for application/json ContentType. -type CreateWhateverJSONRequestBody = Whatever - -// CreateWhateverApplicationJSONPatchPlusJSONRequestBody defines body for CreateWhatever for application/json-patch+json ContentType. -type CreateWhateverApplicationJSONPatchPlusJSONRequestBody = Whatever diff --git a/internal/test/issues/issue-1127/doc.go b/internal/test/issues/issue-1127/doc.go deleted file mode 100644 index d591e52f84..0000000000 --- a/internal/test/issues/issue-1127/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -package issue1127 - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=server.config.yaml spec.yaml diff --git a/internal/test/issues/issue-1127/spec.yaml b/internal/test/issues/issue-1127/spec.yaml deleted file mode 100644 index e3eee06627..0000000000 --- a/internal/test/issues/issue-1127/spec.yaml +++ /dev/null @@ -1,42 +0,0 @@ -openapi: 3.0.1 -info: - title: api - version: "0.1.0" -paths: - /whatever: - post: - operationId: CreateWhatever - requestBody: - content: - application/json-patch+json: - schema: - $ref: "#/components/schemas/Whatever" - application/json: - schema: - $ref: "#/components/schemas/Whatever" - text/json: - schema: - $ref: "#/components/schemas/Whatever" - application/*+json: - schema: - $ref: "#/components/schemas/Whatever" - responses: - 201: - description: Whatever created - content: - text/plain: - schema: - $ref: "#/components/schemas/Whatever" - application/json: - schema: - $ref: "#/components/schemas/Whatever" - text/json: - schema: - $ref: "#/components/schemas/Whatever" -components: - schemas: - Whatever: - type: object - properties: - someProperty: - type: string diff --git a/internal/test/issues/issue-1168/api.gen.go b/internal/test/issues/issue-1168/api.gen.go deleted file mode 100644 index d681fbd81c..0000000000 --- a/internal/test/issues/issue-1168/api.gen.go +++ /dev/null @@ -1,162 +0,0 @@ -// Package issue1168 provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package issue1168 - -import ( - "encoding/json" - "fmt" -) - -// ProblemDetails defines model for ProblemDetails. -type ProblemDetails struct { - // Detail A human readable explanation specific to this occurrence of the problem. - Detail *string `json:"detail,omitempty"` - - // Instance An absolute URI that identifies the specific occurrence of the problem. It may or may not yield further information if dereferenced. - Instance *string `json:"instance,omitempty"` - - // Status The HTTP status code generated by the origin server for this occurrence of the problem. - Status *int32 `json:"status,omitempty"` - - // Title A short, summary of the problem type. Written in english and readable for engineers (usually not suited for non technical stakeholders and not localized); example: Service Unavailable - Title *string `json:"title,omitempty"` - - // Type An absolute URI that identifies the problem type. When dereferenced, it SHOULD provide human-readable documentation for the problem type (e.g., using HTML). - Type *string `json:"type,omitempty"` - AdditionalProperties map[string]interface{} `json:"-"` -} - -// Misc400Error defines model for Misc400Error. -type Misc400Error = ProblemDetails - -// Misc404Error defines model for Misc404Error. -type Misc404Error = ProblemDetails - -// Getter for additional properties for ProblemDetails. Returns the specified -// element and whether it was found -func (a ProblemDetails) Get(fieldName string) (value interface{}, found bool) { - if a.AdditionalProperties != nil { - value, found = a.AdditionalProperties[fieldName] - } - return -} - -// Setter for additional properties for ProblemDetails -func (a *ProblemDetails) Set(fieldName string, value interface{}) { - if a.AdditionalProperties == nil { - a.AdditionalProperties = make(map[string]interface{}) - } - a.AdditionalProperties[fieldName] = value -} - -// Override default JSON handling for ProblemDetails to handle AdditionalProperties -func (a *ProblemDetails) UnmarshalJSON(b []byte) error { - object := make(map[string]json.RawMessage) - err := json.Unmarshal(b, &object) - if err != nil { - return err - } - - if raw, found := object["detail"]; found { - err = json.Unmarshal(raw, &a.Detail) - if err != nil { - return fmt.Errorf("error reading 'detail': %w", err) - } - delete(object, "detail") - } - - if raw, found := object["instance"]; found { - err = json.Unmarshal(raw, &a.Instance) - if err != nil { - return fmt.Errorf("error reading 'instance': %w", err) - } - delete(object, "instance") - } - - if raw, found := object["status"]; found { - err = json.Unmarshal(raw, &a.Status) - if err != nil { - return fmt.Errorf("error reading 'status': %w", err) - } - delete(object, "status") - } - - if raw, found := object["title"]; found { - err = json.Unmarshal(raw, &a.Title) - if err != nil { - return fmt.Errorf("error reading 'title': %w", err) - } - delete(object, "title") - } - - if raw, found := object["type"]; found { - err = json.Unmarshal(raw, &a.Type) - if err != nil { - return fmt.Errorf("error reading 'type': %w", err) - } - delete(object, "type") - } - - if len(object) != 0 { - a.AdditionalProperties = make(map[string]interface{}) - for fieldName, fieldBuf := range object { - var fieldVal interface{} - err := json.Unmarshal(fieldBuf, &fieldVal) - if err != nil { - return fmt.Errorf("error unmarshaling field %s: %w", fieldName, err) - } - a.AdditionalProperties[fieldName] = fieldVal - } - } - return nil -} - -// Override default JSON handling for ProblemDetails to handle AdditionalProperties -func (a ProblemDetails) MarshalJSON() ([]byte, error) { - var err error - object := make(map[string]json.RawMessage) - - if a.Detail != nil { - object["detail"], err = json.Marshal(a.Detail) - if err != nil { - return nil, fmt.Errorf("error marshaling 'detail': %w", err) - } - } - - if a.Instance != nil { - object["instance"], err = json.Marshal(a.Instance) - if err != nil { - return nil, fmt.Errorf("error marshaling 'instance': %w", err) - } - } - - if a.Status != nil { - object["status"], err = json.Marshal(a.Status) - if err != nil { - return nil, fmt.Errorf("error marshaling 'status': %w", err) - } - } - - if a.Title != nil { - object["title"], err = json.Marshal(a.Title) - if err != nil { - return nil, fmt.Errorf("error marshaling 'title': %w", err) - } - } - - if a.Type != nil { - object["type"], err = json.Marshal(a.Type) - if err != nil { - return nil, fmt.Errorf("error marshaling 'type': %w", err) - } - } - - for fieldName, field := range a.AdditionalProperties { - object[fieldName], err = json.Marshal(field) - if err != nil { - return nil, fmt.Errorf("error marshaling '%s': %w", fieldName, err) - } - } - return json.Marshal(object) -} diff --git a/internal/test/issues/issue-1168/doc.go b/internal/test/issues/issue-1168/doc.go deleted file mode 100644 index 2541e721d1..0000000000 --- a/internal/test/issues/issue-1168/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -package issue1168 - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=server.config.yaml spec.yaml diff --git a/internal/test/issues/issue-1168/spec.yaml b/internal/test/issues/issue-1168/spec.yaml deleted file mode 100644 index 72af583253..0000000000 --- a/internal/test/issues/issue-1168/spec.yaml +++ /dev/null @@ -1,95 +0,0 @@ ---- -# Copyright 2023 Coros, Corp. All Rights Reserved. -# -# Apache 2.0 Licensed; the portion included from -# https://github.com/zalando/problem/ is MIT licensed -# -openapi: 3.0.3 -info: - version: 1.0.0 - title: Test - description: Provides access to things - license: - name: Apache License 2.0 - url: http://www.example.com/XXX - -servers: - - url: https://www.example.com/api - description: Production environment - -paths: - /v1/test: - get: - summary: Get it - responses: - '200': - description: Successful response - content: - text/plain: - type: string - '400': - $ref: '#/components/responses/Misc400Error' - '404': - $ref: '#/components/responses/Misc404Error' - -components: - responses: - Misc400Error: - description: Bad request - content: - application/problem+json: - schema: - $ref: '#/components/schemas/ProblemDetails' - Misc404Error: - description: Not found - content: - application/problem+json: - schema: - $ref: '#/components/schemas/ProblemDetails' - - schemas: - # Fetched from https://opensource.zalando.com/problem/schema.yaml - # and slightly modified. - # Part of https://github.com/zalando/problem/; MIT License - ProblemDetails: - type: object - additionalProperties: true - properties: - type: - type: string - format: uri - description: >- - An absolute URI that identifies the problem type. When dereferenced, - it SHOULD provide human-readable documentation for the problem type - (e.g., using HTML). - default: 'about:blank' - example: 'https://zalando.github.io/problem/constraint-violation' - title: - type: string - description: >- - A short, summary of the problem type. Written in english and readable - for engineers (usually not suited for non technical stakeholders and - not localized); example: Service Unavailable - status: - type: integer - format: int32 - description: >- - The HTTP status code generated by the origin server for this occurrence - of the problem. - minimum: 100 - maximum: 600 - exclusiveMaximum: true - example: 503 - detail: - type: string - description: >- - A human readable explanation specific to this occurrence of the - problem. - example: Connection to database timed out - instance: - type: string - format: uri - description: >- - An absolute URI that identifies the specific occurrence of the problem. - It may or may not yield further information if dereferenced. - # diff --git a/internal/test/issues/issue-1180/config.yaml b/internal/test/issues/issue-1180/config.yaml deleted file mode 100644 index f8f01372f9..0000000000 --- a/internal/test/issues/issue-1180/config.yaml +++ /dev/null @@ -1,8 +0,0 @@ -# yaml-language-server: $schema=../../../../configuration-schema.json -package: issue1180 -generate: - echo-server: true - client: true - models: true - embedded-spec: true -output: issue.gen.go diff --git a/internal/test/issues/issue-1180/doc.go b/internal/test/issues/issue-1180/doc.go deleted file mode 100644 index 5fcca2b965..0000000000 --- a/internal/test/issues/issue-1180/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -package issue1180 - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml issue.yaml diff --git a/internal/test/issues/issue-1180/issue.gen.go b/internal/test/issues/issue-1180/issue.gen.go deleted file mode 100644 index 26e358477a..0000000000 --- a/internal/test/issues/issue-1180/issue.gen.go +++ /dev/null @@ -1,380 +0,0 @@ -// Package issue1180 provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package issue1180 - -import ( - "bytes" - "compress/gzip" - "context" - "encoding/base64" - "fmt" - "io" - "net/http" - "net/url" - "path" - "strings" - - "github.com/getkin/kin-openapi/openapi3" - "github.com/labstack/echo/v4" - "github.com/oapi-codegen/runtime" -) - -// RequestEditorFn is the function signature for the RequestEditor callback function -type RequestEditorFn func(ctx context.Context, req *http.Request) error - -// Doer performs HTTP requests. -// -// The standard http.Client implements this interface. -type HttpRequestDoer interface { - Do(req *http.Request) (*http.Response, error) -} - -// Client which conforms to the OpenAPI3 specification for this service. -type Client struct { - // The endpoint of the server conforming to this interface, with scheme, - // https://api.deepmap.com for example. This can contain a path relative - // to the server, such as https://api.deepmap.com/dev-test, and all the - // paths in the swagger spec will be appended to the server. - Server string - - // Doer for performing requests, typically a *http.Client with any - // customized settings, such as certificate chains. - Client HttpRequestDoer - - // A list of callbacks for modifying requests which are generated before sending over - // the network. - RequestEditors []RequestEditorFn -} - -// ClientOption allows setting custom parameters during construction -type ClientOption func(*Client) error - -// Creates a new Client, with reasonable defaults -func NewClient(server string, opts ...ClientOption) (*Client, error) { - // create a client with sane default values - client := Client{ - Server: server, - } - // mutate client and add all optional params - for _, o := range opts { - if err := o(&client); err != nil { - return nil, err - } - } - // ensure the server URL always has a trailing slash - if !strings.HasSuffix(client.Server, "/") { - client.Server += "/" - } - // create httpClient, if not already present - if client.Client == nil { - client.Client = &http.Client{} - } - return &client, nil -} - -// WithHTTPClient allows overriding the default Doer, which is -// automatically created using http.Client. This is useful for tests. -func WithHTTPClient(doer HttpRequestDoer) ClientOption { - return func(c *Client) error { - c.Client = doer - return nil - } -} - -// WithRequestEditorFn allows setting up a callback function, which will be -// called right before sending the request. This can be used to mutate the request. -func WithRequestEditorFn(fn RequestEditorFn) ClientOption { - return func(c *Client) error { - c.RequestEditors = append(c.RequestEditors, fn) - return nil - } -} - -// The interface specification for the client above. -type ClientInterface interface { - // GetSimplePrimitive request - GetSimplePrimitive(ctx context.Context, param string, reqEditors ...RequestEditorFn) (*http.Response, error) -} - -func (c *Client) GetSimplePrimitive(ctx context.Context, param string, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewGetSimplePrimitiveRequest(c.Server, param) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -// NewGetSimplePrimitiveRequest generates requests for GetSimplePrimitive -func NewGetSimplePrimitiveRequest(server string, param string) (*http.Request, error) { - var err error - - var pathParam0 string - - pathParam0, err = runtime.StyleParamWithOptions("simple", false, "param", param, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: "int32"}) - if err != nil { - return nil, err - } - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/simplePrimitive/%s", pathParam0) - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -func (c *Client) applyEditors(ctx context.Context, req *http.Request, additionalEditors []RequestEditorFn) error { - for _, r := range c.RequestEditors { - if err := r(ctx, req); err != nil { - return err - } - } - for _, r := range additionalEditors { - if err := r(ctx, req); err != nil { - return err - } - } - return nil -} - -// ClientWithResponses builds on ClientInterface to offer response payloads -type ClientWithResponses struct { - ClientInterface -} - -// NewClientWithResponses creates a new ClientWithResponses, which wraps -// Client with return type handling -func NewClientWithResponses(server string, opts ...ClientOption) (*ClientWithResponses, error) { - client, err := NewClient(server, opts...) - if err != nil { - return nil, err - } - return &ClientWithResponses{client}, nil -} - -// WithBaseURL overrides the baseURL. -func WithBaseURL(baseURL string) ClientOption { - return func(c *Client) error { - newBaseURL, err := url.Parse(baseURL) - if err != nil { - return err - } - c.Server = newBaseURL.String() - return nil - } -} - -// ClientWithResponsesInterface is the interface specification for the client with responses above. -type ClientWithResponsesInterface interface { - // GetSimplePrimitiveWithResponse request - GetSimplePrimitiveWithResponse(ctx context.Context, param string, reqEditors ...RequestEditorFn) (*GetSimplePrimitiveResponse, error) -} - -type GetSimplePrimitiveResponse struct { - Body []byte - HTTPResponse *http.Response -} - -// Status returns HTTPResponse.Status -func (r GetSimplePrimitiveResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r GetSimplePrimitiveResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -// GetSimplePrimitiveWithResponse request returning *GetSimplePrimitiveResponse -func (c *ClientWithResponses) GetSimplePrimitiveWithResponse(ctx context.Context, param string, reqEditors ...RequestEditorFn) (*GetSimplePrimitiveResponse, error) { - rsp, err := c.GetSimplePrimitive(ctx, param, reqEditors...) - if err != nil { - return nil, err - } - return ParseGetSimplePrimitiveResponse(rsp) -} - -// ParseGetSimplePrimitiveResponse parses an HTTP response from a GetSimplePrimitiveWithResponse call -func ParseGetSimplePrimitiveResponse(rsp *http.Response) (*GetSimplePrimitiveResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &GetSimplePrimitiveResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - return response, nil -} - -// ServerInterface represents all server handlers. -type ServerInterface interface { - - // (GET /simplePrimitive/{param}) - GetSimplePrimitive(ctx echo.Context, param string) error -} - -// ServerInterfaceWrapper converts echo contexts to parameters. -type ServerInterfaceWrapper struct { - Handler ServerInterface -} - -// GetSimplePrimitive converts echo context to params. -func (w *ServerInterfaceWrapper) GetSimplePrimitive(ctx echo.Context) error { - var err error - // ------------- Path parameter "param" ------------- - var param string - - err = runtime.BindStyledParameterWithOptions("simple", "param", ctx.Param("param"), ¶m, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: "int32"}) - if err != nil { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter param: %s", err)) - } - - // Invoke the callback with all the unmarshaled arguments - err = w.Handler.GetSimplePrimitive(ctx, param) - return err -} - -// This is a simple interface which specifies echo.Route addition functions which -// are present on both echo.Echo and echo.Group, since we want to allow using -// either of them for path registration -type EchoRouter interface { - CONNECT(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - DELETE(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - GET(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - HEAD(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - OPTIONS(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - PATCH(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - POST(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - PUT(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - TRACE(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route -} - -// RegisterHandlers adds each server route to the EchoRouter. -func RegisterHandlers(router EchoRouter, si ServerInterface) { - RegisterHandlersWithBaseURL(router, si, "") -} - -// Registers handlers, and prepends BaseURL to the paths, so that the paths -// can be served under a prefix. -func RegisterHandlersWithBaseURL(router EchoRouter, si ServerInterface, baseURL string) { - - wrapper := ServerInterfaceWrapper{ - Handler: si, - } - - router.GET(baseURL+"/simplePrimitive/:param", wrapper.GetSimplePrimitive) - -} - -// Base64 encoded, gzipped, json marshaled Swagger object -var swaggerSpec = []string{ - - "H4sIAAAAAAAC/7RRPY/TQBD9K9aDcuX13XXbUaErkBC5DlEs9iQZ5P1gdhJxsvzf0a4TIBHtVfbMzrz3", - "5r0FYwo5RYpa4BYIlZxioVbsOOSZvlxatTOmqBS1/ir9Uptnz7FWZTxS8K3/mgkORYXjAeu6GkxURuGs", - "nCIcPnSl4XZXri59/0GjbrMc96nCzDzShTT6UBE/Pb9gNVDWuZYvVLTbkZxJYHAmKRv8Qz/0Qx1MmaLP", - "DIenfugfYJC9HtthdlPwWTiw8pnskr34sNa3A7XzUibxVfHzBIePpLvblQYnPpCSFLivC6oRjQLmKrlN", - "wEDo54mFJjiVE5l/3NonCV7hwFGfHmHu7TMo+tru3SRj/WZuQ3ochvp5L7SHwzv7N0/7Z87eJdmcfkv5", - "HJUOJP/VX7lLy20jPskMh6NqdtZeQlMq2k9EOfjce65bvwMAAP//QUrtxqoCAAA=", -} - -// GetSwagger returns the content of the embedded swagger specification file -// or error if failed to decode -func decodeSpec() ([]byte, error) { - zipped, err := base64.StdEncoding.DecodeString(strings.Join(swaggerSpec, "")) - if err != nil { - return nil, fmt.Errorf("error base64 decoding spec: %w", err) - } - zr, err := gzip.NewReader(bytes.NewReader(zipped)) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - var buf bytes.Buffer - _, err = buf.ReadFrom(zr) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - - return buf.Bytes(), nil -} - -var rawSpec = decodeSpecCached() - -// a naive cached of a decoded swagger spec -func decodeSpecCached() func() ([]byte, error) { - data, err := decodeSpec() - return func() ([]byte, error) { - return data, err - } -} - -// Constructs a synthetic filesystem for resolving external references when loading openapi specifications. -func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { - res := make(map[string]func() ([]byte, error)) - if len(pathToFile) > 0 { - res[pathToFile] = rawSpec - } - - return res -} - -// GetSwagger returns the Swagger specification corresponding to the generated code -// in this file. The external references of Swagger specification are resolved. -// The logic of resolving external references is tightly connected to "import-mapping" feature. -// Externally referenced files must be embedded in the corresponding golang packages. -// Urls can be supported but this task was out of the scope. -func GetSwagger() (swagger *openapi3.T, err error) { - resolvePath := PathToRawSpec("") - - loader := openapi3.NewLoader() - loader.IsExternalRefsAllowed = true - loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() - pathToFile = path.Clean(pathToFile) - getSpec, ok := resolvePath[pathToFile] - if !ok { - err1 := fmt.Errorf("path not found: %s", pathToFile) - return nil, err1 - } - return getSpec() - } - var specData []byte - specData, err = rawSpec() - if err != nil { - return - } - swagger, err = loader.LoadFromData(specData) - if err != nil { - return - } - return -} diff --git a/internal/test/issues/issue-1180/issue_test.go b/internal/test/issues/issue-1180/issue_test.go deleted file mode 100644 index 096e41d566..0000000000 --- a/internal/test/issues/issue-1180/issue_test.go +++ /dev/null @@ -1,10 +0,0 @@ -package issue1180 - -import ( - "testing" -) - -// TestIssue1180 validates that the parameter `param` is a string type, rather than an int, as we should prioritise the `param` definition closest to the path -func TestIssue1180(t *testing.T) { - _, _ = NewGetSimplePrimitiveRequest("http://example.com/", "test-string") -} diff --git a/internal/test/issues/issue-1182/pkg1.yaml b/internal/test/issues/issue-1182/pkg1.yaml deleted file mode 100644 index b216d2d85a..0000000000 --- a/internal/test/issues/issue-1182/pkg1.yaml +++ /dev/null @@ -1,16 +0,0 @@ -openapi: "3.0.1" -info: - version: 1.0.0 - title: Test Server - license: - name: MIT -servers: - - url: http://openapitest.deepmap.ai -paths: - /test: - get: - summary: get test response - operationId: TestGet - responses: - '200': - $ref: "pkg2.yaml#/components/responses/ResponseWithReference" diff --git a/internal/test/issues/issue-1182/pkg1/config.yaml b/internal/test/issues/issue-1182/pkg1/config.yaml deleted file mode 100644 index a300242fbc..0000000000 --- a/internal/test/issues/issue-1182/pkg1/config.yaml +++ /dev/null @@ -1,11 +0,0 @@ -# yaml-language-server: $schema=../../../../../configuration-schema.json -package: pkg1 -generate: - echo-server: true - client: true - models: true - embedded-spec: true - strict-server: true -output: pkg1.gen.go -import-mapping: - pkg2.yaml: github.com/oapi-codegen/oapi-codegen/v2/internal/test/issues/issue-1182/pkg2 diff --git a/internal/test/issues/issue-1182/pkg1/doc.go b/internal/test/issues/issue-1182/pkg1/doc.go deleted file mode 100644 index 8b57f0836f..0000000000 --- a/internal/test/issues/issue-1182/pkg1/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -package pkg1 - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml ../pkg1.yaml diff --git a/internal/test/issues/issue-1182/pkg1/pkg1.gen.go b/internal/test/issues/issue-1182/pkg1/pkg1.gen.go deleted file mode 100644 index 0b01c5738e..0000000000 --- a/internal/test/issues/issue-1182/pkg1/pkg1.gen.go +++ /dev/null @@ -1,428 +0,0 @@ -// Package pkg1 provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package pkg1 - -import ( - "bytes" - "compress/gzip" - "context" - "encoding/base64" - "fmt" - "io" - "net/http" - "net/url" - "path" - "strings" - - "github.com/getkin/kin-openapi/openapi3" - "github.com/labstack/echo/v4" - externalRef0 "github.com/oapi-codegen/oapi-codegen/v2/internal/test/issues/issue-1182/pkg2" - strictecho "github.com/oapi-codegen/runtime/strictmiddleware/echo" -) - -// RequestEditorFn is the function signature for the RequestEditor callback function -type RequestEditorFn func(ctx context.Context, req *http.Request) error - -// Doer performs HTTP requests. -// -// The standard http.Client implements this interface. -type HttpRequestDoer interface { - Do(req *http.Request) (*http.Response, error) -} - -// Client which conforms to the OpenAPI3 specification for this service. -type Client struct { - // The endpoint of the server conforming to this interface, with scheme, - // https://api.deepmap.com for example. This can contain a path relative - // to the server, such as https://api.deepmap.com/dev-test, and all the - // paths in the swagger spec will be appended to the server. - Server string - - // Doer for performing requests, typically a *http.Client with any - // customized settings, such as certificate chains. - Client HttpRequestDoer - - // A list of callbacks for modifying requests which are generated before sending over - // the network. - RequestEditors []RequestEditorFn -} - -// ClientOption allows setting custom parameters during construction -type ClientOption func(*Client) error - -// Creates a new Client, with reasonable defaults -func NewClient(server string, opts ...ClientOption) (*Client, error) { - // create a client with sane default values - client := Client{ - Server: server, - } - // mutate client and add all optional params - for _, o := range opts { - if err := o(&client); err != nil { - return nil, err - } - } - // ensure the server URL always has a trailing slash - if !strings.HasSuffix(client.Server, "/") { - client.Server += "/" - } - // create httpClient, if not already present - if client.Client == nil { - client.Client = &http.Client{} - } - return &client, nil -} - -// WithHTTPClient allows overriding the default Doer, which is -// automatically created using http.Client. This is useful for tests. -func WithHTTPClient(doer HttpRequestDoer) ClientOption { - return func(c *Client) error { - c.Client = doer - return nil - } -} - -// WithRequestEditorFn allows setting up a callback function, which will be -// called right before sending the request. This can be used to mutate the request. -func WithRequestEditorFn(fn RequestEditorFn) ClientOption { - return func(c *Client) error { - c.RequestEditors = append(c.RequestEditors, fn) - return nil - } -} - -// The interface specification for the client above. -type ClientInterface interface { - // TestGet request - TestGet(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) -} - -func (c *Client) TestGet(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewTestGetRequest(c.Server) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -// NewTestGetRequest generates requests for TestGet -func NewTestGetRequest(server string) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/test") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -func (c *Client) applyEditors(ctx context.Context, req *http.Request, additionalEditors []RequestEditorFn) error { - for _, r := range c.RequestEditors { - if err := r(ctx, req); err != nil { - return err - } - } - for _, r := range additionalEditors { - if err := r(ctx, req); err != nil { - return err - } - } - return nil -} - -// ClientWithResponses builds on ClientInterface to offer response payloads -type ClientWithResponses struct { - ClientInterface -} - -// NewClientWithResponses creates a new ClientWithResponses, which wraps -// Client with return type handling -func NewClientWithResponses(server string, opts ...ClientOption) (*ClientWithResponses, error) { - client, err := NewClient(server, opts...) - if err != nil { - return nil, err - } - return &ClientWithResponses{client}, nil -} - -// WithBaseURL overrides the baseURL. -func WithBaseURL(baseURL string) ClientOption { - return func(c *Client) error { - newBaseURL, err := url.Parse(baseURL) - if err != nil { - return err - } - c.Server = newBaseURL.String() - return nil - } -} - -// ClientWithResponsesInterface is the interface specification for the client with responses above. -type ClientWithResponsesInterface interface { - // TestGetWithResponse request - TestGetWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*TestGetResponse, error) -} - -type TestGetResponse struct { - Body []byte - HTTPResponse *http.Response -} - -// Status returns HTTPResponse.Status -func (r TestGetResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r TestGetResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -// TestGetWithResponse request returning *TestGetResponse -func (c *ClientWithResponses) TestGetWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*TestGetResponse, error) { - rsp, err := c.TestGet(ctx, reqEditors...) - if err != nil { - return nil, err - } - return ParseTestGetResponse(rsp) -} - -// ParseTestGetResponse parses an HTTP response from a TestGetWithResponse call -func ParseTestGetResponse(rsp *http.Response) (*TestGetResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &TestGetResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - return response, nil -} - -// ServerInterface represents all server handlers. -type ServerInterface interface { - // get test response - // (GET /test) - TestGet(ctx echo.Context) error -} - -// ServerInterfaceWrapper converts echo contexts to parameters. -type ServerInterfaceWrapper struct { - Handler ServerInterface -} - -// TestGet converts echo context to params. -func (w *ServerInterfaceWrapper) TestGet(ctx echo.Context) error { - var err error - - // Invoke the callback with all the unmarshaled arguments - err = w.Handler.TestGet(ctx) - return err -} - -// This is a simple interface which specifies echo.Route addition functions which -// are present on both echo.Echo and echo.Group, since we want to allow using -// either of them for path registration -type EchoRouter interface { - CONNECT(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - DELETE(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - GET(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - HEAD(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - OPTIONS(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - PATCH(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - POST(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - PUT(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - TRACE(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route -} - -// RegisterHandlers adds each server route to the EchoRouter. -func RegisterHandlers(router EchoRouter, si ServerInterface) { - RegisterHandlersWithBaseURL(router, si, "") -} - -// Registers handlers, and prepends BaseURL to the paths, so that the paths -// can be served under a prefix. -func RegisterHandlersWithBaseURL(router EchoRouter, si ServerInterface, baseURL string) { - - wrapper := ServerInterfaceWrapper{ - Handler: si, - } - - router.GET(baseURL+"/test", wrapper.TestGet) - -} - -type TestGetRequestObject struct { -} - -type TestGetResponseObject interface { - VisitTestGetResponse(w http.ResponseWriter) error -} - -type TestGet200Response externalRef0.ResponseWithReferenceResponse - -func (response TestGet200Response) VisitTestGetResponse(w http.ResponseWriter) error { - w.WriteHeader(200) - return nil -} - -// StrictServerInterface represents all server handlers. -type StrictServerInterface interface { - // get test response - // (GET /test) - TestGet(ctx context.Context, request TestGetRequestObject) (TestGetResponseObject, error) -} - -type StrictHandlerFunc = strictecho.StrictEchoHandlerFunc -type StrictMiddlewareFunc = strictecho.StrictEchoMiddlewareFunc - -func NewStrictHandler(ssi StrictServerInterface, middlewares []StrictMiddlewareFunc) ServerInterface { - return &strictHandler{ssi: ssi, middlewares: middlewares} -} - -type strictHandler struct { - ssi StrictServerInterface - middlewares []StrictMiddlewareFunc -} - -// TestGet operation middleware -func (sh *strictHandler) TestGet(ctx echo.Context) error { - var request TestGetRequestObject - - handler := func(ctx echo.Context, request interface{}) (interface{}, error) { - return sh.ssi.TestGet(ctx.Request().Context(), request.(TestGetRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "TestGet") - } - - response, err := handler(ctx, request) - - if err != nil { - return err - } else if validResponse, ok := response.(TestGetResponseObject); ok { - return validResponse.VisitTestGetResponse(ctx.Response()) - } else if response != nil { - return fmt.Errorf("unexpected response type: %T", response) - } - return nil -} - -// Base64 encoded, gzipped, json marshaled Swagger object -var swaggerSpec = []string{ - - "H4sIAAAAAAAC/3yQMU/DMBCF/4r1YIyStGzemFAHllKJASFknJfGtLEt+1qEqvx35LQUsTCdz3fv7r53", - "gg1jDJ5eMvQJiTkGnzkncbddvq0vP89OhjV7JnrLUu2YbXJRXPDQuFc/UhXeP2hFfQ7ODspllYoqsVMS", - "VJ/CqIwPMjCpaOzObIlpmio434cydu8sfZ43eDMSGo+rDaYK4mRf0g2zqCemIxMqHJny+YJF3dZtaQyR", - "3kQHjbu6rReoEI0MM1EjzFIeW84hRCZTCFbdZfIDBdVfG5ZtW8JtYg+Nm+bXseba1/zjVaHLh3E06Qu6", - "bFbliqtfZ/w8A2XolxMOaQ+NQSTqprnQFEndkXE0sTYO0+v0HQAA//9bF49xvAEAAA==", -} - -// GetSwagger returns the content of the embedded swagger specification file -// or error if failed to decode -func decodeSpec() ([]byte, error) { - zipped, err := base64.StdEncoding.DecodeString(strings.Join(swaggerSpec, "")) - if err != nil { - return nil, fmt.Errorf("error base64 decoding spec: %w", err) - } - zr, err := gzip.NewReader(bytes.NewReader(zipped)) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - var buf bytes.Buffer - _, err = buf.ReadFrom(zr) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - - return buf.Bytes(), nil -} - -var rawSpec = decodeSpecCached() - -// a naive cached of a decoded swagger spec -func decodeSpecCached() func() ([]byte, error) { - data, err := decodeSpec() - return func() ([]byte, error) { - return data, err - } -} - -// Constructs a synthetic filesystem for resolving external references when loading openapi specifications. -func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { - res := make(map[string]func() ([]byte, error)) - if len(pathToFile) > 0 { - res[pathToFile] = rawSpec - } - - for rawPath, rawFunc := range externalRef0.PathToRawSpec(path.Join(path.Dir(pathToFile), "pkg2.yaml")) { - if _, ok := res[rawPath]; ok { - // it is not possible to compare functions in golang, so always overwrite the old value - } - res[rawPath] = rawFunc - } - return res -} - -// GetSwagger returns the Swagger specification corresponding to the generated code -// in this file. The external references of Swagger specification are resolved. -// The logic of resolving external references is tightly connected to "import-mapping" feature. -// Externally referenced files must be embedded in the corresponding golang packages. -// Urls can be supported but this task was out of the scope. -func GetSwagger() (swagger *openapi3.T, err error) { - resolvePath := PathToRawSpec("") - - loader := openapi3.NewLoader() - loader.IsExternalRefsAllowed = true - loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() - pathToFile = path.Clean(pathToFile) - getSpec, ok := resolvePath[pathToFile] - if !ok { - err1 := fmt.Errorf("path not found: %s", pathToFile) - return nil, err1 - } - return getSpec() - } - var specData []byte - specData, err = rawSpec() - if err != nil { - return - } - swagger, err = loader.LoadFromData(specData) - if err != nil { - return - } - return -} diff --git a/internal/test/issues/issue-1182/pkg2.yaml b/internal/test/issues/issue-1182/pkg2.yaml deleted file mode 100644 index 6819d9f7a1..0000000000 --- a/internal/test/issues/issue-1182/pkg2.yaml +++ /dev/null @@ -1,12 +0,0 @@ -openapi: "3.0.1" -info: - version: 1.0.0 - title: Test Server - license: - name: MIT -servers: - - url: http://openapitest.deepmap.ai -components: - responses: - ResponseWithReference: - description: A response object which is referred to from another package diff --git a/internal/test/issues/issue-1182/pkg2/doc.go b/internal/test/issues/issue-1182/pkg2/doc.go deleted file mode 100644 index 68cb0b78a1..0000000000 --- a/internal/test/issues/issue-1182/pkg2/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -package pkg2 - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml ../pkg2.yaml diff --git a/internal/test/issues/issue-1182/pkg2/pkg2.gen.go b/internal/test/issues/issue-1182/pkg2/pkg2.gen.go deleted file mode 100644 index 51eece40aa..0000000000 --- a/internal/test/issues/issue-1182/pkg2/pkg2.gen.go +++ /dev/null @@ -1,275 +0,0 @@ -// Package pkg2 provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package pkg2 - -import ( - "bytes" - "compress/gzip" - "context" - "encoding/base64" - "fmt" - "net/http" - "net/url" - "path" - "strings" - - "github.com/getkin/kin-openapi/openapi3" - "github.com/labstack/echo/v4" - strictecho "github.com/oapi-codegen/runtime/strictmiddleware/echo" -) - -// RequestEditorFn is the function signature for the RequestEditor callback function -type RequestEditorFn func(ctx context.Context, req *http.Request) error - -// Doer performs HTTP requests. -// -// The standard http.Client implements this interface. -type HttpRequestDoer interface { - Do(req *http.Request) (*http.Response, error) -} - -// Client which conforms to the OpenAPI3 specification for this service. -type Client struct { - // The endpoint of the server conforming to this interface, with scheme, - // https://api.deepmap.com for example. This can contain a path relative - // to the server, such as https://api.deepmap.com/dev-test, and all the - // paths in the swagger spec will be appended to the server. - Server string - - // Doer for performing requests, typically a *http.Client with any - // customized settings, such as certificate chains. - Client HttpRequestDoer - - // A list of callbacks for modifying requests which are generated before sending over - // the network. - RequestEditors []RequestEditorFn -} - -// ClientOption allows setting custom parameters during construction -type ClientOption func(*Client) error - -// Creates a new Client, with reasonable defaults -func NewClient(server string, opts ...ClientOption) (*Client, error) { - // create a client with sane default values - client := Client{ - Server: server, - } - // mutate client and add all optional params - for _, o := range opts { - if err := o(&client); err != nil { - return nil, err - } - } - // ensure the server URL always has a trailing slash - if !strings.HasSuffix(client.Server, "/") { - client.Server += "/" - } - // create httpClient, if not already present - if client.Client == nil { - client.Client = &http.Client{} - } - return &client, nil -} - -// WithHTTPClient allows overriding the default Doer, which is -// automatically created using http.Client. This is useful for tests. -func WithHTTPClient(doer HttpRequestDoer) ClientOption { - return func(c *Client) error { - c.Client = doer - return nil - } -} - -// WithRequestEditorFn allows setting up a callback function, which will be -// called right before sending the request. This can be used to mutate the request. -func WithRequestEditorFn(fn RequestEditorFn) ClientOption { - return func(c *Client) error { - c.RequestEditors = append(c.RequestEditors, fn) - return nil - } -} - -// The interface specification for the client above. -type ClientInterface interface { -} - -func (c *Client) applyEditors(ctx context.Context, req *http.Request, additionalEditors []RequestEditorFn) error { - for _, r := range c.RequestEditors { - if err := r(ctx, req); err != nil { - return err - } - } - for _, r := range additionalEditors { - if err := r(ctx, req); err != nil { - return err - } - } - return nil -} - -// ClientWithResponses builds on ClientInterface to offer response payloads -type ClientWithResponses struct { - ClientInterface -} - -// NewClientWithResponses creates a new ClientWithResponses, which wraps -// Client with return type handling -func NewClientWithResponses(server string, opts ...ClientOption) (*ClientWithResponses, error) { - client, err := NewClient(server, opts...) - if err != nil { - return nil, err - } - return &ClientWithResponses{client}, nil -} - -// WithBaseURL overrides the baseURL. -func WithBaseURL(baseURL string) ClientOption { - return func(c *Client) error { - newBaseURL, err := url.Parse(baseURL) - if err != nil { - return err - } - c.Server = newBaseURL.String() - return nil - } -} - -// ClientWithResponsesInterface is the interface specification for the client with responses above. -type ClientWithResponsesInterface interface { -} - -// ServerInterface represents all server handlers. -type ServerInterface interface { -} - -// ServerInterfaceWrapper converts echo contexts to parameters. -type ServerInterfaceWrapper struct { - Handler ServerInterface -} - -// This is a simple interface which specifies echo.Route addition functions which -// are present on both echo.Echo and echo.Group, since we want to allow using -// either of them for path registration -type EchoRouter interface { - CONNECT(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - DELETE(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - GET(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - HEAD(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - OPTIONS(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - PATCH(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - POST(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - PUT(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - TRACE(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route -} - -// RegisterHandlers adds each server route to the EchoRouter. -func RegisterHandlers(router EchoRouter, si ServerInterface) { - RegisterHandlersWithBaseURL(router, si, "") -} - -// Registers handlers, and prepends BaseURL to the paths, so that the paths -// can be served under a prefix. -func RegisterHandlersWithBaseURL(router EchoRouter, si ServerInterface, baseURL string) { - -} - -type ResponseWithReferenceResponse struct { -} - -// StrictServerInterface represents all server handlers. -type StrictServerInterface interface { -} - -type StrictHandlerFunc = strictecho.StrictEchoHandlerFunc -type StrictMiddlewareFunc = strictecho.StrictEchoMiddlewareFunc - -func NewStrictHandler(ssi StrictServerInterface, middlewares []StrictMiddlewareFunc) ServerInterface { - return &strictHandler{ssi: ssi, middlewares: middlewares} -} - -type strictHandler struct { - ssi StrictServerInterface - middlewares []StrictMiddlewareFunc -} - -// Base64 encoded, gzipped, json marshaled Swagger object -var swaggerSpec = []string{ - - "H4sIAAAAAAAC/zSOMU/DMBSE/4p1c+S2YvPGyMBSKjEgBuNcsCGxLb/XMkT+7yihjJ/e++5uRShLLZlZ", - "BW5Fo9SShTuc7/CaNJ45sTEHboeRElqqmkqGw6P5t0z5+GJQ8xNTiCaJaZvVOBotZmplMT4XjWym+vDt", - "P4ne+4CUp7LFzikwy96Q/UI4PD9d0Ado0nnDC0XNC9uNDQNubPK34GSP9rg9lsrsa4LDgz3aEwZUr1Hg", - "8nWeB8iuCtzbimub4RBVqzsc7p5S1I5kXXy1PqG/998AAAD//4Nm84whAQAA", -} - -// GetSwagger returns the content of the embedded swagger specification file -// or error if failed to decode -func decodeSpec() ([]byte, error) { - zipped, err := base64.StdEncoding.DecodeString(strings.Join(swaggerSpec, "")) - if err != nil { - return nil, fmt.Errorf("error base64 decoding spec: %w", err) - } - zr, err := gzip.NewReader(bytes.NewReader(zipped)) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - var buf bytes.Buffer - _, err = buf.ReadFrom(zr) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - - return buf.Bytes(), nil -} - -var rawSpec = decodeSpecCached() - -// a naive cached of a decoded swagger spec -func decodeSpecCached() func() ([]byte, error) { - data, err := decodeSpec() - return func() ([]byte, error) { - return data, err - } -} - -// Constructs a synthetic filesystem for resolving external references when loading openapi specifications. -func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { - res := make(map[string]func() ([]byte, error)) - if len(pathToFile) > 0 { - res[pathToFile] = rawSpec - } - - return res -} - -// GetSwagger returns the Swagger specification corresponding to the generated code -// in this file. The external references of Swagger specification are resolved. -// The logic of resolving external references is tightly connected to "import-mapping" feature. -// Externally referenced files must be embedded in the corresponding golang packages. -// Urls can be supported but this task was out of the scope. -func GetSwagger() (swagger *openapi3.T, err error) { - resolvePath := PathToRawSpec("") - - loader := openapi3.NewLoader() - loader.IsExternalRefsAllowed = true - loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() - pathToFile = path.Clean(pathToFile) - getSpec, ok := resolvePath[pathToFile] - if !ok { - err1 := fmt.Errorf("path not found: %s", pathToFile) - return nil, err1 - } - return getSpec() - } - var specData []byte - specData, err = rawSpec() - if err != nil { - return - } - swagger, err = loader.LoadFromData(specData) - if err != nil { - return - } - return -} diff --git a/internal/test/issues/issue-1189/config.yaml b/internal/test/issues/issue-1189/config.yaml deleted file mode 100644 index ddc5076566..0000000000 --- a/internal/test/issues/issue-1189/config.yaml +++ /dev/null @@ -1,8 +0,0 @@ -# yaml-language-server: $schema=../../../../configuration-schema.json -package: param -generate: - echo-server: true - client: true - models: true - embedded-spec: true -output: issue1189.gen.go diff --git a/internal/test/issues/issue-1189/doc.go b/internal/test/issues/issue-1189/doc.go deleted file mode 100644 index e64506f488..0000000000 --- a/internal/test/issues/issue-1189/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -package param - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml issue1189.yaml diff --git a/internal/test/issues/issue-1189/issue1189.gen.go b/internal/test/issues/issue-1189/issue1189.gen.go deleted file mode 100644 index c6e0579fd5..0000000000 --- a/internal/test/issues/issue-1189/issue1189.gen.go +++ /dev/null @@ -1,586 +0,0 @@ -// Package param provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package param - -import ( - "bytes" - "compress/gzip" - "context" - "encoding/base64" - "encoding/json" - "fmt" - "io" - "net/http" - "net/url" - "path" - "strings" - - "github.com/getkin/kin-openapi/openapi3" - "github.com/labstack/echo/v4" - "github.com/oapi-codegen/runtime" -) - -// Defines values for TestFieldA1. -const ( - TestFieldA1Bar TestFieldA1 = "bar" - TestFieldA1Foo TestFieldA1 = "foo" -) - -// Valid indicates whether the value is a known member of the TestFieldA1 enum. -func (e TestFieldA1) Valid() bool { - switch e { - case TestFieldA1Bar: - return true - case TestFieldA1Foo: - return true - default: - return false - } -} - -// Defines values for TestFieldB. -const ( - TestFieldBBar TestFieldB = "bar" - TestFieldBFoo TestFieldB = "foo" -) - -// Valid indicates whether the value is a known member of the TestFieldB enum. -func (e TestFieldB) Valid() bool { - switch e { - case TestFieldBBar: - return true - case TestFieldBFoo: - return true - default: - return false - } -} - -// Defines values for TestFieldC1. -const ( - Bar TestFieldC1 = "bar" - Foo TestFieldC1 = "foo" -) - -// Valid indicates whether the value is a known member of the TestFieldC1 enum. -func (e TestFieldC1) Valid() bool { - switch e { - case Bar: - return true - case Foo: - return true - default: - return false - } -} - -// Test defines model for test. -type Test struct { - FieldA *Test_FieldA `json:"fieldA,omitempty"` - FieldB *TestFieldB `json:"fieldB,omitempty"` - FieldC *Test_FieldC `json:"fieldC,omitempty"` -} - -// TestFieldA0 defines model for . -type TestFieldA0 = string - -// TestFieldA1 defines model for Test.FieldA.1. -type TestFieldA1 string - -// Test_FieldA defines model for Test.FieldA. -type Test_FieldA struct { - union json.RawMessage -} - -// TestFieldB defines model for Test.FieldB. -type TestFieldB string - -// TestFieldC0 defines model for . -type TestFieldC0 = string - -// TestFieldC1 defines model for Test.FieldC.1. -type TestFieldC1 string - -// Test_FieldC defines model for Test.FieldC. -type Test_FieldC struct { - union json.RawMessage -} - -// AsTestFieldA0 returns the union data inside the Test_FieldA as a TestFieldA0 -func (t Test_FieldA) AsTestFieldA0() (TestFieldA0, error) { - var body TestFieldA0 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromTestFieldA0 overwrites any union data inside the Test_FieldA as the provided TestFieldA0 -func (t *Test_FieldA) FromTestFieldA0(v TestFieldA0) error { - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeTestFieldA0 performs a merge with any union data inside the Test_FieldA, using the provided TestFieldA0 -func (t *Test_FieldA) MergeTestFieldA0(v TestFieldA0) error { - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -// AsTestFieldA1 returns the union data inside the Test_FieldA as a TestFieldA1 -func (t Test_FieldA) AsTestFieldA1() (TestFieldA1, error) { - var body TestFieldA1 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromTestFieldA1 overwrites any union data inside the Test_FieldA as the provided TestFieldA1 -func (t *Test_FieldA) FromTestFieldA1(v TestFieldA1) error { - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeTestFieldA1 performs a merge with any union data inside the Test_FieldA, using the provided TestFieldA1 -func (t *Test_FieldA) MergeTestFieldA1(v TestFieldA1) error { - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -func (t Test_FieldA) MarshalJSON() ([]byte, error) { - b, err := t.union.MarshalJSON() - return b, err -} - -func (t *Test_FieldA) UnmarshalJSON(b []byte) error { - err := t.union.UnmarshalJSON(b) - return err -} - -// AsTestFieldC0 returns the union data inside the Test_FieldC as a TestFieldC0 -func (t Test_FieldC) AsTestFieldC0() (TestFieldC0, error) { - var body TestFieldC0 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromTestFieldC0 overwrites any union data inside the Test_FieldC as the provided TestFieldC0 -func (t *Test_FieldC) FromTestFieldC0(v TestFieldC0) error { - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeTestFieldC0 performs a merge with any union data inside the Test_FieldC, using the provided TestFieldC0 -func (t *Test_FieldC) MergeTestFieldC0(v TestFieldC0) error { - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -// AsTestFieldC1 returns the union data inside the Test_FieldC as a TestFieldC1 -func (t Test_FieldC) AsTestFieldC1() (TestFieldC1, error) { - var body TestFieldC1 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromTestFieldC1 overwrites any union data inside the Test_FieldC as the provided TestFieldC1 -func (t *Test_FieldC) FromTestFieldC1(v TestFieldC1) error { - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeTestFieldC1 performs a merge with any union data inside the Test_FieldC, using the provided TestFieldC1 -func (t *Test_FieldC) MergeTestFieldC1(v TestFieldC1) error { - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -func (t Test_FieldC) MarshalJSON() ([]byte, error) { - b, err := t.union.MarshalJSON() - return b, err -} - -func (t *Test_FieldC) UnmarshalJSON(b []byte) error { - err := t.union.UnmarshalJSON(b) - return err -} - -// RequestEditorFn is the function signature for the RequestEditor callback function -type RequestEditorFn func(ctx context.Context, req *http.Request) error - -// Doer performs HTTP requests. -// -// The standard http.Client implements this interface. -type HttpRequestDoer interface { - Do(req *http.Request) (*http.Response, error) -} - -// Client which conforms to the OpenAPI3 specification for this service. -type Client struct { - // The endpoint of the server conforming to this interface, with scheme, - // https://api.deepmap.com for example. This can contain a path relative - // to the server, such as https://api.deepmap.com/dev-test, and all the - // paths in the swagger spec will be appended to the server. - Server string - - // Doer for performing requests, typically a *http.Client with any - // customized settings, such as certificate chains. - Client HttpRequestDoer - - // A list of callbacks for modifying requests which are generated before sending over - // the network. - RequestEditors []RequestEditorFn -} - -// ClientOption allows setting custom parameters during construction -type ClientOption func(*Client) error - -// Creates a new Client, with reasonable defaults -func NewClient(server string, opts ...ClientOption) (*Client, error) { - // create a client with sane default values - client := Client{ - Server: server, - } - // mutate client and add all optional params - for _, o := range opts { - if err := o(&client); err != nil { - return nil, err - } - } - // ensure the server URL always has a trailing slash - if !strings.HasSuffix(client.Server, "/") { - client.Server += "/" - } - // create httpClient, if not already present - if client.Client == nil { - client.Client = &http.Client{} - } - return &client, nil -} - -// WithHTTPClient allows overriding the default Doer, which is -// automatically created using http.Client. This is useful for tests. -func WithHTTPClient(doer HttpRequestDoer) ClientOption { - return func(c *Client) error { - c.Client = doer - return nil - } -} - -// WithRequestEditorFn allows setting up a callback function, which will be -// called right before sending the request. This can be used to mutate the request. -func WithRequestEditorFn(fn RequestEditorFn) ClientOption { - return func(c *Client) error { - c.RequestEditors = append(c.RequestEditors, fn) - return nil - } -} - -// The interface specification for the client above. -type ClientInterface interface { - // Test request - Test(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) -} - -func (c *Client) Test(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewTestRequest(c.Server) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -// NewTestRequest generates requests for Test -func NewTestRequest(server string) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/test") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -func (c *Client) applyEditors(ctx context.Context, req *http.Request, additionalEditors []RequestEditorFn) error { - for _, r := range c.RequestEditors { - if err := r(ctx, req); err != nil { - return err - } - } - for _, r := range additionalEditors { - if err := r(ctx, req); err != nil { - return err - } - } - return nil -} - -// ClientWithResponses builds on ClientInterface to offer response payloads -type ClientWithResponses struct { - ClientInterface -} - -// NewClientWithResponses creates a new ClientWithResponses, which wraps -// Client with return type handling -func NewClientWithResponses(server string, opts ...ClientOption) (*ClientWithResponses, error) { - client, err := NewClient(server, opts...) - if err != nil { - return nil, err - } - return &ClientWithResponses{client}, nil -} - -// WithBaseURL overrides the baseURL. -func WithBaseURL(baseURL string) ClientOption { - return func(c *Client) error { - newBaseURL, err := url.Parse(baseURL) - if err != nil { - return err - } - c.Server = newBaseURL.String() - return nil - } -} - -// ClientWithResponsesInterface is the interface specification for the client with responses above. -type ClientWithResponsesInterface interface { - // TestWithResponse request - TestWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*TestResponse, error) -} - -type TestResponse struct { - Body []byte - HTTPResponse *http.Response - JSON200 *Test -} - -// Status returns HTTPResponse.Status -func (r TestResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r TestResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -// TestWithResponse request returning *TestResponse -func (c *ClientWithResponses) TestWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*TestResponse, error) { - rsp, err := c.Test(ctx, reqEditors...) - if err != nil { - return nil, err - } - return ParseTestResponse(rsp) -} - -// ParseTestResponse parses an HTTP response from a TestWithResponse call -func ParseTestResponse(rsp *http.Response) (*TestResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &TestResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest Test - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON200 = &dest - - } - - return response, nil -} - -// ServerInterface represents all server handlers. -type ServerInterface interface { - - // (GET /test) - Test(ctx echo.Context) error -} - -// ServerInterfaceWrapper converts echo contexts to parameters. -type ServerInterfaceWrapper struct { - Handler ServerInterface -} - -// Test converts echo context to params. -func (w *ServerInterfaceWrapper) Test(ctx echo.Context) error { - var err error - - // Invoke the callback with all the unmarshaled arguments - err = w.Handler.Test(ctx) - return err -} - -// This is a simple interface which specifies echo.Route addition functions which -// are present on both echo.Echo and echo.Group, since we want to allow using -// either of them for path registration -type EchoRouter interface { - CONNECT(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - DELETE(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - GET(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - HEAD(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - OPTIONS(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - PATCH(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - POST(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - PUT(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - TRACE(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route -} - -// RegisterHandlers adds each server route to the EchoRouter. -func RegisterHandlers(router EchoRouter, si ServerInterface) { - RegisterHandlersWithBaseURL(router, si, "") -} - -// Registers handlers, and prepends BaseURL to the paths, so that the paths -// can be served under a prefix. -func RegisterHandlersWithBaseURL(router EchoRouter, si ServerInterface, baseURL string) { - - wrapper := ServerInterfaceWrapper{ - Handler: si, - } - - router.GET(baseURL+"/test", wrapper.Test) - -} - -// Base64 encoded, gzipped, json marshaled Swagger object -var swaggerSpec = []string{ - - "H4sIAAAAAAAC/6yRsU4zMRCE32X+v7RyJ+jcARUVDV2UwlzWiZFvd2Vviuh0747sI4pEC9vMyPZ+lmYW", - "TDKrMLFV+AV1OtMcujWq1lSLKBVL1E9jonx8ai7w9S3C7xfYVQke1UriE1a3gPgyw+8RReDwEQoO7uez", - "w+o22nOn5fw3tJdGE6Zf0to4JI4Cz5ecHUSJgyZ4PO7G3QgHDXbuoQy3rE7UpQUWLAm/HuHx3i4dClUV", - "rluMD+PYZBI24r4TVHOa+tbwWYXvbTT3v1CEx7/hXtfw3dX2+XqbrwAAAP//gr+fh9IBAAA=", -} - -// GetSwagger returns the content of the embedded swagger specification file -// or error if failed to decode -func decodeSpec() ([]byte, error) { - zipped, err := base64.StdEncoding.DecodeString(strings.Join(swaggerSpec, "")) - if err != nil { - return nil, fmt.Errorf("error base64 decoding spec: %w", err) - } - zr, err := gzip.NewReader(bytes.NewReader(zipped)) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - var buf bytes.Buffer - _, err = buf.ReadFrom(zr) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - - return buf.Bytes(), nil -} - -var rawSpec = decodeSpecCached() - -// a naive cached of a decoded swagger spec -func decodeSpecCached() func() ([]byte, error) { - data, err := decodeSpec() - return func() ([]byte, error) { - return data, err - } -} - -// Constructs a synthetic filesystem for resolving external references when loading openapi specifications. -func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { - res := make(map[string]func() ([]byte, error)) - if len(pathToFile) > 0 { - res[pathToFile] = rawSpec - } - - return res -} - -// GetSwagger returns the Swagger specification corresponding to the generated code -// in this file. The external references of Swagger specification are resolved. -// The logic of resolving external references is tightly connected to "import-mapping" feature. -// Externally referenced files must be embedded in the corresponding golang packages. -// Urls can be supported but this task was out of the scope. -func GetSwagger() (swagger *openapi3.T, err error) { - resolvePath := PathToRawSpec("") - - loader := openapi3.NewLoader() - loader.IsExternalRefsAllowed = true - loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() - pathToFile = path.Clean(pathToFile) - getSpec, ok := resolvePath[pathToFile] - if !ok { - err1 := fmt.Errorf("path not found: %s", pathToFile) - return nil, err1 - } - return getSpec() - } - var specData []byte - specData, err = rawSpec() - if err != nil { - return - } - swagger, err = loader.LoadFromData(specData) - if err != nil { - return - } - return -} diff --git a/internal/test/issues/issue-1189/issue1189.yaml b/internal/test/issues/issue-1189/issue1189.yaml deleted file mode 100644 index e84bcea034..0000000000 --- a/internal/test/issues/issue-1189/issue1189.yaml +++ /dev/null @@ -1,36 +0,0 @@ -openapi: 3.0.0 -paths: - /test: - get: - operationId: Test - responses: - "200": - content: - application/json: - schema: - $ref: '#/components/schemas/test' -components: - schemas: - test: - properties: - fieldA: - anyOf: - - type: string - - type: string - enum: - - foo - - bar - fieldB: - allOf: - - type: string - - type: string - enum: - - foo - - bar - fieldC: - oneOf: - - type: string - - type: string - enum: - - foo - - bar diff --git a/internal/test/issues/issue-1208-1209/config.yaml b/internal/test/issues/issue-1208-1209/config.yaml deleted file mode 100644 index 52a520aa38..0000000000 --- a/internal/test/issues/issue-1208-1209/config.yaml +++ /dev/null @@ -1,9 +0,0 @@ -# yaml-language-server: $schema=../../../../configuration-schema.json -package: multijson -generate: - client: true - models: true - embedded-spec: true - gin-server: true - strict-server: true -output: issue-multi-json.gen.go diff --git a/internal/test/issues/issue-1208-1209/doc.go b/internal/test/issues/issue-1208-1209/doc.go deleted file mode 100644 index 7384a2ab9f..0000000000 --- a/internal/test/issues/issue-1208-1209/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -package multijson - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml issue-multi-json.yaml diff --git a/internal/test/issues/issue-1208-1209/issue-multi-json.gen.go b/internal/test/issues/issue-1208-1209/issue-multi-json.gen.go deleted file mode 100644 index 780d45e6a7..0000000000 --- a/internal/test/issues/issue-1208-1209/issue-multi-json.gen.go +++ /dev/null @@ -1,516 +0,0 @@ -// Package multijson provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package multijson - -import ( - "bytes" - "compress/gzip" - "context" - "encoding/base64" - "encoding/json" - "fmt" - "io" - "net/http" - "net/url" - "path" - "strings" - - "github.com/getkin/kin-openapi/openapi3" - "github.com/gin-gonic/gin" - strictgin "github.com/oapi-codegen/runtime/strictmiddleware/gin" -) - -// Bar defines model for bar. -type Bar struct { - Field2 *string `json:"field2,omitempty"` -} - -// Foo defines model for foo. -type Foo struct { - Field1 *string `json:"field1,omitempty"` -} - -// BazApplicationBarPlusJSON defines model for baz. -type BazApplicationBarPlusJSON = Bar - -// BazApplicationFooPlusJSON defines model for baz. -type BazApplicationFooPlusJSON = Foo - -// RequestEditorFn is the function signature for the RequestEditor callback function -type RequestEditorFn func(ctx context.Context, req *http.Request) error - -// Doer performs HTTP requests. -// -// The standard http.Client implements this interface. -type HttpRequestDoer interface { - Do(req *http.Request) (*http.Response, error) -} - -// Client which conforms to the OpenAPI3 specification for this service. -type Client struct { - // The endpoint of the server conforming to this interface, with scheme, - // https://api.deepmap.com for example. This can contain a path relative - // to the server, such as https://api.deepmap.com/dev-test, and all the - // paths in the swagger spec will be appended to the server. - Server string - - // Doer for performing requests, typically a *http.Client with any - // customized settings, such as certificate chains. - Client HttpRequestDoer - - // A list of callbacks for modifying requests which are generated before sending over - // the network. - RequestEditors []RequestEditorFn -} - -// ClientOption allows setting custom parameters during construction -type ClientOption func(*Client) error - -// Creates a new Client, with reasonable defaults -func NewClient(server string, opts ...ClientOption) (*Client, error) { - // create a client with sane default values - client := Client{ - Server: server, - } - // mutate client and add all optional params - for _, o := range opts { - if err := o(&client); err != nil { - return nil, err - } - } - // ensure the server URL always has a trailing slash - if !strings.HasSuffix(client.Server, "/") { - client.Server += "/" - } - // create httpClient, if not already present - if client.Client == nil { - client.Client = &http.Client{} - } - return &client, nil -} - -// WithHTTPClient allows overriding the default Doer, which is -// automatically created using http.Client. This is useful for tests. -func WithHTTPClient(doer HttpRequestDoer) ClientOption { - return func(c *Client) error { - c.Client = doer - return nil - } -} - -// WithRequestEditorFn allows setting up a callback function, which will be -// called right before sending the request. This can be used to mutate the request. -func WithRequestEditorFn(fn RequestEditorFn) ClientOption { - return func(c *Client) error { - c.RequestEditors = append(c.RequestEditors, fn) - return nil - } -} - -// The interface specification for the client above. -type ClientInterface interface { - // Test request - Test(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) -} - -func (c *Client) Test(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewTestRequest(c.Server) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -// NewTestRequest generates requests for Test -func NewTestRequest(server string) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/test") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -func (c *Client) applyEditors(ctx context.Context, req *http.Request, additionalEditors []RequestEditorFn) error { - for _, r := range c.RequestEditors { - if err := r(ctx, req); err != nil { - return err - } - } - for _, r := range additionalEditors { - if err := r(ctx, req); err != nil { - return err - } - } - return nil -} - -// ClientWithResponses builds on ClientInterface to offer response payloads -type ClientWithResponses struct { - ClientInterface -} - -// NewClientWithResponses creates a new ClientWithResponses, which wraps -// Client with return type handling -func NewClientWithResponses(server string, opts ...ClientOption) (*ClientWithResponses, error) { - client, err := NewClient(server, opts...) - if err != nil { - return nil, err - } - return &ClientWithResponses{client}, nil -} - -// WithBaseURL overrides the baseURL. -func WithBaseURL(baseURL string) ClientOption { - return func(c *Client) error { - newBaseURL, err := url.Parse(baseURL) - if err != nil { - return err - } - c.Server = newBaseURL.String() - return nil - } -} - -// ClientWithResponsesInterface is the interface specification for the client with responses above. -type ClientWithResponsesInterface interface { - // TestWithResponse request - TestWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*TestResponse, error) -} - -type TestResponse struct { - Body []byte - HTTPResponse *http.Response - ApplicationbarJSON200 *Bar - ApplicationfooJSON200 *Foo - ApplicationbarJSON201 *BazApplicationBarPlusJSON - ApplicationfooJSON201 *BazApplicationFooPlusJSON -} - -// Status returns HTTPResponse.Status -func (r TestResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r TestResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -// TestWithResponse request returning *TestResponse -func (c *ClientWithResponses) TestWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*TestResponse, error) { - rsp, err := c.Test(ctx, reqEditors...) - if err != nil { - return nil, err - } - return ParseTestResponse(rsp) -} - -// ParseTestResponse parses an HTTP response from a TestWithResponse call -func ParseTestResponse(rsp *http.Response) (*TestResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &TestResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - switch { - case rsp.Header.Get("Content-Type") == "application/bar+json" && rsp.StatusCode == 200: - var dest Bar - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.ApplicationbarJSON200 = &dest - - case rsp.Header.Get("Content-Type") == "application/bar+json" && rsp.StatusCode == 201: - var dest BazApplicationBarPlusJSON - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.ApplicationbarJSON201 = &dest - - case rsp.Header.Get("Content-Type") == "application/foo+json" && rsp.StatusCode == 200: - var dest Foo - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.ApplicationfooJSON200 = &dest - - case rsp.Header.Get("Content-Type") == "application/foo+json" && rsp.StatusCode == 201: - var dest BazApplicationFooPlusJSON - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.ApplicationfooJSON201 = &dest - - } - - return response, nil -} - -// ServerInterface represents all server handlers. -type ServerInterface interface { - - // (GET /test) - Test(c *gin.Context) -} - -// ServerInterfaceWrapper converts contexts to parameters. -type ServerInterfaceWrapper struct { - Handler ServerInterface - HandlerMiddlewares []MiddlewareFunc - ErrorHandler func(*gin.Context, error, int) -} - -type MiddlewareFunc func(c *gin.Context) - -// Test operation middleware -func (siw *ServerInterfaceWrapper) Test(c *gin.Context) { - - for _, middleware := range siw.HandlerMiddlewares { - middleware(c) - if c.IsAborted() { - return - } - } - - siw.Handler.Test(c) -} - -// GinServerOptions provides options for the Gin server. -type GinServerOptions struct { - BaseURL string - Middlewares []MiddlewareFunc - ErrorHandler func(*gin.Context, error, int) -} - -// RegisterHandlers creates http.Handler with routing matching OpenAPI spec. -func RegisterHandlers(router gin.IRouter, si ServerInterface) { - RegisterHandlersWithOptions(router, si, GinServerOptions{}) -} - -// RegisterHandlersWithOptions creates http.Handler with additional options -func RegisterHandlersWithOptions(router gin.IRouter, si ServerInterface, options GinServerOptions) { - errorHandler := options.ErrorHandler - if errorHandler == nil { - errorHandler = func(c *gin.Context, err error, statusCode int) { - c.JSON(statusCode, gin.H{"msg": err.Error()}) - } - } - - wrapper := ServerInterfaceWrapper{ - Handler: si, - HandlerMiddlewares: options.Middlewares, - ErrorHandler: errorHandler, - } - - router.GET(options.BaseURL+"/test", wrapper.Test) -} - -type BazApplicationBarPlusJSONResponse Bar -type BazApplicationFooPlusJSONResponse Foo - -type TestRequestObject struct { -} - -type TestResponseObject interface { - VisitTestResponse(w http.ResponseWriter) error -} - -type Test200ApplicationBarPlusJSONResponse Bar - -func (response Test200ApplicationBarPlusJSONResponse) VisitTestResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/bar+json") - w.WriteHeader(200) - - return json.NewEncoder(w).Encode(response) -} - -type Test200ApplicationFooPlusJSONResponse Foo - -func (response Test200ApplicationFooPlusJSONResponse) VisitTestResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/foo+json") - w.WriteHeader(200) - - return json.NewEncoder(w).Encode(response) -} - -type Test201ApplicationBarPlusJSONResponse struct { - BazApplicationBarPlusJSONResponse -} - -func (response Test201ApplicationBarPlusJSONResponse) VisitTestResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/bar+json") - w.WriteHeader(201) - - return json.NewEncoder(w).Encode(response) -} - -type Test201ApplicationFooPlusJSONResponse struct { - BazApplicationFooPlusJSONResponse -} - -func (response Test201ApplicationFooPlusJSONResponse) VisitTestResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/foo+json") - w.WriteHeader(201) - - return json.NewEncoder(w).Encode(response) -} - -// StrictServerInterface represents all server handlers. -type StrictServerInterface interface { - - // (GET /test) - Test(ctx context.Context, request TestRequestObject) (TestResponseObject, error) -} - -type StrictHandlerFunc = strictgin.StrictGinHandlerFunc -type StrictMiddlewareFunc = strictgin.StrictGinMiddlewareFunc - -func NewStrictHandler(ssi StrictServerInterface, middlewares []StrictMiddlewareFunc) ServerInterface { - return &strictHandler{ssi: ssi, middlewares: middlewares} -} - -type strictHandler struct { - ssi StrictServerInterface - middlewares []StrictMiddlewareFunc -} - -// Test operation middleware -func (sh *strictHandler) Test(ctx *gin.Context) { - var request TestRequestObject - - handler := func(ctx *gin.Context, request interface{}) (interface{}, error) { - return sh.ssi.Test(ctx, request.(TestRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "Test") - } - - response, err := handler(ctx, request) - - if err != nil { - ctx.Error(err) - ctx.Status(http.StatusInternalServerError) - } else if validResponse, ok := response.(TestResponseObject); ok { - if err := validResponse.VisitTestResponse(ctx.Writer); err != nil { - ctx.Error(err) - } - } else if response != nil { - ctx.Error(fmt.Errorf("unexpected response type: %T", response)) - } -} - -// Base64 encoded, gzipped, json marshaled Swagger object -var swaggerSpec = []string{ - - "H4sIAAAAAAAC/8ySQU4DMQxF7/JhR9Skwy43YM8F0qnTBk1tKwkLqObuyGkFqlQW7JiNPXHeT/5Xzpjl", - "pMLEvSGeUampcKPxs0ufVmbhTtytTapLmVMvwn6X6tNbE7b1Nh/plKx7rJQR8eB/dP1l2ozAuroblSzy", - "R5UsgtU+dwWud61WtIpS7eViIBda9pN1/UMJEa3XwgcM2HTuE9u7hDGFsyDy+7I4iBInLYh43oRNgIOm", - "fhwqvlMbeR1oFDth2H3ZI+LVhu426imEfxy1wxS2v23+9uHtvYyg1q8AAAD//25zbQ5XAgAA", -} - -// GetSwagger returns the content of the embedded swagger specification file -// or error if failed to decode -func decodeSpec() ([]byte, error) { - zipped, err := base64.StdEncoding.DecodeString(strings.Join(swaggerSpec, "")) - if err != nil { - return nil, fmt.Errorf("error base64 decoding spec: %w", err) - } - zr, err := gzip.NewReader(bytes.NewReader(zipped)) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - var buf bytes.Buffer - _, err = buf.ReadFrom(zr) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - - return buf.Bytes(), nil -} - -var rawSpec = decodeSpecCached() - -// a naive cached of a decoded swagger spec -func decodeSpecCached() func() ([]byte, error) { - data, err := decodeSpec() - return func() ([]byte, error) { - return data, err - } -} - -// Constructs a synthetic filesystem for resolving external references when loading openapi specifications. -func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { - res := make(map[string]func() ([]byte, error)) - if len(pathToFile) > 0 { - res[pathToFile] = rawSpec - } - - return res -} - -// GetSwagger returns the Swagger specification corresponding to the generated code -// in this file. The external references of Swagger specification are resolved. -// The logic of resolving external references is tightly connected to "import-mapping" feature. -// Externally referenced files must be embedded in the corresponding golang packages. -// Urls can be supported but this task was out of the scope. -func GetSwagger() (swagger *openapi3.T, err error) { - resolvePath := PathToRawSpec("") - - loader := openapi3.NewLoader() - loader.IsExternalRefsAllowed = true - loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() - pathToFile = path.Clean(pathToFile) - getSpec, ok := resolvePath[pathToFile] - if !ok { - err1 := fmt.Errorf("path not found: %s", pathToFile) - return nil, err1 - } - return getSpec() - } - var specData []byte - specData, err = rawSpec() - if err != nil { - return - } - swagger, err = loader.LoadFromData(specData) - if err != nil { - return - } - return -} diff --git a/internal/test/issues/issue-1208-1209/issue-multi-json.yaml b/internal/test/issues/issue-1208-1209/issue-multi-json.yaml deleted file mode 100644 index 8a52ac0c0c..0000000000 --- a/internal/test/issues/issue-1208-1209/issue-multi-json.yaml +++ /dev/null @@ -1,35 +0,0 @@ -openapi: 3.0.0 -paths: - /test: - get: - operationId: Test - responses: - "200": - content: - application/foo+json: - schema: - $ref: '#/components/schemas/foo' - application/bar+json: - schema: - $ref: '#/components/schemas/bar' - "201": - $ref: '#/components/responses/baz' -components: - schemas: - foo: - properties: - field1: - type: string - bar: - properties: - field2: - type: string - responses: - baz: - content: - application/foo+json: - schema: - $ref: '#/components/schemas/foo' - application/bar+json: - schema: - $ref: '#/components/schemas/bar' diff --git a/internal/test/issues/issue-1208-1209/issue-multi-json_test.go b/internal/test/issues/issue-1208-1209/issue-multi-json_test.go deleted file mode 100644 index 2c379909e9..0000000000 --- a/internal/test/issues/issue-1208-1209/issue-multi-json_test.go +++ /dev/null @@ -1,114 +0,0 @@ -package multijson_test - -import ( - "bytes" - "io" - "net/http" - "testing" - - multijson "github.com/oapi-codegen/oapi-codegen/v2/internal/test/issues/issue-1208-1209" - "github.com/stretchr/testify/assert" -) - -func TestIssueMultiJson(t *testing.T) { - // Status code 200, application/foo+json - bodyFoo := []byte(`{"field1": "foo"}`) - rawResponse := &http.Response{ - StatusCode: 200, - Body: io.NopCloser(bytes.NewReader(bodyFoo)), - Header: http.Header{}, - } - rawResponse.Header.Add("Content-type", "application/foo+json") - - response, err := multijson.ParseTestResponse(rawResponse) - assert.NoError(t, err) - assert.NotNil(t, response.ApplicationfooJSON200) - assert.NotNil(t, response.ApplicationfooJSON200.Field1) - assert.Equal(t, "foo", *response.ApplicationfooJSON200.Field1) - assert.Nil(t, response.ApplicationbarJSON200) - assert.Nil(t, response.ApplicationfooJSON201) - assert.Nil(t, response.ApplicationbarJSON201) - - // Status code 200, application/bar+json - bodyBar := []byte(`{"field2": "bar"}`) - rawResponse = &http.Response{ - StatusCode: 200, - Body: io.NopCloser(bytes.NewReader(bodyBar)), - Header: http.Header{}, - } - rawResponse.Header.Add("Content-type", "application/bar+json") - - response, err = multijson.ParseTestResponse(rawResponse) - assert.NoError(t, err) - assert.Nil(t, response.ApplicationfooJSON200) - assert.NotNil(t, response.ApplicationbarJSON200) - assert.NotNil(t, response.ApplicationbarJSON200.Field2) - assert.Equal(t, "bar", *response.ApplicationbarJSON200.Field2) - assert.Nil(t, response.ApplicationfooJSON201) - assert.Nil(t, response.ApplicationbarJSON201) - - // Status code 200, application/qux+json - bodyQux := []byte(`{"field4": "Qux"}`) - rawResponse = &http.Response{ - StatusCode: 200, - Body: io.NopCloser(bytes.NewReader(bodyQux)), - Header: http.Header{}, - } - rawResponse.Header.Add("Content-type", "application/qux+json") - - response, err = multijson.ParseTestResponse(rawResponse) - assert.NoError(t, err) - assert.Nil(t, response.ApplicationfooJSON200) - assert.Nil(t, response.ApplicationbarJSON200) - assert.Nil(t, response.ApplicationfooJSON201) - assert.Nil(t, response.ApplicationbarJSON201) - - // Status code 201, application/foo+json - rawResponse = &http.Response{ - StatusCode: 201, - Body: io.NopCloser(bytes.NewReader(bodyFoo)), - Header: http.Header{}, - } - rawResponse.Header.Add("Content-type", "application/foo+json") - - response, err = multijson.ParseTestResponse(rawResponse) - assert.NoError(t, err) - assert.Nil(t, response.ApplicationfooJSON200) - assert.Nil(t, response.ApplicationbarJSON200) - assert.NotNil(t, response.ApplicationfooJSON201) - assert.NotNil(t, response.ApplicationfooJSON201.Field1) - assert.Equal(t, "foo", *response.ApplicationfooJSON201.Field1) - assert.Nil(t, response.ApplicationbarJSON201) - - // Status code 201, application/bar+json - rawResponse = &http.Response{ - StatusCode: 201, - Body: io.NopCloser(bytes.NewReader(bodyBar)), - Header: http.Header{}, - } - rawResponse.Header.Add("Content-type", "application/bar+json") - - response, err = multijson.ParseTestResponse(rawResponse) - assert.NoError(t, err) - assert.Nil(t, response.ApplicationfooJSON200) - assert.Nil(t, response.ApplicationbarJSON200) - assert.Nil(t, response.ApplicationfooJSON201) - assert.NotNil(t, response.ApplicationbarJSON201) - assert.NotNil(t, response.ApplicationbarJSON201.Field2) - assert.Equal(t, "bar", *response.ApplicationbarJSON201.Field2) - - // Status code 201, application/qux+json - rawResponse = &http.Response{ - StatusCode: 201, - Body: io.NopCloser(bytes.NewReader(bodyQux)), - Header: http.Header{}, - } - rawResponse.Header.Add("Content-type", "application/qux+json") - - response, err = multijson.ParseTestResponse(rawResponse) - assert.NoError(t, err) - assert.Nil(t, response.ApplicationfooJSON200) - assert.Nil(t, response.ApplicationbarJSON200) - assert.Nil(t, response.ApplicationfooJSON201) - assert.Nil(t, response.ApplicationbarJSON201) -} diff --git a/internal/test/issues/issue-1212/pkg1.yaml b/internal/test/issues/issue-1212/pkg1.yaml deleted file mode 100644 index c079bd6d9f..0000000000 --- a/internal/test/issues/issue-1212/pkg1.yaml +++ /dev/null @@ -1,8 +0,0 @@ -openapi: 3.0.0 -paths: - /test: - get: - operationId: Test - responses: - "200": - $ref: 'pkg2.yaml#/components/responses/test' diff --git a/internal/test/issues/issue-1212/pkg1/config.yaml b/internal/test/issues/issue-1212/pkg1/config.yaml deleted file mode 100644 index 040b8223b7..0000000000 --- a/internal/test/issues/issue-1212/pkg1/config.yaml +++ /dev/null @@ -1,11 +0,0 @@ -# yaml-language-server: $schema=../../../../../configuration-schema.json -package: pkg1 -generate: - client: true - models: true - embedded-spec: true - gin-server: true - strict-server: true -output: pkg1.gen.go -import-mapping: - pkg2.yaml: github.com/oapi-codegen/oapi-codegen/v2/internal/test/issues/issue-1212/pkg2 diff --git a/internal/test/issues/issue-1212/pkg1/doc.go b/internal/test/issues/issue-1212/pkg1/doc.go deleted file mode 100644 index 8b57f0836f..0000000000 --- a/internal/test/issues/issue-1212/pkg1/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -package pkg1 - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml ../pkg1.yaml diff --git a/internal/test/issues/issue-1212/pkg1/pkg1.gen.go b/internal/test/issues/issue-1212/pkg1/pkg1.gen.go deleted file mode 100644 index c24850b199..0000000000 --- a/internal/test/issues/issue-1212/pkg1/pkg1.gen.go +++ /dev/null @@ -1,441 +0,0 @@ -// Package pkg1 provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package pkg1 - -import ( - "bytes" - "compress/gzip" - "context" - "encoding/base64" - "fmt" - "io" - "mime" - "mime/multipart" - "net/http" - "net/url" - "path" - "strings" - - "github.com/getkin/kin-openapi/openapi3" - "github.com/gin-gonic/gin" - externalRef0 "github.com/oapi-codegen/oapi-codegen/v2/internal/test/issues/issue-1212/pkg2" - strictgin "github.com/oapi-codegen/runtime/strictmiddleware/gin" -) - -// RequestEditorFn is the function signature for the RequestEditor callback function -type RequestEditorFn func(ctx context.Context, req *http.Request) error - -// Doer performs HTTP requests. -// -// The standard http.Client implements this interface. -type HttpRequestDoer interface { - Do(req *http.Request) (*http.Response, error) -} - -// Client which conforms to the OpenAPI3 specification for this service. -type Client struct { - // The endpoint of the server conforming to this interface, with scheme, - // https://api.deepmap.com for example. This can contain a path relative - // to the server, such as https://api.deepmap.com/dev-test, and all the - // paths in the swagger spec will be appended to the server. - Server string - - // Doer for performing requests, typically a *http.Client with any - // customized settings, such as certificate chains. - Client HttpRequestDoer - - // A list of callbacks for modifying requests which are generated before sending over - // the network. - RequestEditors []RequestEditorFn -} - -// ClientOption allows setting custom parameters during construction -type ClientOption func(*Client) error - -// Creates a new Client, with reasonable defaults -func NewClient(server string, opts ...ClientOption) (*Client, error) { - // create a client with sane default values - client := Client{ - Server: server, - } - // mutate client and add all optional params - for _, o := range opts { - if err := o(&client); err != nil { - return nil, err - } - } - // ensure the server URL always has a trailing slash - if !strings.HasSuffix(client.Server, "/") { - client.Server += "/" - } - // create httpClient, if not already present - if client.Client == nil { - client.Client = &http.Client{} - } - return &client, nil -} - -// WithHTTPClient allows overriding the default Doer, which is -// automatically created using http.Client. This is useful for tests. -func WithHTTPClient(doer HttpRequestDoer) ClientOption { - return func(c *Client) error { - c.Client = doer - return nil - } -} - -// WithRequestEditorFn allows setting up a callback function, which will be -// called right before sending the request. This can be used to mutate the request. -func WithRequestEditorFn(fn RequestEditorFn) ClientOption { - return func(c *Client) error { - c.RequestEditors = append(c.RequestEditors, fn) - return nil - } -} - -// The interface specification for the client above. -type ClientInterface interface { - // Test request - Test(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) -} - -func (c *Client) Test(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewTestRequest(c.Server) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -// NewTestRequest generates requests for Test -func NewTestRequest(server string) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/test") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -func (c *Client) applyEditors(ctx context.Context, req *http.Request, additionalEditors []RequestEditorFn) error { - for _, r := range c.RequestEditors { - if err := r(ctx, req); err != nil { - return err - } - } - for _, r := range additionalEditors { - if err := r(ctx, req); err != nil { - return err - } - } - return nil -} - -// ClientWithResponses builds on ClientInterface to offer response payloads -type ClientWithResponses struct { - ClientInterface -} - -// NewClientWithResponses creates a new ClientWithResponses, which wraps -// Client with return type handling -func NewClientWithResponses(server string, opts ...ClientOption) (*ClientWithResponses, error) { - client, err := NewClient(server, opts...) - if err != nil { - return nil, err - } - return &ClientWithResponses{client}, nil -} - -// WithBaseURL overrides the baseURL. -func WithBaseURL(baseURL string) ClientOption { - return func(c *Client) error { - newBaseURL, err := url.Parse(baseURL) - if err != nil { - return err - } - c.Server = newBaseURL.String() - return nil - } -} - -// ClientWithResponsesInterface is the interface specification for the client with responses above. -type ClientWithResponsesInterface interface { - // TestWithResponse request - TestWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*TestResponse, error) -} - -type TestResponse struct { - Body []byte - HTTPResponse *http.Response -} - -// Status returns HTTPResponse.Status -func (r TestResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r TestResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -// TestWithResponse request returning *TestResponse -func (c *ClientWithResponses) TestWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*TestResponse, error) { - rsp, err := c.Test(ctx, reqEditors...) - if err != nil { - return nil, err - } - return ParseTestResponse(rsp) -} - -// ParseTestResponse parses an HTTP response from a TestWithResponse call -func ParseTestResponse(rsp *http.Response) (*TestResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &TestResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - return response, nil -} - -// ServerInterface represents all server handlers. -type ServerInterface interface { - - // (GET /test) - Test(c *gin.Context) -} - -// ServerInterfaceWrapper converts contexts to parameters. -type ServerInterfaceWrapper struct { - Handler ServerInterface - HandlerMiddlewares []MiddlewareFunc - ErrorHandler func(*gin.Context, error, int) -} - -type MiddlewareFunc func(c *gin.Context) - -// Test operation middleware -func (siw *ServerInterfaceWrapper) Test(c *gin.Context) { - - for _, middleware := range siw.HandlerMiddlewares { - middleware(c) - if c.IsAborted() { - return - } - } - - siw.Handler.Test(c) -} - -// GinServerOptions provides options for the Gin server. -type GinServerOptions struct { - BaseURL string - Middlewares []MiddlewareFunc - ErrorHandler func(*gin.Context, error, int) -} - -// RegisterHandlers creates http.Handler with routing matching OpenAPI spec. -func RegisterHandlers(router gin.IRouter, si ServerInterface) { - RegisterHandlersWithOptions(router, si, GinServerOptions{}) -} - -// RegisterHandlersWithOptions creates http.Handler with additional options -func RegisterHandlersWithOptions(router gin.IRouter, si ServerInterface, options GinServerOptions) { - errorHandler := options.ErrorHandler - if errorHandler == nil { - errorHandler = func(c *gin.Context, err error, statusCode int) { - c.JSON(statusCode, gin.H{"msg": err.Error()}) - } - } - - wrapper := ServerInterfaceWrapper{ - Handler: si, - HandlerMiddlewares: options.Middlewares, - ErrorHandler: errorHandler, - } - - router.GET(options.BaseURL+"/test", wrapper.Test) -} - -type TestRequestObject struct { -} - -type TestResponseObject interface { - VisitTestResponse(w http.ResponseWriter) error -} - -type Test200MultipartResponse externalRef0.TestMultipartResponse - -func (response Test200MultipartResponse) VisitTestResponse(w http.ResponseWriter) error { - writer := multipart.NewWriter(w) - w.Header().Set("Content-Type", mime.FormatMediaType("multipart/related", map[string]string{"boundary": writer.Boundary()})) - w.WriteHeader(200) - - defer writer.Close() - return response(writer) -} - -// StrictServerInterface represents all server handlers. -type StrictServerInterface interface { - - // (GET /test) - Test(ctx context.Context, request TestRequestObject) (TestResponseObject, error) -} - -type StrictHandlerFunc = strictgin.StrictGinHandlerFunc -type StrictMiddlewareFunc = strictgin.StrictGinMiddlewareFunc - -func NewStrictHandler(ssi StrictServerInterface, middlewares []StrictMiddlewareFunc) ServerInterface { - return &strictHandler{ssi: ssi, middlewares: middlewares} -} - -type strictHandler struct { - ssi StrictServerInterface - middlewares []StrictMiddlewareFunc -} - -// Test operation middleware -func (sh *strictHandler) Test(ctx *gin.Context) { - var request TestRequestObject - - handler := func(ctx *gin.Context, request interface{}) (interface{}, error) { - return sh.ssi.Test(ctx, request.(TestRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "Test") - } - - response, err := handler(ctx, request) - - if err != nil { - ctx.Error(err) - ctx.Status(http.StatusInternalServerError) - } else if validResponse, ok := response.(TestResponseObject); ok { - if err := validResponse.VisitTestResponse(ctx.Writer); err != nil { - ctx.Error(err) - } - } else if response != nil { - ctx.Error(fmt.Errorf("unexpected response type: %T", response)) - } -} - -// Base64 encoded, gzipped, json marshaled Swagger object -var swaggerSpec = []string{ - - "H4sIAAAAAAAC/4yRMU/DMBCF/8uDMapD2DwyILGzIze5pAbnzrKvA6r635FtaFSpSM2SO9vfe6d3J4yy", - "RmFizbAnJMpROFNt4tcyfChlLc0orMS1XI9BfXRJTaLglKZymMcDra5iSSIl9U3kMwu/uFTKx0QzLB7M", - "5mkalk312ruEc1eRV5G7kFkE5/Z1vzNss++b7/VAs6cwDaXS70iwyJo8L6gKF83b2NNNrICeZ4HlYwgd", - "JBK76GHxvOt3PTpEp4eqYv7iXKj+ioNTL/w2weK9XHbXSxj6/r8gLu/MtqkWxU8AAAD//+WESHLXAQAA", -} - -// GetSwagger returns the content of the embedded swagger specification file -// or error if failed to decode -func decodeSpec() ([]byte, error) { - zipped, err := base64.StdEncoding.DecodeString(strings.Join(swaggerSpec, "")) - if err != nil { - return nil, fmt.Errorf("error base64 decoding spec: %w", err) - } - zr, err := gzip.NewReader(bytes.NewReader(zipped)) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - var buf bytes.Buffer - _, err = buf.ReadFrom(zr) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - - return buf.Bytes(), nil -} - -var rawSpec = decodeSpecCached() - -// a naive cached of a decoded swagger spec -func decodeSpecCached() func() ([]byte, error) { - data, err := decodeSpec() - return func() ([]byte, error) { - return data, err - } -} - -// Constructs a synthetic filesystem for resolving external references when loading openapi specifications. -func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { - res := make(map[string]func() ([]byte, error)) - if len(pathToFile) > 0 { - res[pathToFile] = rawSpec - } - - for rawPath, rawFunc := range externalRef0.PathToRawSpec(path.Join(path.Dir(pathToFile), "pkg2.yaml")) { - if _, ok := res[rawPath]; ok { - // it is not possible to compare functions in golang, so always overwrite the old value - } - res[rawPath] = rawFunc - } - return res -} - -// GetSwagger returns the Swagger specification corresponding to the generated code -// in this file. The external references of Swagger specification are resolved. -// The logic of resolving external references is tightly connected to "import-mapping" feature. -// Externally referenced files must be embedded in the corresponding golang packages. -// Urls can be supported but this task was out of the scope. -func GetSwagger() (swagger *openapi3.T, err error) { - resolvePath := PathToRawSpec("") - - loader := openapi3.NewLoader() - loader.IsExternalRefsAllowed = true - loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() - pathToFile = path.Clean(pathToFile) - getSpec, ok := resolvePath[pathToFile] - if !ok { - err1 := fmt.Errorf("path not found: %s", pathToFile) - return nil, err1 - } - return getSpec() - } - var specData []byte - specData, err = rawSpec() - if err != nil { - return - } - swagger, err = loader.LoadFromData(specData) - if err != nil { - return - } - return -} diff --git a/internal/test/issues/issue-1212/pkg2.yaml b/internal/test/issues/issue-1212/pkg2.yaml deleted file mode 100644 index 96941832ca..0000000000 --- a/internal/test/issues/issue-1212/pkg2.yaml +++ /dev/null @@ -1,21 +0,0 @@ -openapi: "3.0.1" -components: - schemas: - foo: - properties: - field1: - type: string - bar: - properties: - field2: - type: string - responses: - test: - content: - multipart/related: - schema: - properties: - jsonFoo: - $ref: '#/components/schemas/foo' - jsonBar: - $ref: '#/components/schemas/bar' diff --git a/internal/test/issues/issue-1212/pkg2/config.yaml b/internal/test/issues/issue-1212/pkg2/config.yaml deleted file mode 100644 index d3a63e5d40..0000000000 --- a/internal/test/issues/issue-1212/pkg2/config.yaml +++ /dev/null @@ -1,11 +0,0 @@ -# yaml-language-server: $schema=../../../../../configuration-schema.json -package: pkg2 -generate: - client: true - models: true - embedded-spec: true - gin-server: true - strict-server: true -output: pkg2.gen.go -output-options: - skip-prune: true diff --git a/internal/test/issues/issue-1212/pkg2/doc.go b/internal/test/issues/issue-1212/pkg2/doc.go deleted file mode 100644 index 68cb0b78a1..0000000000 --- a/internal/test/issues/issue-1212/pkg2/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -package pkg2 - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml ../pkg2.yaml diff --git a/internal/test/issues/issue-1212/pkg2/pkg2.gen.go b/internal/test/issues/issue-1212/pkg2/pkg2.gen.go deleted file mode 100644 index 5a994ed06f..0000000000 --- a/internal/test/issues/issue-1212/pkg2/pkg2.gen.go +++ /dev/null @@ -1,280 +0,0 @@ -// Package pkg2 provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package pkg2 - -import ( - "bytes" - "compress/gzip" - "context" - "encoding/base64" - "fmt" - "mime/multipart" - "net/http" - "net/url" - "path" - "strings" - - "github.com/getkin/kin-openapi/openapi3" - "github.com/gin-gonic/gin" - strictgin "github.com/oapi-codegen/runtime/strictmiddleware/gin" -) - -// Bar defines model for bar. -type Bar struct { - Field2 *string `json:"field2,omitempty"` -} - -// Foo defines model for foo. -type Foo struct { - Field1 *string `json:"field1,omitempty"` -} - -// RequestEditorFn is the function signature for the RequestEditor callback function -type RequestEditorFn func(ctx context.Context, req *http.Request) error - -// Doer performs HTTP requests. -// -// The standard http.Client implements this interface. -type HttpRequestDoer interface { - Do(req *http.Request) (*http.Response, error) -} - -// Client which conforms to the OpenAPI3 specification for this service. -type Client struct { - // The endpoint of the server conforming to this interface, with scheme, - // https://api.deepmap.com for example. This can contain a path relative - // to the server, such as https://api.deepmap.com/dev-test, and all the - // paths in the swagger spec will be appended to the server. - Server string - - // Doer for performing requests, typically a *http.Client with any - // customized settings, such as certificate chains. - Client HttpRequestDoer - - // A list of callbacks for modifying requests which are generated before sending over - // the network. - RequestEditors []RequestEditorFn -} - -// ClientOption allows setting custom parameters during construction -type ClientOption func(*Client) error - -// Creates a new Client, with reasonable defaults -func NewClient(server string, opts ...ClientOption) (*Client, error) { - // create a client with sane default values - client := Client{ - Server: server, - } - // mutate client and add all optional params - for _, o := range opts { - if err := o(&client); err != nil { - return nil, err - } - } - // ensure the server URL always has a trailing slash - if !strings.HasSuffix(client.Server, "/") { - client.Server += "/" - } - // create httpClient, if not already present - if client.Client == nil { - client.Client = &http.Client{} - } - return &client, nil -} - -// WithHTTPClient allows overriding the default Doer, which is -// automatically created using http.Client. This is useful for tests. -func WithHTTPClient(doer HttpRequestDoer) ClientOption { - return func(c *Client) error { - c.Client = doer - return nil - } -} - -// WithRequestEditorFn allows setting up a callback function, which will be -// called right before sending the request. This can be used to mutate the request. -func WithRequestEditorFn(fn RequestEditorFn) ClientOption { - return func(c *Client) error { - c.RequestEditors = append(c.RequestEditors, fn) - return nil - } -} - -// The interface specification for the client above. -type ClientInterface interface { -} - -func (c *Client) applyEditors(ctx context.Context, req *http.Request, additionalEditors []RequestEditorFn) error { - for _, r := range c.RequestEditors { - if err := r(ctx, req); err != nil { - return err - } - } - for _, r := range additionalEditors { - if err := r(ctx, req); err != nil { - return err - } - } - return nil -} - -// ClientWithResponses builds on ClientInterface to offer response payloads -type ClientWithResponses struct { - ClientInterface -} - -// NewClientWithResponses creates a new ClientWithResponses, which wraps -// Client with return type handling -func NewClientWithResponses(server string, opts ...ClientOption) (*ClientWithResponses, error) { - client, err := NewClient(server, opts...) - if err != nil { - return nil, err - } - return &ClientWithResponses{client}, nil -} - -// WithBaseURL overrides the baseURL. -func WithBaseURL(baseURL string) ClientOption { - return func(c *Client) error { - newBaseURL, err := url.Parse(baseURL) - if err != nil { - return err - } - c.Server = newBaseURL.String() - return nil - } -} - -// ClientWithResponsesInterface is the interface specification for the client with responses above. -type ClientWithResponsesInterface interface { -} - -// ServerInterface represents all server handlers. -type ServerInterface interface { -} - -// ServerInterfaceWrapper converts contexts to parameters. -type ServerInterfaceWrapper struct { - Handler ServerInterface - HandlerMiddlewares []MiddlewareFunc - ErrorHandler func(*gin.Context, error, int) -} - -type MiddlewareFunc func(c *gin.Context) - -// GinServerOptions provides options for the Gin server. -type GinServerOptions struct { - BaseURL string - Middlewares []MiddlewareFunc - ErrorHandler func(*gin.Context, error, int) -} - -// RegisterHandlers creates http.Handler with routing matching OpenAPI spec. -func RegisterHandlers(router gin.IRouter, si ServerInterface) { - RegisterHandlersWithOptions(router, si, GinServerOptions{}) -} - -// RegisterHandlersWithOptions creates http.Handler with additional options -func RegisterHandlersWithOptions(router gin.IRouter, si ServerInterface, options GinServerOptions) { - -} - -type TestMultipartResponse func(writer *multipart.Writer) error - -// StrictServerInterface represents all server handlers. -type StrictServerInterface interface { -} - -type StrictHandlerFunc = strictgin.StrictGinHandlerFunc -type StrictMiddlewareFunc = strictgin.StrictGinMiddlewareFunc - -func NewStrictHandler(ssi StrictServerInterface, middlewares []StrictMiddlewareFunc) ServerInterface { - return &strictHandler{ssi: ssi, middlewares: middlewares} -} - -type strictHandler struct { - ssi StrictServerInterface - middlewares []StrictMiddlewareFunc -} - -// Base64 encoded, gzipped, json marshaled Swagger object -var swaggerSpec = []string{ - - "H4sIAAAAAAAC/4SPwU4EIQyG36V6JIurN44efA92trgYpm3a7sFM5t0NYGJMJlku/MD/5aMbLLwKE5Ib", - "pA0UTZgMx8HRvO8LkyONuN6bV8nqUbFlx2u/tOWGa+5JlAXV6+S/jOk9a4/PigUSPMU/XZyYxUtW2MNo", - "fzA/ahdm2OcKv+Yhu0zR/x+Uiu36Omb5FoQE5lrpEwZcpuyAOB8SnalUGBLdWwvAgpSlQoK308vpDAEk", - "+83m8/4TAAD//08ZxXtaAQAA", -} - -// GetSwagger returns the content of the embedded swagger specification file -// or error if failed to decode -func decodeSpec() ([]byte, error) { - zipped, err := base64.StdEncoding.DecodeString(strings.Join(swaggerSpec, "")) - if err != nil { - return nil, fmt.Errorf("error base64 decoding spec: %w", err) - } - zr, err := gzip.NewReader(bytes.NewReader(zipped)) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - var buf bytes.Buffer - _, err = buf.ReadFrom(zr) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - - return buf.Bytes(), nil -} - -var rawSpec = decodeSpecCached() - -// a naive cached of a decoded swagger spec -func decodeSpecCached() func() ([]byte, error) { - data, err := decodeSpec() - return func() ([]byte, error) { - return data, err - } -} - -// Constructs a synthetic filesystem for resolving external references when loading openapi specifications. -func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { - res := make(map[string]func() ([]byte, error)) - if len(pathToFile) > 0 { - res[pathToFile] = rawSpec - } - - return res -} - -// GetSwagger returns the Swagger specification corresponding to the generated code -// in this file. The external references of Swagger specification are resolved. -// The logic of resolving external references is tightly connected to "import-mapping" feature. -// Externally referenced files must be embedded in the corresponding golang packages. -// Urls can be supported but this task was out of the scope. -func GetSwagger() (swagger *openapi3.T, err error) { - resolvePath := PathToRawSpec("") - - loader := openapi3.NewLoader() - loader.IsExternalRefsAllowed = true - loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() - pathToFile = path.Clean(pathToFile) - getSpec, ok := resolvePath[pathToFile] - if !ok { - err1 := fmt.Errorf("path not found: %s", pathToFile) - return nil, err1 - } - return getSpec() - } - var specData []byte - specData, err = rawSpec() - if err != nil { - return - } - swagger, err = loader.LoadFromData(specData) - if err != nil { - return - } - return -} diff --git a/internal/test/issues/issue-1219/config.yaml b/internal/test/issues/issue-1219/config.yaml deleted file mode 100644 index 91e041af5f..0000000000 --- a/internal/test/issues/issue-1219/config.yaml +++ /dev/null @@ -1,7 +0,0 @@ -# yaml-language-server: $schema=../../../../configuration-schema.json -package: issue1219 -generate: - models: true -output-options: - skip-prune: true -output: issue.gen.go diff --git a/internal/test/issues/issue-1219/doc.go b/internal/test/issues/issue-1219/doc.go deleted file mode 100644 index 7e1118e5c9..0000000000 --- a/internal/test/issues/issue-1219/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -package issue1219 - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml issue.yaml diff --git a/internal/test/issues/issue-1219/issue.yaml b/internal/test/issues/issue-1219/issue.yaml deleted file mode 100644 index 0437423277..0000000000 --- a/internal/test/issues/issue-1219/issue.yaml +++ /dev/null @@ -1,136 +0,0 @@ -openapi: "3.0.1" -components: - schemas: - WithAnyAdditional1: - type: object - properties: - field1: - type: integer - field2: - type: string - additionalProperties: true - WithAnyAdditional2: - type: object - properties: - fieldA: - type: integer - fieldB: - type: string - additionalProperties: true - WithStringAdditional1: - type: object - properties: - field1: - type: integer - field2: - type: string - additionalProperties: - type: string - WithStringAdditional2: - type: object - properties: - fieldA: - type: integer - fieldB: - type: string - additionalProperties: - type: string - WithoutAdditional1: - type: object - properties: - field1: - type: integer - field2: - type: string - additionalProperties: false - WithoutAdditional2: - type: object - properties: - fieldA: - type: integer - fieldB: - type: string - additionalProperties: false - DefaultAdditional1: - type: object - properties: - field1: - type: integer - field2: - type: string - DefaultAdditional2: - type: object - properties: - fieldA: - type: integer - fieldB: - type: string - - MergeWithoutWithout: - allOf: - - $ref: '#/components/schemas/WithoutAdditional1' - - $ref: '#/components/schemas/WithoutAdditional2' - MergeWithoutWithString: - allOf: - - $ref: '#/components/schemas/WithoutAdditional1' - - $ref: '#/components/schemas/WithStringAdditional2' - MergeWithoutWithAny: - allOf: - - $ref: '#/components/schemas/WithoutAdditional1' - - $ref: '#/components/schemas/WithAnyAdditional2' - MergeWithoutDefault: - allOf: - - $ref: '#/components/schemas/WithoutAdditional1' - - $ref: '#/components/schemas/DefaultAdditional2' - - MergeWithStringWithout: - allOf: - - $ref: '#/components/schemas/WithStringAdditional1' - - $ref: '#/components/schemas/WithoutAdditional2' - # Cannot merge this - # MergeWithStringWithString: - # allOf: - # - $ref: '#/components/schemas/WithStringAdditional1' - # - $ref: '#/components/schemas/WithStringAdditional2' - MergeWithStringWithAny: - allOf: - - $ref: '#/components/schemas/WithStringAdditional1' - - $ref: '#/components/schemas/WithAnyAdditional2' - MergeWithStringDefault: - allOf: - - $ref: '#/components/schemas/WithStringAdditional1' - - $ref: '#/components/schemas/DefaultAdditional2' - - MergeWithAnyWithout: - allOf: - - $ref: '#/components/schemas/WithAnyAdditional1' - - $ref: '#/components/schemas/WithoutAdditional2' - MergeWithAnyWithString: - allOf: - - $ref: '#/components/schemas/WithAnyAdditional1' - - $ref: '#/components/schemas/WithStringAdditional2' - MergeWithAnyWithAny: - allOf: - - $ref: '#/components/schemas/WithAnyAdditional1' - - $ref: '#/components/schemas/WithAnyAdditional2' - MergeWithAnyDefault: - allOf: - - $ref: '#/components/schemas/WithAnyAdditional1' - - $ref: '#/components/schemas/DefaultAdditional2' - - MergeDefaultWithout: - allOf: - - $ref: '#/components/schemas/DefaultAdditional1' - - $ref: '#/components/schemas/WithoutAdditional2' - MergeDefaultWithString: - allOf: - - $ref: '#/components/schemas/DefaultAdditional1' - - $ref: '#/components/schemas/WithStringAdditional2' - MergeDefaultWithAny: - allOf: - - $ref: '#/components/schemas/DefaultAdditional1' - - $ref: '#/components/schemas/WithAnyAdditional2' - MergeDefaultDefault: - allOf: - - $ref: '#/components/schemas/DefaultAdditional1' - - $ref: '#/components/schemas/DefaultAdditional2' diff --git a/internal/test/issues/issue-1219/issue_test.go b/internal/test/issues/issue-1219/issue_test.go deleted file mode 100644 index aebd0d1afd..0000000000 --- a/internal/test/issues/issue-1219/issue_test.go +++ /dev/null @@ -1,85 +0,0 @@ -package issue1219_test - -import ( - "reflect" - "testing" - - issue1219 "github.com/oapi-codegen/oapi-codegen/v2/internal/test/issues/issue-1219" - "github.com/stretchr/testify/assert" -) - -// Test treatment additionalProperties in mergeOpenapiSchemas() -func TestIssue1219(t *testing.T) { - var exist bool - // In the current oapi-codegen, additionalProperties is treated as `false’ unlike the openapi specification - // when it is not specified, so the case where additionalProperties is unspecified and - // the case where it is explicitly `true’ are treated separately. - - // When properties "additionalProperties" in both schemas are explicitly "true", - // the property "additionalProperties" in merged schema must be "true". - assert.IsType(t, map[string]interface{}{}, issue1219.MergeWithAnyWithAny{}.AdditionalProperties) - // Old behavior: generate fail - - // When property "additionalProperties" in one schema is explicitly "true" and - // property "additionalProperties" in another schema specifies sub-schema, - // the property "additionalProperties" in merged schema must use specified sub-schema in later source schema. - assert.IsType(t, map[string]string{}, issue1219.MergeWithAnyWithString{}.AdditionalProperties) - assert.IsType(t, map[string]string{}, issue1219.MergeWithStringWithAny{}.AdditionalProperties) - // Old behavior: generate fail - - // When property "additionalProperties" in one schema is explicitly "true" and - // property "additionalProperties" in another schema is not specified, - // the property "additionalProperties" in merged schema must be "true". - // This is because properties "additionalProperties" in both schemas are treated as "true" in the openapi specification. - assert.IsType(t, map[string]interface{}{}, issue1219.MergeWithAnyDefault{}.AdditionalProperties) - assert.IsType(t, map[string]interface{}{}, issue1219.MergeDefaultWithAny{}.AdditionalProperties) - // Old behavior: additionalProperties is treated as unspecified - - // When property "additionalProperties" in one schema is explicitly "true" and - // property "additionalProperties" in another schema is "false", - // the property "additionalProperties" in merged schema must be "false". - _, exist = reflect.TypeOf(issue1219.MergeWithAnyWithout{}).FieldByName("AdditionalProperties") - assert.False(t, exist) - _, exist = reflect.TypeOf(issue1219.MergeWithoutWithAny{}).FieldByName("AdditionalProperties") - assert.False(t, exist) - // Old behavior: additionalProperties is treated as unspecified - - // When properties "additionalProperties" in both schemas specify sub-schema, - // sub-schemas must be merged. - // But this is not yet implemented. - // issue1219.MergeWithStringWithString{} - - // When property "additionalProperties" in one schema specifies sub-schema and - // property "additionalProperties" in another schema is not specified, - // the property "additionalProperties" in merged schema must use specified sub-schema. - assert.IsType(t, map[string]string{}, issue1219.MergeWithStringDefault{}.AdditionalProperties) - assert.IsType(t, map[string]string{}, issue1219.MergeDefaultWithString{}.AdditionalProperties) - - // When property "additionalProperties" in one schema specifies sub-schema and - // property "additionalProperties" in another schema is "false", - // the property "additionalProperties" in merged schema must be "false". - _, exist = reflect.TypeOf(issue1219.MergeWithStringWithout{}).FieldByName("AdditionalProperties") - assert.False(t, exist) - _, exist = reflect.TypeOf(issue1219.MergeWithoutWithString{}).FieldByName("AdditionalProperties") - assert.False(t, exist) - // Old behavior: additionalProperties use specified sub-schema. - - // When properties "additionalProperties" in both schemas are not specified, - // the property "additionalProperties" in merged schema must be "true" in the openapi specification. - // But to avoid compatibility issue, property "additionalProperties" in merged schema is treated as unspecified. - _, exist = reflect.TypeOf(issue1219.MergeDefaultDefault{}).FieldByName("AdditionalProperties") - assert.False(t, exist) - - // When property "additionalProperties" in one schema is not specified and - // property "additionalProperties" in another schema is "false", - // the property "additionalProperties" in merged schema must be "false". - _, exist = reflect.TypeOf(issue1219.MergeDefaultWithout{}).FieldByName("AdditionalProperties") - assert.False(t, exist) - _, exist = reflect.TypeOf(issue1219.MergeWithoutDefault{}).FieldByName("AdditionalProperties") - assert.False(t, exist) - - // When properties "additionalProperties" in both schemas are "false", - // the property "additionalProperties" in merged schema must be "false". - _, exist = reflect.TypeOf(issue1219.MergeWithoutWithout{}).FieldByName("AdditionalProperties") - assert.False(t, exist) -} diff --git a/internal/test/issues/issue-1298/config.yaml b/internal/test/issues/issue-1298/config.yaml deleted file mode 100644 index 76ef6715e7..0000000000 --- a/internal/test/issues/issue-1298/config.yaml +++ /dev/null @@ -1,8 +0,0 @@ -# yaml-language-server: $schema=../../../../configuration-schema.json -package: issue1298 -generate: - models: true - client: true - gin-server: true - strict-server: true -output: issue1298.gen.go diff --git a/internal/test/issues/issue-1298/doc.go b/internal/test/issues/issue-1298/doc.go deleted file mode 100644 index b5e5ee95c9..0000000000 --- a/internal/test/issues/issue-1298/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -package issue1298 - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml issue1298.yaml diff --git a/internal/test/issues/issue-1298/issue1298.gen.go b/internal/test/issues/issue-1298/issue1298.gen.go deleted file mode 100644 index 2e5a48dc57..0000000000 --- a/internal/test/issues/issue-1298/issue1298.gen.go +++ /dev/null @@ -1,404 +0,0 @@ -// Package issue1298 provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package issue1298 - -import ( - "bytes" - "context" - "encoding/json" - "errors" - "fmt" - "io" - "net/http" - "net/url" - "strings" - - "github.com/gin-gonic/gin" - strictgin "github.com/oapi-codegen/runtime/strictmiddleware/gin" -) - -// Test defines model for Test. -type Test struct { - Field1 string `json:"field1"` - Field2 string `json:"field2"` -} - -// TestApplicationTestPlusJSONRequestBody defines body for Test for application/test+json ContentType. -type TestApplicationTestPlusJSONRequestBody = Test - -// RequestEditorFn is the function signature for the RequestEditor callback function -type RequestEditorFn func(ctx context.Context, req *http.Request) error - -// Doer performs HTTP requests. -// -// The standard http.Client implements this interface. -type HttpRequestDoer interface { - Do(req *http.Request) (*http.Response, error) -} - -// Client which conforms to the OpenAPI3 specification for this service. -type Client struct { - // The endpoint of the server conforming to this interface, with scheme, - // https://api.deepmap.com for example. This can contain a path relative - // to the server, such as https://api.deepmap.com/dev-test, and all the - // paths in the swagger spec will be appended to the server. - Server string - - // Doer for performing requests, typically a *http.Client with any - // customized settings, such as certificate chains. - Client HttpRequestDoer - - // A list of callbacks for modifying requests which are generated before sending over - // the network. - RequestEditors []RequestEditorFn -} - -// ClientOption allows setting custom parameters during construction -type ClientOption func(*Client) error - -// Creates a new Client, with reasonable defaults -func NewClient(server string, opts ...ClientOption) (*Client, error) { - // create a client with sane default values - client := Client{ - Server: server, - } - // mutate client and add all optional params - for _, o := range opts { - if err := o(&client); err != nil { - return nil, err - } - } - // ensure the server URL always has a trailing slash - if !strings.HasSuffix(client.Server, "/") { - client.Server += "/" - } - // create httpClient, if not already present - if client.Client == nil { - client.Client = &http.Client{} - } - return &client, nil -} - -// WithHTTPClient allows overriding the default Doer, which is -// automatically created using http.Client. This is useful for tests. -func WithHTTPClient(doer HttpRequestDoer) ClientOption { - return func(c *Client) error { - c.Client = doer - return nil - } -} - -// WithRequestEditorFn allows setting up a callback function, which will be -// called right before sending the request. This can be used to mutate the request. -func WithRequestEditorFn(fn RequestEditorFn) ClientOption { - return func(c *Client) error { - c.RequestEditors = append(c.RequestEditors, fn) - return nil - } -} - -// The interface specification for the client above. -type ClientInterface interface { - // TestWithBody request with any body - TestWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) - - TestWithApplicationTestPlusJSONBody(ctx context.Context, body TestApplicationTestPlusJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) -} - -func (c *Client) TestWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewTestRequestWithBody(c.Server, contentType, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) TestWithApplicationTestPlusJSONBody(ctx context.Context, body TestApplicationTestPlusJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewTestRequestWithApplicationTestPlusJSONBody(c.Server, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -// NewTestRequestWithApplicationTestPlusJSONBody calls the generic Test builder with application/test+json body -func NewTestRequestWithApplicationTestPlusJSONBody(server string, body TestApplicationTestPlusJSONRequestBody) (*http.Request, error) { - var bodyReader io.Reader - buf, err := json.Marshal(body) - if err != nil { - return nil, err - } - bodyReader = bytes.NewReader(buf) - return NewTestRequestWithBody(server, "application/test+json", bodyReader) -} - -// NewTestRequestWithBody generates requests for Test with any type of body -func NewTestRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/test") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), body) - if err != nil { - return nil, err - } - - req.Header.Add("Content-Type", contentType) - - return req, nil -} - -func (c *Client) applyEditors(ctx context.Context, req *http.Request, additionalEditors []RequestEditorFn) error { - for _, r := range c.RequestEditors { - if err := r(ctx, req); err != nil { - return err - } - } - for _, r := range additionalEditors { - if err := r(ctx, req); err != nil { - return err - } - } - return nil -} - -// ClientWithResponses builds on ClientInterface to offer response payloads -type ClientWithResponses struct { - ClientInterface -} - -// NewClientWithResponses creates a new ClientWithResponses, which wraps -// Client with return type handling -func NewClientWithResponses(server string, opts ...ClientOption) (*ClientWithResponses, error) { - client, err := NewClient(server, opts...) - if err != nil { - return nil, err - } - return &ClientWithResponses{client}, nil -} - -// WithBaseURL overrides the baseURL. -func WithBaseURL(baseURL string) ClientOption { - return func(c *Client) error { - newBaseURL, err := url.Parse(baseURL) - if err != nil { - return err - } - c.Server = newBaseURL.String() - return nil - } -} - -// ClientWithResponsesInterface is the interface specification for the client with responses above. -type ClientWithResponsesInterface interface { - // TestWithBodyWithResponse request with any body - TestWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*TestResponse, error) - - TestWithApplicationTestPlusJSONBodyWithResponse(ctx context.Context, body TestApplicationTestPlusJSONRequestBody, reqEditors ...RequestEditorFn) (*TestResponse, error) -} - -type TestResponse struct { - Body []byte - HTTPResponse *http.Response -} - -// Status returns HTTPResponse.Status -func (r TestResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r TestResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -// TestWithBodyWithResponse request with arbitrary body returning *TestResponse -func (c *ClientWithResponses) TestWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*TestResponse, error) { - rsp, err := c.TestWithBody(ctx, contentType, body, reqEditors...) - if err != nil { - return nil, err - } - return ParseTestResponse(rsp) -} - -func (c *ClientWithResponses) TestWithApplicationTestPlusJSONBodyWithResponse(ctx context.Context, body TestApplicationTestPlusJSONRequestBody, reqEditors ...RequestEditorFn) (*TestResponse, error) { - rsp, err := c.TestWithApplicationTestPlusJSONBody(ctx, body, reqEditors...) - if err != nil { - return nil, err - } - return ParseTestResponse(rsp) -} - -// ParseTestResponse parses an HTTP response from a TestWithResponse call -func ParseTestResponse(rsp *http.Response) (*TestResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &TestResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - return response, nil -} - -// ServerInterface represents all server handlers. -type ServerInterface interface { - - // (GET /test) - Test(c *gin.Context) -} - -// ServerInterfaceWrapper converts contexts to parameters. -type ServerInterfaceWrapper struct { - Handler ServerInterface - HandlerMiddlewares []MiddlewareFunc - ErrorHandler func(*gin.Context, error, int) -} - -type MiddlewareFunc func(c *gin.Context) - -// Test operation middleware -func (siw *ServerInterfaceWrapper) Test(c *gin.Context) { - - for _, middleware := range siw.HandlerMiddlewares { - middleware(c) - if c.IsAborted() { - return - } - } - - siw.Handler.Test(c) -} - -// GinServerOptions provides options for the Gin server. -type GinServerOptions struct { - BaseURL string - Middlewares []MiddlewareFunc - ErrorHandler func(*gin.Context, error, int) -} - -// RegisterHandlers creates http.Handler with routing matching OpenAPI spec. -func RegisterHandlers(router gin.IRouter, si ServerInterface) { - RegisterHandlersWithOptions(router, si, GinServerOptions{}) -} - -// RegisterHandlersWithOptions creates http.Handler with additional options -func RegisterHandlersWithOptions(router gin.IRouter, si ServerInterface, options GinServerOptions) { - errorHandler := options.ErrorHandler - if errorHandler == nil { - errorHandler = func(c *gin.Context, err error, statusCode int) { - c.JSON(statusCode, gin.H{"msg": err.Error()}) - } - } - - wrapper := ServerInterfaceWrapper{ - Handler: si, - HandlerMiddlewares: options.Middlewares, - ErrorHandler: errorHandler, - } - - router.GET(options.BaseURL+"/test", wrapper.Test) -} - -type TestRequestObject struct { - Body *TestApplicationTestPlusJSONRequestBody -} - -type TestResponseObject interface { - VisitTestResponse(w http.ResponseWriter) error -} - -type Test204Response struct { -} - -func (response Test204Response) VisitTestResponse(w http.ResponseWriter) error { - w.WriteHeader(204) - return nil -} - -// StrictServerInterface represents all server handlers. -type StrictServerInterface interface { - - // (GET /test) - Test(ctx context.Context, request TestRequestObject) (TestResponseObject, error) -} - -type StrictHandlerFunc = strictgin.StrictGinHandlerFunc -type StrictMiddlewareFunc = strictgin.StrictGinMiddlewareFunc - -func NewStrictHandler(ssi StrictServerInterface, middlewares []StrictMiddlewareFunc) ServerInterface { - return &strictHandler{ssi: ssi, middlewares: middlewares} -} - -type strictHandler struct { - ssi StrictServerInterface - middlewares []StrictMiddlewareFunc -} - -// Test operation middleware -func (sh *strictHandler) Test(ctx *gin.Context) { - var request TestRequestObject - - var body TestApplicationTestPlusJSONRequestBody - if err := ctx.ShouldBindJSON(&body); err != nil { - if !errors.Is(err, io.EOF) { - ctx.Status(http.StatusBadRequest) - ctx.Error(err) - return - } - } else { - request.Body = &body - } - - handler := func(ctx *gin.Context, request interface{}) (interface{}, error) { - return sh.ssi.Test(ctx, request.(TestRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "Test") - } - - response, err := handler(ctx, request) - - if err != nil { - ctx.Error(err) - ctx.Status(http.StatusInternalServerError) - } else if validResponse, ok := response.(TestResponseObject); ok { - if err := validResponse.VisitTestResponse(ctx.Writer); err != nil { - ctx.Error(err) - } - } else if response != nil { - ctx.Error(fmt.Errorf("unexpected response type: %T", response)) - } -} diff --git a/internal/test/issues/issue-1298/issue1298.yaml b/internal/test/issues/issue-1298/issue1298.yaml deleted file mode 100644 index 889d0c2b17..0000000000 --- a/internal/test/issues/issue-1298/issue1298.yaml +++ /dev/null @@ -1,25 +0,0 @@ -openapi: "3.0.1" -components: - schemas: - Test: - type: object - properties: - field1: - type: string - field2: - type: string - required: - - field1 - - field2 -paths: - /test: - get: - operationId: test - requestBody: - content: - application/test+json: - schema: - $ref: "#/components/schemas/Test" - responses: - 204: - description: good diff --git a/internal/test/issues/issue-1298/issue1298_test.go b/internal/test/issues/issue-1298/issue1298_test.go deleted file mode 100644 index 0d627f10f5..0000000000 --- a/internal/test/issues/issue-1298/issue1298_test.go +++ /dev/null @@ -1,44 +0,0 @@ -package issue1298_test - -import ( - "context" - "net/http" - "net/http/httptest" - "testing" - - "github.com/gin-gonic/gin" - issue1298 "github.com/oapi-codegen/oapi-codegen/v2/internal/test/issues/issue-1298" - "github.com/stretchr/testify/assert" -) - -type testStrictServerInterface struct { - t *testing.T -} - -// (GET /test) -func (s *testStrictServerInterface) Test(ctx context.Context, request issue1298.TestRequestObject) (issue1298.TestResponseObject, error) { - assert.Equal(s.t, "test1", request.Body.Field1) - assert.Equal(s.t, "test2", request.Body.Field2) - return issue1298.Test204Response{}, nil -} - -func TestIssue1298(t *testing.T) { - g := gin.Default() - issue1298.RegisterHandlersWithOptions(g, - issue1298.NewStrictHandler(&testStrictServerInterface{t: t}, nil), - issue1298.GinServerOptions{}) - ts := httptest.NewServer(g) - defer ts.Close() - - c, err := issue1298.NewClientWithResponses(ts.URL) - assert.NoError(t, err) - res, err := c.TestWithApplicationTestPlusJSONBodyWithResponse( - context.TODO(), - issue1298.Test{ - Field1: "test1", - Field2: "test2", - }, - ) - assert.NoError(t, err) - assert.Equal(t, http.StatusNoContent, res.StatusCode()) -} diff --git a/internal/test/issues/issue-1378/bionicle.yaml b/internal/test/issues/issue-1378/bionicle.yaml deleted file mode 100644 index 0013d121a5..0000000000 --- a/internal/test/issues/issue-1378/bionicle.yaml +++ /dev/null @@ -1,43 +0,0 @@ -openapi: 3.0.1 - -info: - title: Test - description: Test - version: 1.0.0 - -paths: - /bionicle/{name}: - get: - parameters: - - $ref: "#/components/parameters/bionicleName" - responses: - '200': - content: - application/json: - schema: - $ref: '#/components/schemas/Bionicle' - '400': - content: - application/json: - schema: - oneOf: - - $ref: '#/components/schemas/Bionicle' - -components: - parameters: - bionicleName: - name: name - in: path - description: Name of the character - required: true - schema: - type: string - - schemas: - Bionicle: - type: object - properties: - name: - type: string - required: - - name diff --git a/internal/test/issues/issue-1378/bionicle/bionicle.gen.go b/internal/test/issues/issue-1378/bionicle/bionicle.gen.go deleted file mode 100644 index 863c5fd380..0000000000 --- a/internal/test/issues/issue-1378/bionicle/bionicle.gen.go +++ /dev/null @@ -1,369 +0,0 @@ -// Package bionicle provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package bionicle - -import ( - "bytes" - "compress/gzip" - "context" - "encoding/base64" - "encoding/json" - "fmt" - "net/http" - "net/url" - "path" - "strings" - - "github.com/getkin/kin-openapi/openapi3" - "github.com/gorilla/mux" - externalRef0 "github.com/oapi-codegen/oapi-codegen/v2/internal/test/issues/issue-1378/common" - "github.com/oapi-codegen/runtime" - strictnethttp "github.com/oapi-codegen/runtime/strictmiddleware/nethttp" -) - -// Bionicle defines model for Bionicle. -type Bionicle struct { - Name string `json:"name"` -} - -// BionicleName defines model for bionicleName. -type BionicleName = string - -// ServerInterface represents all server handlers. -type ServerInterface interface { - - // (GET /bionicle/{name}) - GetBionicleName(w http.ResponseWriter, r *http.Request, name BionicleName) -} - -// ServerInterfaceWrapper converts contexts to parameters. -type ServerInterfaceWrapper struct { - Handler ServerInterface - HandlerMiddlewares []MiddlewareFunc - ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) -} - -type MiddlewareFunc func(http.Handler) http.Handler - -// GetBionicleName operation middleware -func (siw *ServerInterfaceWrapper) GetBionicleName(w http.ResponseWriter, r *http.Request) { - - var err error - - // ------------- Path parameter "name" ------------- - var name BionicleName - - err = runtime.BindStyledParameterWithOptions("simple", "name", mux.Vars(r)["name"], &name, runtime.BindStyledParameterOptions{Explode: false, Required: true, Type: "string", Format: ""}) - if err != nil { - siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "name", Err: err}) - return - } - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.GetBionicleName(w, r, name) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -type UnescapedCookieParamError struct { - ParamName string - Err error -} - -func (e *UnescapedCookieParamError) Error() string { - return fmt.Sprintf("error unescaping cookie parameter '%s'", e.ParamName) -} - -func (e *UnescapedCookieParamError) Unwrap() error { - return e.Err -} - -type UnmarshalingParamError struct { - ParamName string - Err error -} - -func (e *UnmarshalingParamError) Error() string { - return fmt.Sprintf("Error unmarshaling parameter %s as JSON: %s", e.ParamName, e.Err.Error()) -} - -func (e *UnmarshalingParamError) Unwrap() error { - return e.Err -} - -type RequiredParamError struct { - ParamName string -} - -func (e *RequiredParamError) Error() string { - return fmt.Sprintf("Query argument %s is required, but not found", e.ParamName) -} - -type RequiredHeaderError struct { - ParamName string - Err error -} - -func (e *RequiredHeaderError) Error() string { - return fmt.Sprintf("Header parameter %s is required, but not found", e.ParamName) -} - -func (e *RequiredHeaderError) Unwrap() error { - return e.Err -} - -type InvalidParamFormatError struct { - ParamName string - Err error -} - -func (e *InvalidParamFormatError) Error() string { - return fmt.Sprintf("Invalid format for parameter %s: %s", e.ParamName, e.Err.Error()) -} - -func (e *InvalidParamFormatError) Unwrap() error { - return e.Err -} - -type TooManyValuesForParamError struct { - ParamName string - Count int -} - -func (e *TooManyValuesForParamError) Error() string { - return fmt.Sprintf("Expected one value for %s, got %d", e.ParamName, e.Count) -} - -// Handler creates http.Handler with routing matching OpenAPI spec. -func Handler(si ServerInterface) http.Handler { - return HandlerWithOptions(si, GorillaServerOptions{}) -} - -type GorillaServerOptions struct { - BaseURL string - BaseRouter *mux.Router - Middlewares []MiddlewareFunc - ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) -} - -// HandlerFromMux creates http.Handler with routing matching OpenAPI spec based on the provided mux. -func HandlerFromMux(si ServerInterface, r *mux.Router) http.Handler { - return HandlerWithOptions(si, GorillaServerOptions{ - BaseRouter: r, - }) -} - -func HandlerFromMuxWithBaseURL(si ServerInterface, r *mux.Router, baseURL string) http.Handler { - return HandlerWithOptions(si, GorillaServerOptions{ - BaseURL: baseURL, - BaseRouter: r, - }) -} - -// HandlerWithOptions creates http.Handler with additional options -func HandlerWithOptions(si ServerInterface, options GorillaServerOptions) http.Handler { - r := options.BaseRouter - - if r == nil { - r = mux.NewRouter() - } - if options.ErrorHandlerFunc == nil { - options.ErrorHandlerFunc = func(w http.ResponseWriter, r *http.Request, err error) { - http.Error(w, err.Error(), http.StatusBadRequest) - } - } - wrapper := ServerInterfaceWrapper{ - Handler: si, - HandlerMiddlewares: options.Middlewares, - ErrorHandlerFunc: options.ErrorHandlerFunc, - } - - r.HandleFunc(options.BaseURL+"/bionicle/{name}", wrapper.GetBionicleName).Methods("GET") - - return r -} - -type GetBionicleNameRequestObject struct { - Name BionicleName `json:"name"` -} - -type GetBionicleNameResponseObject interface { - VisitGetBionicleNameResponse(w http.ResponseWriter) error -} - -type GetBionicleName200JSONResponse Bionicle - -func (response GetBionicleName200JSONResponse) VisitGetBionicleNameResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(200) - - return json.NewEncoder(w).Encode(response) -} - -type GetBionicleName400JSONResponse struct { - union json.RawMessage -} - -func (response GetBionicleName400JSONResponse) VisitGetBionicleNameResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(400) - - return json.NewEncoder(w).Encode(response.union) -} - -// StrictServerInterface represents all server handlers. -type StrictServerInterface interface { - - // (GET /bionicle/{name}) - GetBionicleName(ctx context.Context, request GetBionicleNameRequestObject) (GetBionicleNameResponseObject, error) -} - -type StrictHandlerFunc = strictnethttp.StrictHTTPHandlerFunc -type StrictMiddlewareFunc = strictnethttp.StrictHTTPMiddlewareFunc - -type StrictHTTPServerOptions struct { - RequestErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) - ResponseErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) -} - -func NewStrictHandler(ssi StrictServerInterface, middlewares []StrictMiddlewareFunc) ServerInterface { - return &strictHandler{ssi: ssi, middlewares: middlewares, options: StrictHTTPServerOptions{ - RequestErrorHandlerFunc: func(w http.ResponseWriter, r *http.Request, err error) { - http.Error(w, err.Error(), http.StatusBadRequest) - }, - ResponseErrorHandlerFunc: func(w http.ResponseWriter, r *http.Request, err error) { - http.Error(w, err.Error(), http.StatusInternalServerError) - }, - }} -} - -func NewStrictHandlerWithOptions(ssi StrictServerInterface, middlewares []StrictMiddlewareFunc, options StrictHTTPServerOptions) ServerInterface { - return &strictHandler{ssi: ssi, middlewares: middlewares, options: options} -} - -type strictHandler struct { - ssi StrictServerInterface - middlewares []StrictMiddlewareFunc - options StrictHTTPServerOptions -} - -// GetBionicleName operation middleware -func (sh *strictHandler) GetBionicleName(w http.ResponseWriter, r *http.Request, name BionicleName) { - var request GetBionicleNameRequestObject - - request.Name = name - - handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { - return sh.ssi.GetBionicleName(ctx, request.(GetBionicleNameRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "GetBionicleName") - } - - response, err := handler(r.Context(), w, r, request) - - if err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } else if validResponse, ok := response.(GetBionicleNameResponseObject); ok { - if err := validResponse.VisitGetBionicleNameResponse(w); err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } - } else if response != nil { - sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) - } -} - -// Base64 encoded, gzipped, json marshaled Swagger object -var swaggerSpec = []string{ - - "H4sIAAAAAAAC/5SRMU8zMQyG/0rl7xujyxWYbuyCWGBhqzqkqa+XqpcEx0VCp/x35FyPXikMZLEcO3n8", - "+h3Ahj4Gj54TNANEQ6ZHRirZ1gXv7BGfTY+S7zBZcpFd8NCA3C5Cu+AOF7YzZCwjgQInxWi4AwW+vByD", - "AsK3kyPcQcN0QgXJdtgb+Zk/ovQlJuf3kHOeimWO1XmOMiGFiMQOS8WfJ/v+fs5aj10bNXWF7QEtjxTn", - "23Ar7RUTgwJ2LNApfUdKY31Z1VUNWUGI6E100MB9VVdLUEV4GU1P29OD8LPc7ZEliAIjqKcdNPCIvJov", - "Wl25sB7gP2ELDfzTF6/0pUVfuZQ3Ij3F4NO4obu6lmCDZ/SFbmI8Olv4+pBEzzBz4ifY2Qr95UMuu3v4", - "49fB40v7q6JbyCZP5zMAAP//9Jg3p6cCAAA=", -} - -// GetSwagger returns the content of the embedded swagger specification file -// or error if failed to decode -func decodeSpec() ([]byte, error) { - zipped, err := base64.StdEncoding.DecodeString(strings.Join(swaggerSpec, "")) - if err != nil { - return nil, fmt.Errorf("error base64 decoding spec: %w", err) - } - zr, err := gzip.NewReader(bytes.NewReader(zipped)) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - var buf bytes.Buffer - _, err = buf.ReadFrom(zr) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - - return buf.Bytes(), nil -} - -var rawSpec = decodeSpecCached() - -// a naive cached of a decoded swagger spec -func decodeSpecCached() func() ([]byte, error) { - data, err := decodeSpec() - return func() ([]byte, error) { - return data, err - } -} - -// Constructs a synthetic filesystem for resolving external references when loading openapi specifications. -func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { - res := make(map[string]func() ([]byte, error)) - if len(pathToFile) > 0 { - res[pathToFile] = rawSpec - } - - for rawPath, rawFunc := range externalRef0.PathToRawSpec(path.Join(path.Dir(pathToFile), "common.yaml")) { - if _, ok := res[rawPath]; ok { - // it is not possible to compare functions in golang, so always overwrite the old value - } - res[rawPath] = rawFunc - } - return res -} - -// GetSwagger returns the Swagger specification corresponding to the generated code -// in this file. The external references of Swagger specification are resolved. -// The logic of resolving external references is tightly connected to "import-mapping" feature. -// Externally referenced files must be embedded in the corresponding golang packages. -// Urls can be supported but this task was out of the scope. -func GetSwagger() (swagger *openapi3.T, err error) { - resolvePath := PathToRawSpec("") - - loader := openapi3.NewLoader() - loader.IsExternalRefsAllowed = true - loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() - pathToFile = path.Clean(pathToFile) - getSpec, ok := resolvePath[pathToFile] - if !ok { - err1 := fmt.Errorf("path not found: %s", pathToFile) - return nil, err1 - } - return getSpec() - } - var specData []byte - specData, err = rawSpec() - if err != nil { - return - } - swagger, err = loader.LoadFromData(specData) - if err != nil { - return - } - return -} diff --git a/internal/test/issues/issue-1378/bionicle/config.yaml b/internal/test/issues/issue-1378/bionicle/config.yaml deleted file mode 100644 index 4f81605dc4..0000000000 --- a/internal/test/issues/issue-1378/bionicle/config.yaml +++ /dev/null @@ -1,10 +0,0 @@ -# yaml-language-server: $schema=../../../../../configuration-schema.json -package: bionicle -generate: - gorilla-server: true - embedded-spec: true - strict-server: true - models: true -import-mapping: - common.yaml: github.com/oapi-codegen/oapi-codegen/v2/internal/test/issues/issue-1378/common -output: bionicle.gen.go diff --git a/internal/test/issues/issue-1378/bionicle/generate.go b/internal/test/issues/issue-1378/bionicle/generate.go deleted file mode 100644 index 26b3661696..0000000000 --- a/internal/test/issues/issue-1378/bionicle/generate.go +++ /dev/null @@ -1,3 +0,0 @@ -package bionicle - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml ../bionicle.yaml diff --git a/internal/test/issues/issue-1378/common.yaml b/internal/test/issues/issue-1378/common.yaml deleted file mode 100644 index 8aac6cdf4c..0000000000 --- a/internal/test/issues/issue-1378/common.yaml +++ /dev/null @@ -1,16 +0,0 @@ -openapi: 3.0.1 - -info: - title: Test - description: Test - version: 1.0.0 - -components: - schemas: - ErrTracingIdNotSent: - type: object - properties: - code: - type: string - required: - - code diff --git a/internal/test/issues/issue-1378/common/common.gen.go b/internal/test/issues/issue-1378/common/common.gen.go deleted file mode 100644 index d1747783e0..0000000000 --- a/internal/test/issues/issue-1378/common/common.gen.go +++ /dev/null @@ -1,262 +0,0 @@ -// Package common provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package common - -import ( - "bytes" - "compress/gzip" - "encoding/base64" - "fmt" - "net/http" - "net/url" - "path" - "strings" - - "github.com/getkin/kin-openapi/openapi3" - "github.com/gorilla/mux" - strictnethttp "github.com/oapi-codegen/runtime/strictmiddleware/nethttp" -) - -// ErrTracingIdNotSent defines model for ErrTracingIdNotSent. -type ErrTracingIdNotSent struct { - Code string `json:"code"` -} - -// ServerInterface represents all server handlers. -type ServerInterface interface { -} - -// ServerInterfaceWrapper converts contexts to parameters. -type ServerInterfaceWrapper struct { - Handler ServerInterface - HandlerMiddlewares []MiddlewareFunc - ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) -} - -type MiddlewareFunc func(http.Handler) http.Handler - -type UnescapedCookieParamError struct { - ParamName string - Err error -} - -func (e *UnescapedCookieParamError) Error() string { - return fmt.Sprintf("error unescaping cookie parameter '%s'", e.ParamName) -} - -func (e *UnescapedCookieParamError) Unwrap() error { - return e.Err -} - -type UnmarshalingParamError struct { - ParamName string - Err error -} - -func (e *UnmarshalingParamError) Error() string { - return fmt.Sprintf("Error unmarshaling parameter %s as JSON: %s", e.ParamName, e.Err.Error()) -} - -func (e *UnmarshalingParamError) Unwrap() error { - return e.Err -} - -type RequiredParamError struct { - ParamName string -} - -func (e *RequiredParamError) Error() string { - return fmt.Sprintf("Query argument %s is required, but not found", e.ParamName) -} - -type RequiredHeaderError struct { - ParamName string - Err error -} - -func (e *RequiredHeaderError) Error() string { - return fmt.Sprintf("Header parameter %s is required, but not found", e.ParamName) -} - -func (e *RequiredHeaderError) Unwrap() error { - return e.Err -} - -type InvalidParamFormatError struct { - ParamName string - Err error -} - -func (e *InvalidParamFormatError) Error() string { - return fmt.Sprintf("Invalid format for parameter %s: %s", e.ParamName, e.Err.Error()) -} - -func (e *InvalidParamFormatError) Unwrap() error { - return e.Err -} - -type TooManyValuesForParamError struct { - ParamName string - Count int -} - -func (e *TooManyValuesForParamError) Error() string { - return fmt.Sprintf("Expected one value for %s, got %d", e.ParamName, e.Count) -} - -// Handler creates http.Handler with routing matching OpenAPI spec. -func Handler(si ServerInterface) http.Handler { - return HandlerWithOptions(si, GorillaServerOptions{}) -} - -type GorillaServerOptions struct { - BaseURL string - BaseRouter *mux.Router - Middlewares []MiddlewareFunc - ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) -} - -// HandlerFromMux creates http.Handler with routing matching OpenAPI spec based on the provided mux. -func HandlerFromMux(si ServerInterface, r *mux.Router) http.Handler { - return HandlerWithOptions(si, GorillaServerOptions{ - BaseRouter: r, - }) -} - -func HandlerFromMuxWithBaseURL(si ServerInterface, r *mux.Router, baseURL string) http.Handler { - return HandlerWithOptions(si, GorillaServerOptions{ - BaseURL: baseURL, - BaseRouter: r, - }) -} - -// HandlerWithOptions creates http.Handler with additional options -func HandlerWithOptions(si ServerInterface, options GorillaServerOptions) http.Handler { - r := options.BaseRouter - - if r == nil { - r = mux.NewRouter() - } - if options.ErrorHandlerFunc == nil { - options.ErrorHandlerFunc = func(w http.ResponseWriter, r *http.Request, err error) { - http.Error(w, err.Error(), http.StatusBadRequest) - } - } - - return r -} - -// StrictServerInterface represents all server handlers. -type StrictServerInterface interface { -} - -type StrictHandlerFunc = strictnethttp.StrictHTTPHandlerFunc -type StrictMiddlewareFunc = strictnethttp.StrictHTTPMiddlewareFunc - -type StrictHTTPServerOptions struct { - RequestErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) - ResponseErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) -} - -func NewStrictHandler(ssi StrictServerInterface, middlewares []StrictMiddlewareFunc) ServerInterface { - return &strictHandler{ssi: ssi, middlewares: middlewares, options: StrictHTTPServerOptions{ - RequestErrorHandlerFunc: func(w http.ResponseWriter, r *http.Request, err error) { - http.Error(w, err.Error(), http.StatusBadRequest) - }, - ResponseErrorHandlerFunc: func(w http.ResponseWriter, r *http.Request, err error) { - http.Error(w, err.Error(), http.StatusInternalServerError) - }, - }} -} - -func NewStrictHandlerWithOptions(ssi StrictServerInterface, middlewares []StrictMiddlewareFunc, options StrictHTTPServerOptions) ServerInterface { - return &strictHandler{ssi: ssi, middlewares: middlewares, options: options} -} - -type strictHandler struct { - ssi StrictServerInterface - middlewares []StrictMiddlewareFunc - options StrictHTTPServerOptions -} - -// Base64 encoded, gzipped, json marshaled Swagger object -var swaggerSpec = []string{ - - "H4sIAAAAAAAC/0TMP08DMQwF8O/y5uh0FVt2BhYWuiGGkJjW6Gobx0VCVb47Sk+IyX/eT++GqhdTIYmO", - "fEOvZ7qU+/rofvRSWU5P7VnjhSTm21yNPJjuqGqjOePHCBk9nOWEMRKcvq7s1JBfd/WW/pS+f1INjMlY", - "PnQWNOrV2YJVkHGkHkgIjo3+z2/yvueHZV1WjAQ1kmKMjIdlXQ5IsBLnjizXbRu/AQAA//9/cprb3gAA", - "AA==", -} - -// GetSwagger returns the content of the embedded swagger specification file -// or error if failed to decode -func decodeSpec() ([]byte, error) { - zipped, err := base64.StdEncoding.DecodeString(strings.Join(swaggerSpec, "")) - if err != nil { - return nil, fmt.Errorf("error base64 decoding spec: %w", err) - } - zr, err := gzip.NewReader(bytes.NewReader(zipped)) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - var buf bytes.Buffer - _, err = buf.ReadFrom(zr) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - - return buf.Bytes(), nil -} - -var rawSpec = decodeSpecCached() - -// a naive cached of a decoded swagger spec -func decodeSpecCached() func() ([]byte, error) { - data, err := decodeSpec() - return func() ([]byte, error) { - return data, err - } -} - -// Constructs a synthetic filesystem for resolving external references when loading openapi specifications. -func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { - res := make(map[string]func() ([]byte, error)) - if len(pathToFile) > 0 { - res[pathToFile] = rawSpec - } - - return res -} - -// GetSwagger returns the Swagger specification corresponding to the generated code -// in this file. The external references of Swagger specification are resolved. -// The logic of resolving external references is tightly connected to "import-mapping" feature. -// Externally referenced files must be embedded in the corresponding golang packages. -// Urls can be supported but this task was out of the scope. -func GetSwagger() (swagger *openapi3.T, err error) { - resolvePath := PathToRawSpec("") - - loader := openapi3.NewLoader() - loader.IsExternalRefsAllowed = true - loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() - pathToFile = path.Clean(pathToFile) - getSpec, ok := resolvePath[pathToFile] - if !ok { - err1 := fmt.Errorf("path not found: %s", pathToFile) - return nil, err1 - } - return getSpec() - } - var specData []byte - specData, err = rawSpec() - if err != nil { - return - } - swagger, err = loader.LoadFromData(specData) - if err != nil { - return - } - return -} diff --git a/internal/test/issues/issue-1378/common/config.yaml b/internal/test/issues/issue-1378/common/config.yaml deleted file mode 100644 index 2d2960cdcf..0000000000 --- a/internal/test/issues/issue-1378/common/config.yaml +++ /dev/null @@ -1,10 +0,0 @@ -# yaml-language-server: $schema=../../../../../configuration-schema.json -package: common -generate: - gorilla-server: true - embedded-spec: true - strict-server: true - models: true -output-options: - skip-prune: true -output: common.gen.go diff --git a/internal/test/issues/issue-1378/common/generate.go b/internal/test/issues/issue-1378/common/generate.go deleted file mode 100644 index dbb23b05d1..0000000000 --- a/internal/test/issues/issue-1378/common/generate.go +++ /dev/null @@ -1,3 +0,0 @@ -package common - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml ../common.yaml diff --git a/internal/test/issues/issue-1378/foo-service.yaml b/internal/test/issues/issue-1378/foo-service.yaml deleted file mode 100644 index ebd8447440..0000000000 --- a/internal/test/issues/issue-1378/foo-service.yaml +++ /dev/null @@ -1,10 +0,0 @@ -openapi: 3.0.1 - -info: - title: Test - description: Test - version: 1.0.0 - -paths: - /bionicle/{name}: - $ref: "bionicle.yaml#/paths/~1bionicle~1{name}" diff --git a/internal/test/issues/issue-1378/fooservice/config.yaml b/internal/test/issues/issue-1378/fooservice/config.yaml deleted file mode 100644 index 4690bd037e..0000000000 --- a/internal/test/issues/issue-1378/fooservice/config.yaml +++ /dev/null @@ -1,11 +0,0 @@ -# yaml-language-server: $schema=../../../../../configuration-schema.json -package: fooservice -generate: - gorilla-server: true - embedded-spec: true - strict-server: true - models: true -import-mapping: - common.yaml: github.com/oapi-codegen/oapi-codegen/v2/internal/test/issues/issue-1378/common - bionicle.yaml: github.com/oapi-codegen/oapi-codegen/v2/internal/test/issues/issue-1378/bionicle -output: fooservice.gen.go diff --git a/internal/test/issues/issue-1378/fooservice/fooservice.gen.go b/internal/test/issues/issue-1378/fooservice/fooservice.gen.go deleted file mode 100644 index d076409c14..0000000000 --- a/internal/test/issues/issue-1378/fooservice/fooservice.gen.go +++ /dev/null @@ -1,368 +0,0 @@ -// Package fooservice provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package fooservice - -import ( - "bytes" - "compress/gzip" - "context" - "encoding/base64" - "encoding/json" - "fmt" - "net/http" - "net/url" - "path" - "strings" - - "github.com/getkin/kin-openapi/openapi3" - "github.com/gorilla/mux" - externalRef0 "github.com/oapi-codegen/oapi-codegen/v2/internal/test/issues/issue-1378/bionicle" - externalRef1 "github.com/oapi-codegen/oapi-codegen/v2/internal/test/issues/issue-1378/common" - "github.com/oapi-codegen/runtime" - strictnethttp "github.com/oapi-codegen/runtime/strictmiddleware/nethttp" -) - -// ServerInterface represents all server handlers. -type ServerInterface interface { - - // (GET /bionicle/{name}) - GetBionicleName(w http.ResponseWriter, r *http.Request, name externalRef0.BionicleName) -} - -// ServerInterfaceWrapper converts contexts to parameters. -type ServerInterfaceWrapper struct { - Handler ServerInterface - HandlerMiddlewares []MiddlewareFunc - ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) -} - -type MiddlewareFunc func(http.Handler) http.Handler - -// GetBionicleName operation middleware -func (siw *ServerInterfaceWrapper) GetBionicleName(w http.ResponseWriter, r *http.Request) { - - var err error - - // ------------- Path parameter "name" ------------- - var name externalRef0.BionicleName - - err = runtime.BindStyledParameterWithOptions("simple", "name", mux.Vars(r)["name"], &name, runtime.BindStyledParameterOptions{Explode: false, Required: true, Type: "string", Format: ""}) - if err != nil { - siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "name", Err: err}) - return - } - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.GetBionicleName(w, r, name) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -type UnescapedCookieParamError struct { - ParamName string - Err error -} - -func (e *UnescapedCookieParamError) Error() string { - return fmt.Sprintf("error unescaping cookie parameter '%s'", e.ParamName) -} - -func (e *UnescapedCookieParamError) Unwrap() error { - return e.Err -} - -type UnmarshalingParamError struct { - ParamName string - Err error -} - -func (e *UnmarshalingParamError) Error() string { - return fmt.Sprintf("Error unmarshaling parameter %s as JSON: %s", e.ParamName, e.Err.Error()) -} - -func (e *UnmarshalingParamError) Unwrap() error { - return e.Err -} - -type RequiredParamError struct { - ParamName string -} - -func (e *RequiredParamError) Error() string { - return fmt.Sprintf("Query argument %s is required, but not found", e.ParamName) -} - -type RequiredHeaderError struct { - ParamName string - Err error -} - -func (e *RequiredHeaderError) Error() string { - return fmt.Sprintf("Header parameter %s is required, but not found", e.ParamName) -} - -func (e *RequiredHeaderError) Unwrap() error { - return e.Err -} - -type InvalidParamFormatError struct { - ParamName string - Err error -} - -func (e *InvalidParamFormatError) Error() string { - return fmt.Sprintf("Invalid format for parameter %s: %s", e.ParamName, e.Err.Error()) -} - -func (e *InvalidParamFormatError) Unwrap() error { - return e.Err -} - -type TooManyValuesForParamError struct { - ParamName string - Count int -} - -func (e *TooManyValuesForParamError) Error() string { - return fmt.Sprintf("Expected one value for %s, got %d", e.ParamName, e.Count) -} - -// Handler creates http.Handler with routing matching OpenAPI spec. -func Handler(si ServerInterface) http.Handler { - return HandlerWithOptions(si, GorillaServerOptions{}) -} - -type GorillaServerOptions struct { - BaseURL string - BaseRouter *mux.Router - Middlewares []MiddlewareFunc - ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) -} - -// HandlerFromMux creates http.Handler with routing matching OpenAPI spec based on the provided mux. -func HandlerFromMux(si ServerInterface, r *mux.Router) http.Handler { - return HandlerWithOptions(si, GorillaServerOptions{ - BaseRouter: r, - }) -} - -func HandlerFromMuxWithBaseURL(si ServerInterface, r *mux.Router, baseURL string) http.Handler { - return HandlerWithOptions(si, GorillaServerOptions{ - BaseURL: baseURL, - BaseRouter: r, - }) -} - -// HandlerWithOptions creates http.Handler with additional options -func HandlerWithOptions(si ServerInterface, options GorillaServerOptions) http.Handler { - r := options.BaseRouter - - if r == nil { - r = mux.NewRouter() - } - if options.ErrorHandlerFunc == nil { - options.ErrorHandlerFunc = func(w http.ResponseWriter, r *http.Request, err error) { - http.Error(w, err.Error(), http.StatusBadRequest) - } - } - wrapper := ServerInterfaceWrapper{ - Handler: si, - HandlerMiddlewares: options.Middlewares, - ErrorHandlerFunc: options.ErrorHandlerFunc, - } - - r.HandleFunc(options.BaseURL+"/bionicle/{name}", wrapper.GetBionicleName).Methods("GET") - - return r -} - -type GetBionicleNameRequestObject struct { - Name externalRef0.BionicleName `json:"name"` -} - -type GetBionicleNameResponseObject interface { - VisitGetBionicleNameResponse(w http.ResponseWriter) error -} - -type GetBionicleName200JSONResponse externalRef0.Bionicle - -func (response GetBionicleName200JSONResponse) VisitGetBionicleNameResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(200) - - return json.NewEncoder(w).Encode(response) -} - -type GetBionicleName400JSONResponse struct { - union json.RawMessage -} - -func (response GetBionicleName400JSONResponse) VisitGetBionicleNameResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(400) - - return json.NewEncoder(w).Encode(response.union) -} - -// StrictServerInterface represents all server handlers. -type StrictServerInterface interface { - - // (GET /bionicle/{name}) - GetBionicleName(ctx context.Context, request GetBionicleNameRequestObject) (GetBionicleNameResponseObject, error) -} - -type StrictHandlerFunc = strictnethttp.StrictHTTPHandlerFunc -type StrictMiddlewareFunc = strictnethttp.StrictHTTPMiddlewareFunc - -type StrictHTTPServerOptions struct { - RequestErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) - ResponseErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) -} - -func NewStrictHandler(ssi StrictServerInterface, middlewares []StrictMiddlewareFunc) ServerInterface { - return &strictHandler{ssi: ssi, middlewares: middlewares, options: StrictHTTPServerOptions{ - RequestErrorHandlerFunc: func(w http.ResponseWriter, r *http.Request, err error) { - http.Error(w, err.Error(), http.StatusBadRequest) - }, - ResponseErrorHandlerFunc: func(w http.ResponseWriter, r *http.Request, err error) { - http.Error(w, err.Error(), http.StatusInternalServerError) - }, - }} -} - -func NewStrictHandlerWithOptions(ssi StrictServerInterface, middlewares []StrictMiddlewareFunc, options StrictHTTPServerOptions) ServerInterface { - return &strictHandler{ssi: ssi, middlewares: middlewares, options: options} -} - -type strictHandler struct { - ssi StrictServerInterface - middlewares []StrictMiddlewareFunc - options StrictHTTPServerOptions -} - -// GetBionicleName operation middleware -func (sh *strictHandler) GetBionicleName(w http.ResponseWriter, r *http.Request, name externalRef0.BionicleName) { - var request GetBionicleNameRequestObject - - request.Name = name - - handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { - return sh.ssi.GetBionicleName(ctx, request.(GetBionicleNameRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "GetBionicleName") - } - - response, err := handler(r.Context(), w, r, request) - - if err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } else if validResponse, ok := response.(GetBionicleNameResponseObject); ok { - if err := validResponse.VisitGetBionicleNameResponse(w); err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } - } else if response != nil { - sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) - } -} - -// Base64 encoded, gzipped, json marshaled Swagger object -var swaggerSpec = []string{ - - "H4sIAAAAAAAC/5RRQU/zMAz9K5O/7xg1HXDqcRfEBS7cpgllmbtmWpPgeEioyn9HTldtYwOJXpzEr37P", - "7w1gQx+DR88JmgGiIdMjI5Xb2gXv7B7fpsOz6VEaG0yWXGQXPDQgr7PQzrjDme0MGctIoMBJMxruQIEv", - "f45FAeH7wRFuoGE6oIJkO+yNTObPKLjE5PwWcs5T81LQ4ngomilEJHZYIP4o8fugc9LliFqpCRXWO7Q8", - "0jnfhusdXzExKGDHQjpdP5DS2J9XdVVDVhAiehMdNHBf1dUcVHGgSNOTfD0If5a3LbIU2cAI1dMGGnhE", - "Xpw7ri5yWQ7wn7CFBv7pU3r6BNG3c8sr8SDF4NNo1V1dS7HBM/oiw8S4d7YI0bskiw1n2dxiPYajr5PJ", - "xc2HP3IEjy/tjzv+wrbK0/cVAAD//37MjEPUAgAA", -} - -// GetSwagger returns the content of the embedded swagger specification file -// or error if failed to decode -func decodeSpec() ([]byte, error) { - zipped, err := base64.StdEncoding.DecodeString(strings.Join(swaggerSpec, "")) - if err != nil { - return nil, fmt.Errorf("error base64 decoding spec: %w", err) - } - zr, err := gzip.NewReader(bytes.NewReader(zipped)) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - var buf bytes.Buffer - _, err = buf.ReadFrom(zr) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - - return buf.Bytes(), nil -} - -var rawSpec = decodeSpecCached() - -// a naive cached of a decoded swagger spec -func decodeSpecCached() func() ([]byte, error) { - data, err := decodeSpec() - return func() ([]byte, error) { - return data, err - } -} - -// Constructs a synthetic filesystem for resolving external references when loading openapi specifications. -func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { - res := make(map[string]func() ([]byte, error)) - if len(pathToFile) > 0 { - res[pathToFile] = rawSpec - } - - for rawPath, rawFunc := range externalRef0.PathToRawSpec(path.Join(path.Dir(pathToFile), "bionicle.yaml")) { - if _, ok := res[rawPath]; ok { - // it is not possible to compare functions in golang, so always overwrite the old value - } - res[rawPath] = rawFunc - } - for rawPath, rawFunc := range externalRef1.PathToRawSpec(path.Join(path.Dir(pathToFile), "common.yaml")) { - if _, ok := res[rawPath]; ok { - // it is not possible to compare functions in golang, so always overwrite the old value - } - res[rawPath] = rawFunc - } - return res -} - -// GetSwagger returns the Swagger specification corresponding to the generated code -// in this file. The external references of Swagger specification are resolved. -// The logic of resolving external references is tightly connected to "import-mapping" feature. -// Externally referenced files must be embedded in the corresponding golang packages. -// Urls can be supported but this task was out of the scope. -func GetSwagger() (swagger *openapi3.T, err error) { - resolvePath := PathToRawSpec("") - - loader := openapi3.NewLoader() - loader.IsExternalRefsAllowed = true - loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() - pathToFile = path.Clean(pathToFile) - getSpec, ok := resolvePath[pathToFile] - if !ok { - err1 := fmt.Errorf("path not found: %s", pathToFile) - return nil, err1 - } - return getSpec() - } - var specData []byte - specData, err = rawSpec() - if err != nil { - return - } - swagger, err = loader.LoadFromData(specData) - if err != nil { - return - } - return -} diff --git a/internal/test/issues/issue-1378/fooservice/generate.go b/internal/test/issues/issue-1378/fooservice/generate.go deleted file mode 100644 index 2419719dbf..0000000000 --- a/internal/test/issues/issue-1378/fooservice/generate.go +++ /dev/null @@ -1,3 +0,0 @@ -package fooservice - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml ../foo-service.yaml diff --git a/internal/test/issues/issue-1397/config.yaml b/internal/test/issues/issue-1397/config.yaml deleted file mode 100644 index d4a1284eeb..0000000000 --- a/internal/test/issues/issue-1397/config.yaml +++ /dev/null @@ -1,8 +0,0 @@ -# yaml-language-server: $schema=../../../../configuration-schema.json -package: issue1397 -generate: - echo-server: true - client: true - models: true - embedded-spec: true -output: issue1397.gen.go diff --git a/internal/test/issues/issue-1397/doc.go b/internal/test/issues/issue-1397/doc.go deleted file mode 100644 index e5964fe298..0000000000 --- a/internal/test/issues/issue-1397/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -package issue1397 - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml spec.yaml diff --git a/internal/test/issues/issue-1397/issue1397.gen.go b/internal/test/issues/issue-1397/issue1397.gen.go deleted file mode 100644 index 11bc883db2..0000000000 --- a/internal/test/issues/issue-1397/issue1397.gen.go +++ /dev/null @@ -1,452 +0,0 @@ -// Package issue1397 provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package issue1397 - -import ( - "bytes" - "compress/gzip" - "context" - "encoding/base64" - "encoding/json" - "fmt" - "io" - "net/http" - "net/url" - "path" - "strings" - - "github.com/getkin/kin-openapi/openapi3" - "github.com/labstack/echo/v4" -) - -// Defines values for TestField1. -const ( - Option1 TestField1 = "option1" - Option2 TestField1 = "option2" -) - -// Valid indicates whether the value is a known member of the TestField1 enum. -func (e TestField1) Valid() bool { - switch e { - case Option1: - return true - case Option2: - return true - default: - return false - } -} - -// Test defines model for Test. -type Test = MyTestRequest - -// TestField1 defines model for Test.Field1. -type TestField1 string - -// MyTestRequestNestedField A nested object with allocated name -type MyTestRequestNestedField struct { - Field1 bool `json:"field1"` - Field2 string `json:"field2"` -} - -// MyTestRequest defines model for . -type MyTestRequest struct { - // Field1 A array of enum values - Field1 *[]TestField1 `json:"field1,omitempty"` - - // Field2 A nested object with allocated name - Field2 *MyTestRequestNestedField `json:"field2,omitempty"` - - // Field3 A nested object without allocated name - Field3 *struct { - Field1 bool `json:"field1"` - Field2 string `json:"field2"` - } `json:"field3,omitempty"` -} - -// TestApplicationTestPlusJSONRequestBody defines body for Test for application/test+json ContentType. -type TestApplicationTestPlusJSONRequestBody = Test - -// RequestEditorFn is the function signature for the RequestEditor callback function -type RequestEditorFn func(ctx context.Context, req *http.Request) error - -// Doer performs HTTP requests. -// -// The standard http.Client implements this interface. -type HttpRequestDoer interface { - Do(req *http.Request) (*http.Response, error) -} - -// Client which conforms to the OpenAPI3 specification for this service. -type Client struct { - // The endpoint of the server conforming to this interface, with scheme, - // https://api.deepmap.com for example. This can contain a path relative - // to the server, such as https://api.deepmap.com/dev-test, and all the - // paths in the swagger spec will be appended to the server. - Server string - - // Doer for performing requests, typically a *http.Client with any - // customized settings, such as certificate chains. - Client HttpRequestDoer - - // A list of callbacks for modifying requests which are generated before sending over - // the network. - RequestEditors []RequestEditorFn -} - -// ClientOption allows setting custom parameters during construction -type ClientOption func(*Client) error - -// Creates a new Client, with reasonable defaults -func NewClient(server string, opts ...ClientOption) (*Client, error) { - // create a client with sane default values - client := Client{ - Server: server, - } - // mutate client and add all optional params - for _, o := range opts { - if err := o(&client); err != nil { - return nil, err - } - } - // ensure the server URL always has a trailing slash - if !strings.HasSuffix(client.Server, "/") { - client.Server += "/" - } - // create httpClient, if not already present - if client.Client == nil { - client.Client = &http.Client{} - } - return &client, nil -} - -// WithHTTPClient allows overriding the default Doer, which is -// automatically created using http.Client. This is useful for tests. -func WithHTTPClient(doer HttpRequestDoer) ClientOption { - return func(c *Client) error { - c.Client = doer - return nil - } -} - -// WithRequestEditorFn allows setting up a callback function, which will be -// called right before sending the request. This can be used to mutate the request. -func WithRequestEditorFn(fn RequestEditorFn) ClientOption { - return func(c *Client) error { - c.RequestEditors = append(c.RequestEditors, fn) - return nil - } -} - -// The interface specification for the client above. -type ClientInterface interface { - // TestWithBody request with any body - TestWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) - - TestWithApplicationTestPlusJSONBody(ctx context.Context, body TestApplicationTestPlusJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) -} - -func (c *Client) TestWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewTestRequestWithBody(c.Server, contentType, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) TestWithApplicationTestPlusJSONBody(ctx context.Context, body TestApplicationTestPlusJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewTestRequestWithApplicationTestPlusJSONBody(c.Server, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -// NewTestRequestWithApplicationTestPlusJSONBody calls the generic Test builder with application/test+json body -func NewTestRequestWithApplicationTestPlusJSONBody(server string, body TestApplicationTestPlusJSONRequestBody) (*http.Request, error) { - var bodyReader io.Reader - buf, err := json.Marshal(body) - if err != nil { - return nil, err - } - bodyReader = bytes.NewReader(buf) - return NewTestRequestWithBody(server, "application/test+json", bodyReader) -} - -// NewTestRequestWithBody generates requests for Test with any type of body -func NewTestRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/test") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), body) - if err != nil { - return nil, err - } - - req.Header.Add("Content-Type", contentType) - - return req, nil -} - -func (c *Client) applyEditors(ctx context.Context, req *http.Request, additionalEditors []RequestEditorFn) error { - for _, r := range c.RequestEditors { - if err := r(ctx, req); err != nil { - return err - } - } - for _, r := range additionalEditors { - if err := r(ctx, req); err != nil { - return err - } - } - return nil -} - -// ClientWithResponses builds on ClientInterface to offer response payloads -type ClientWithResponses struct { - ClientInterface -} - -// NewClientWithResponses creates a new ClientWithResponses, which wraps -// Client with return type handling -func NewClientWithResponses(server string, opts ...ClientOption) (*ClientWithResponses, error) { - client, err := NewClient(server, opts...) - if err != nil { - return nil, err - } - return &ClientWithResponses{client}, nil -} - -// WithBaseURL overrides the baseURL. -func WithBaseURL(baseURL string) ClientOption { - return func(c *Client) error { - newBaseURL, err := url.Parse(baseURL) - if err != nil { - return err - } - c.Server = newBaseURL.String() - return nil - } -} - -// ClientWithResponsesInterface is the interface specification for the client with responses above. -type ClientWithResponsesInterface interface { - // TestWithBodyWithResponse request with any body - TestWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*TestResponse, error) - - TestWithApplicationTestPlusJSONBodyWithResponse(ctx context.Context, body TestApplicationTestPlusJSONRequestBody, reqEditors ...RequestEditorFn) (*TestResponse, error) -} - -type TestResponse struct { - Body []byte - HTTPResponse *http.Response -} - -// Status returns HTTPResponse.Status -func (r TestResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r TestResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -// TestWithBodyWithResponse request with arbitrary body returning *TestResponse -func (c *ClientWithResponses) TestWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*TestResponse, error) { - rsp, err := c.TestWithBody(ctx, contentType, body, reqEditors...) - if err != nil { - return nil, err - } - return ParseTestResponse(rsp) -} - -func (c *ClientWithResponses) TestWithApplicationTestPlusJSONBodyWithResponse(ctx context.Context, body TestApplicationTestPlusJSONRequestBody, reqEditors ...RequestEditorFn) (*TestResponse, error) { - rsp, err := c.TestWithApplicationTestPlusJSONBody(ctx, body, reqEditors...) - if err != nil { - return nil, err - } - return ParseTestResponse(rsp) -} - -// ParseTestResponse parses an HTTP response from a TestWithResponse call -func ParseTestResponse(rsp *http.Response) (*TestResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &TestResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - return response, nil -} - -// ServerInterface represents all server handlers. -type ServerInterface interface { - - // (GET /test) - Test(ctx echo.Context) error -} - -// ServerInterfaceWrapper converts echo contexts to parameters. -type ServerInterfaceWrapper struct { - Handler ServerInterface -} - -// Test converts echo context to params. -func (w *ServerInterfaceWrapper) Test(ctx echo.Context) error { - var err error - - // Invoke the callback with all the unmarshaled arguments - err = w.Handler.Test(ctx) - return err -} - -// This is a simple interface which specifies echo.Route addition functions which -// are present on both echo.Echo and echo.Group, since we want to allow using -// either of them for path registration -type EchoRouter interface { - CONNECT(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - DELETE(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - GET(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - HEAD(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - OPTIONS(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - PATCH(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - POST(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - PUT(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - TRACE(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route -} - -// RegisterHandlers adds each server route to the EchoRouter. -func RegisterHandlers(router EchoRouter, si ServerInterface) { - RegisterHandlersWithBaseURL(router, si, "") -} - -// Registers handlers, and prepends BaseURL to the paths, so that the paths -// can be served under a prefix. -func RegisterHandlersWithBaseURL(router EchoRouter, si ServerInterface, baseURL string) { - - wrapper := ServerInterfaceWrapper{ - Handler: si, - } - - router.GET(baseURL+"/test", wrapper.Test) - -} - -// Base64 encoded, gzipped, json marshaled Swagger object -var swaggerSpec = []string{ - - "H4sIAAAAAAAC/8xTO2/bMBD+K8K1W2XLj3bh1g4FPLRD4C3IQEsnmQbFo8lTYsHQfw+OUmzkBSRbJh2O", - "9/F76HiGklpPDh1HUGeI5R5bncotRpavD+QxsMHUrQ3aailVhbEMxrMhBwp+ZzoE3WdUZ+i6NrvXtsMI", - "ORjGNiGlDeoWKEGWkE/VCu5y4N4jKIgcjGtgyKHVp82I/HU5TQxymESs3hLhMDJWGe0OWHL2YHifaWup", - "1NJ1ukXI3zU0seyILGr3nOeFviGHgMfOBKzE0nTHBXA1NAqBHE6zhmbSnCUVCv71EvANHjuM/D/J/ivo", - "C+/6Y/6o4y9hUQCfMw2DYIyrCZTrrJWFQKe9AQXr+WIubF7zPnkoeFrHBtNH/GmJZVOBGnd1FIyR/1DV", - "y0xJjtGlce29NWUCpJt+HKIk+rTwUn0PWIOCb8X1RRTTcyi2k9wUSvTk4pjsavHz9V9qiKo0PAyPAQAA", - "///99gukXwMAAA==", -} - -// GetSwagger returns the content of the embedded swagger specification file -// or error if failed to decode -func decodeSpec() ([]byte, error) { - zipped, err := base64.StdEncoding.DecodeString(strings.Join(swaggerSpec, "")) - if err != nil { - return nil, fmt.Errorf("error base64 decoding spec: %w", err) - } - zr, err := gzip.NewReader(bytes.NewReader(zipped)) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - var buf bytes.Buffer - _, err = buf.ReadFrom(zr) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - - return buf.Bytes(), nil -} - -var rawSpec = decodeSpecCached() - -// a naive cached of a decoded swagger spec -func decodeSpecCached() func() ([]byte, error) { - data, err := decodeSpec() - return func() ([]byte, error) { - return data, err - } -} - -// Constructs a synthetic filesystem for resolving external references when loading openapi specifications. -func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { - res := make(map[string]func() ([]byte, error)) - if len(pathToFile) > 0 { - res[pathToFile] = rawSpec - } - - return res -} - -// GetSwagger returns the Swagger specification corresponding to the generated code -// in this file. The external references of Swagger specification are resolved. -// The logic of resolving external references is tightly connected to "import-mapping" feature. -// Externally referenced files must be embedded in the corresponding golang packages. -// Urls can be supported but this task was out of the scope. -func GetSwagger() (swagger *openapi3.T, err error) { - resolvePath := PathToRawSpec("") - - loader := openapi3.NewLoader() - loader.IsExternalRefsAllowed = true - loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() - pathToFile = path.Clean(pathToFile) - getSpec, ok := resolvePath[pathToFile] - if !ok { - err1 := fmt.Errorf("path not found: %s", pathToFile) - return nil, err1 - } - return getSpec() - } - var specData []byte - specData, err = rawSpec() - if err != nil { - return - } - swagger, err = loader.LoadFromData(specData) - if err != nil { - return - } - return -} diff --git a/internal/test/issues/issue-1397/spec.yaml b/internal/test/issues/issue-1397/spec.yaml deleted file mode 100644 index 93cc609edf..0000000000 --- a/internal/test/issues/issue-1397/spec.yaml +++ /dev/null @@ -1,52 +0,0 @@ -openapi: "3.0.1" -components: - schemas: - Test: - type: object - properties: - field1: - description: A array of enum values - items: - enum: - - option1 - - option2 - type: string - maxItems: 5 - minItems: 0 - type: array - field2: - description: A nested object with allocated name - properties: - field1: - type: boolean - field2: - type: string - required: - - field1 - - field2 - type: object - x-go-type-name: MyTestRequestNestedField - field3: - description: A nested object without allocated name - properties: - field1: - type: boolean - field2: - type: string - required: - - field1 - - field2 - type: object - x-go-type-name: MyTestRequest -paths: - /test: - get: - operationId: test - requestBody: - content: - application/test+json: - schema: - $ref: "#/components/schemas/Test" - responses: - 204: - description: good diff --git a/internal/test/issues/issue-1529/strict-echo/doc.go b/internal/test/issues/issue-1529/strict-echo/doc.go deleted file mode 100644 index 4bf78249fa..0000000000 --- a/internal/test/issues/issue-1529/strict-echo/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -package issue1529 - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml spec.yaml diff --git a/internal/test/issues/issue-1529/strict-echo/issue1529.gen.go b/internal/test/issues/issue-1529/strict-echo/issue1529.gen.go deleted file mode 100644 index cd5260fae4..0000000000 --- a/internal/test/issues/issue-1529/strict-echo/issue1529.gen.go +++ /dev/null @@ -1,471 +0,0 @@ -// Package issue1529 provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package issue1529 - -import ( - "bytes" - "compress/gzip" - "context" - "encoding/base64" - "encoding/json" - "fmt" - "io" - "net/http" - "net/url" - "path" - "strings" - - "github.com/getkin/kin-openapi/openapi3" - "github.com/labstack/echo/v4" - strictecho "github.com/oapi-codegen/runtime/strictmiddleware/echo" -) - -// Test defines model for Test. -type Test = map[string]interface{} - -// RequestEditorFn is the function signature for the RequestEditor callback function -type RequestEditorFn func(ctx context.Context, req *http.Request) error - -// Doer performs HTTP requests. -// -// The standard http.Client implements this interface. -type HttpRequestDoer interface { - Do(req *http.Request) (*http.Response, error) -} - -// Client which conforms to the OpenAPI3 specification for this service. -type Client struct { - // The endpoint of the server conforming to this interface, with scheme, - // https://api.deepmap.com for example. This can contain a path relative - // to the server, such as https://api.deepmap.com/dev-test, and all the - // paths in the swagger spec will be appended to the server. - Server string - - // Doer for performing requests, typically a *http.Client with any - // customized settings, such as certificate chains. - Client HttpRequestDoer - - // A list of callbacks for modifying requests which are generated before sending over - // the network. - RequestEditors []RequestEditorFn -} - -// ClientOption allows setting custom parameters during construction -type ClientOption func(*Client) error - -// Creates a new Client, with reasonable defaults -func NewClient(server string, opts ...ClientOption) (*Client, error) { - // create a client with sane default values - client := Client{ - Server: server, - } - // mutate client and add all optional params - for _, o := range opts { - if err := o(&client); err != nil { - return nil, err - } - } - // ensure the server URL always has a trailing slash - if !strings.HasSuffix(client.Server, "/") { - client.Server += "/" - } - // create httpClient, if not already present - if client.Client == nil { - client.Client = &http.Client{} - } - return &client, nil -} - -// WithHTTPClient allows overriding the default Doer, which is -// automatically created using http.Client. This is useful for tests. -func WithHTTPClient(doer HttpRequestDoer) ClientOption { - return func(c *Client) error { - c.Client = doer - return nil - } -} - -// WithRequestEditorFn allows setting up a callback function, which will be -// called right before sending the request. This can be used to mutate the request. -func WithRequestEditorFn(fn RequestEditorFn) ClientOption { - return func(c *Client) error { - c.RequestEditors = append(c.RequestEditors, fn) - return nil - } -} - -// The interface specification for the client above. -type ClientInterface interface { - // Test request - Test(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) -} - -func (c *Client) Test(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewTestRequest(c.Server) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -// NewTestRequest generates requests for Test -func NewTestRequest(server string) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/test") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -func (c *Client) applyEditors(ctx context.Context, req *http.Request, additionalEditors []RequestEditorFn) error { - for _, r := range c.RequestEditors { - if err := r(ctx, req); err != nil { - return err - } - } - for _, r := range additionalEditors { - if err := r(ctx, req); err != nil { - return err - } - } - return nil -} - -// ClientWithResponses builds on ClientInterface to offer response payloads -type ClientWithResponses struct { - ClientInterface -} - -// NewClientWithResponses creates a new ClientWithResponses, which wraps -// Client with return type handling -func NewClientWithResponses(server string, opts ...ClientOption) (*ClientWithResponses, error) { - client, err := NewClient(server, opts...) - if err != nil { - return nil, err - } - return &ClientWithResponses{client}, nil -} - -// WithBaseURL overrides the baseURL. -func WithBaseURL(baseURL string) ClientOption { - return func(c *Client) error { - newBaseURL, err := url.Parse(baseURL) - if err != nil { - return err - } - c.Server = newBaseURL.String() - return nil - } -} - -// ClientWithResponsesInterface is the interface specification for the client with responses above. -type ClientWithResponsesInterface interface { - // TestWithResponse request - TestWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*TestResponse, error) -} - -type TestResponse struct { - Body []byte - HTTPResponse *http.Response - JSON200 *Test - ApplicationjsonProfileBar200 *Test - ApplicationjsonProfileFoo200 *Test -} - -// Status returns HTTPResponse.Status -func (r TestResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r TestResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -// TestWithResponse request returning *TestResponse -func (c *ClientWithResponses) TestWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*TestResponse, error) { - rsp, err := c.Test(ctx, reqEditors...) - if err != nil { - return nil, err - } - return ParseTestResponse(rsp) -} - -// ParseTestResponse parses an HTTP response from a TestWithResponse call -func ParseTestResponse(rsp *http.Response) (*TestResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &TestResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - switch { - case rsp.Header.Get("Content-Type") == "application/json" && rsp.StatusCode == 200: - var dest Test - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON200 = &dest - - case rsp.Header.Get("Content-Type") == "application/json; profile=\"Bar\"" && rsp.StatusCode == 200: - var dest Test - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.ApplicationjsonProfileBar200 = &dest - - case rsp.Header.Get("Content-Type") == "application/json; profile=\"Foo\"" && rsp.StatusCode == 200: - var dest Test - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.ApplicationjsonProfileFoo200 = &dest - - } - - return response, nil -} - -// ServerInterface represents all server handlers. -type ServerInterface interface { - - // (GET /test) - Test(ctx echo.Context) error -} - -// ServerInterfaceWrapper converts echo contexts to parameters. -type ServerInterfaceWrapper struct { - Handler ServerInterface -} - -// Test converts echo context to params. -func (w *ServerInterfaceWrapper) Test(ctx echo.Context) error { - var err error - - // Invoke the callback with all the unmarshaled arguments - err = w.Handler.Test(ctx) - return err -} - -// This is a simple interface which specifies echo.Route addition functions which -// are present on both echo.Echo and echo.Group, since we want to allow using -// either of them for path registration -type EchoRouter interface { - CONNECT(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - DELETE(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - GET(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - HEAD(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - OPTIONS(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - PATCH(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - POST(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - PUT(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - TRACE(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route -} - -// RegisterHandlers adds each server route to the EchoRouter. -func RegisterHandlers(router EchoRouter, si ServerInterface) { - RegisterHandlersWithBaseURL(router, si, "") -} - -// Registers handlers, and prepends BaseURL to the paths, so that the paths -// can be served under a prefix. -func RegisterHandlersWithBaseURL(router EchoRouter, si ServerInterface, baseURL string) { - - wrapper := ServerInterfaceWrapper{ - Handler: si, - } - - router.GET(baseURL+"/test", wrapper.Test) - -} - -type TestRequestObject struct { -} - -type TestResponseObject interface { - VisitTestResponse(w http.ResponseWriter) error -} - -type Test200JSONResponse Test - -func (response Test200JSONResponse) VisitTestResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(200) - - return json.NewEncoder(w).Encode(response) -} - -type Test200ApplicationJSONProfileBarResponse Test - -func (response Test200ApplicationJSONProfileBarResponse) VisitTestResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/json; profile=\"Bar\"") - w.WriteHeader(200) - - return json.NewEncoder(w).Encode(response) -} - -type Test200ApplicationJSONProfileFooResponse Test - -func (response Test200ApplicationJSONProfileFooResponse) VisitTestResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/json; profile=\"Foo\"") - w.WriteHeader(200) - - return json.NewEncoder(w).Encode(response) -} - -// StrictServerInterface represents all server handlers. -type StrictServerInterface interface { - - // (GET /test) - Test(ctx context.Context, request TestRequestObject) (TestResponseObject, error) -} - -type StrictHandlerFunc = strictecho.StrictEchoHandlerFunc -type StrictMiddlewareFunc = strictecho.StrictEchoMiddlewareFunc - -func NewStrictHandler(ssi StrictServerInterface, middlewares []StrictMiddlewareFunc) ServerInterface { - return &strictHandler{ssi: ssi, middlewares: middlewares} -} - -type strictHandler struct { - ssi StrictServerInterface - middlewares []StrictMiddlewareFunc -} - -// Test operation middleware -func (sh *strictHandler) Test(ctx echo.Context) error { - var request TestRequestObject - - handler := func(ctx echo.Context, request interface{}) (interface{}, error) { - return sh.ssi.Test(ctx.Request().Context(), request.(TestRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "Test") - } - - response, err := handler(ctx, request) - - if err != nil { - return err - } else if validResponse, ok := response.(TestResponseObject); ok { - return validResponse.VisitTestResponse(ctx.Response()) - } else if response != nil { - return fmt.Errorf("unexpected response type: %T", response) - } - return nil -} - -// Base64 encoded, gzipped, json marshaled Swagger object -var swaggerSpec = []string{ - - "H4sIAAAAAAAC/6zPMUsEMRAF4L8iT8twWbWL2FgI9pbXxDjr5cjNDMlYyLL/XRIXFizFad4072NmQZKL", - "ChNbQ1jQ0okucayv1KynfSkhQN7OlAzrujpkngWBP0txECWOmhFwf5gOt3DQaKcheNuIDxohSjVaFn55", - "R/jxHSo1FW40GnfT1CMJG/HoRNWS02j5cxPej+zbTaUZAdd+/8JvL/jh92t/Ew9XWmXOhR6PeIr1iH82", - "n0X+YG7zHQAA//9fnz6pkQEAAA==", -} - -// GetSwagger returns the content of the embedded swagger specification file -// or error if failed to decode -func decodeSpec() ([]byte, error) { - zipped, err := base64.StdEncoding.DecodeString(strings.Join(swaggerSpec, "")) - if err != nil { - return nil, fmt.Errorf("error base64 decoding spec: %w", err) - } - zr, err := gzip.NewReader(bytes.NewReader(zipped)) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - var buf bytes.Buffer - _, err = buf.ReadFrom(zr) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - - return buf.Bytes(), nil -} - -var rawSpec = decodeSpecCached() - -// a naive cached of a decoded swagger spec -func decodeSpecCached() func() ([]byte, error) { - data, err := decodeSpec() - return func() ([]byte, error) { - return data, err - } -} - -// Constructs a synthetic filesystem for resolving external references when loading openapi specifications. -func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { - res := make(map[string]func() ([]byte, error)) - if len(pathToFile) > 0 { - res[pathToFile] = rawSpec - } - - return res -} - -// GetSwagger returns the Swagger specification corresponding to the generated code -// in this file. The external references of Swagger specification are resolved. -// The logic of resolving external references is tightly connected to "import-mapping" feature. -// Externally referenced files must be embedded in the corresponding golang packages. -// Urls can be supported but this task was out of the scope. -func GetSwagger() (swagger *openapi3.T, err error) { - resolvePath := PathToRawSpec("") - - loader := openapi3.NewLoader() - loader.IsExternalRefsAllowed = true - loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() - pathToFile = path.Clean(pathToFile) - getSpec, ok := resolvePath[pathToFile] - if !ok { - err1 := fmt.Errorf("path not found: %s", pathToFile) - return nil, err1 - } - return getSpec() - } - var specData []byte - specData, err = rawSpec() - if err != nil { - return - } - swagger, err = loader.LoadFromData(specData) - if err != nil { - return - } - return -} diff --git a/internal/test/issues/issue-1529/strict-echo/spec.yaml b/internal/test/issues/issue-1529/strict-echo/spec.yaml deleted file mode 100644 index ca7aae80a3..0000000000 --- a/internal/test/issues/issue-1529/strict-echo/spec.yaml +++ /dev/null @@ -1,21 +0,0 @@ -openapi: "3.0.1" -components: - schemas: - Test: - type: object -paths: - /test: - get: - operationId: test - responses: - 200: - content: - application/json: - schema: - $ref: "#/components/schemas/Test" - application/json; profile="Foo": - schema: - $ref: "#/components/schemas/Test" - application/json; profile="Bar": - schema: - $ref: "#/components/schemas/Test" diff --git a/internal/test/issues/issue-1529/strict-fiber/config.yaml b/internal/test/issues/issue-1529/strict-fiber/config.yaml deleted file mode 100644 index e03a3f678b..0000000000 --- a/internal/test/issues/issue-1529/strict-fiber/config.yaml +++ /dev/null @@ -1,9 +0,0 @@ -# yaml-language-server: $schema=../../../../../configuration-schema.json -package: issue1529 -generate: - client: true - models: true - embedded-spec: true - fiber-server: true - strict-server: true -output: issue1529.gen.go diff --git a/internal/test/issues/issue-1529/strict-fiber/doc.go b/internal/test/issues/issue-1529/strict-fiber/doc.go deleted file mode 100644 index 4bf78249fa..0000000000 --- a/internal/test/issues/issue-1529/strict-fiber/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -package issue1529 - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml spec.yaml diff --git a/internal/test/issues/issue-1529/strict-fiber/issue1529.gen.go b/internal/test/issues/issue-1529/strict-fiber/issue1529.gen.go deleted file mode 100644 index e1324845b6..0000000000 --- a/internal/test/issues/issue-1529/strict-fiber/issue1529.gen.go +++ /dev/null @@ -1,465 +0,0 @@ -// Package issue1529 provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package issue1529 - -import ( - "bytes" - "compress/gzip" - "context" - "encoding/base64" - "encoding/json" - "fmt" - "io" - "net/http" - "net/url" - "path" - "strings" - - "github.com/getkin/kin-openapi/openapi3" - "github.com/gofiber/fiber/v2" -) - -// Test defines model for Test. -type Test = map[string]interface{} - -// RequestEditorFn is the function signature for the RequestEditor callback function -type RequestEditorFn func(ctx context.Context, req *http.Request) error - -// Doer performs HTTP requests. -// -// The standard http.Client implements this interface. -type HttpRequestDoer interface { - Do(req *http.Request) (*http.Response, error) -} - -// Client which conforms to the OpenAPI3 specification for this service. -type Client struct { - // The endpoint of the server conforming to this interface, with scheme, - // https://api.deepmap.com for example. This can contain a path relative - // to the server, such as https://api.deepmap.com/dev-test, and all the - // paths in the swagger spec will be appended to the server. - Server string - - // Doer for performing requests, typically a *http.Client with any - // customized settings, such as certificate chains. - Client HttpRequestDoer - - // A list of callbacks for modifying requests which are generated before sending over - // the network. - RequestEditors []RequestEditorFn -} - -// ClientOption allows setting custom parameters during construction -type ClientOption func(*Client) error - -// Creates a new Client, with reasonable defaults -func NewClient(server string, opts ...ClientOption) (*Client, error) { - // create a client with sane default values - client := Client{ - Server: server, - } - // mutate client and add all optional params - for _, o := range opts { - if err := o(&client); err != nil { - return nil, err - } - } - // ensure the server URL always has a trailing slash - if !strings.HasSuffix(client.Server, "/") { - client.Server += "/" - } - // create httpClient, if not already present - if client.Client == nil { - client.Client = &http.Client{} - } - return &client, nil -} - -// WithHTTPClient allows overriding the default Doer, which is -// automatically created using http.Client. This is useful for tests. -func WithHTTPClient(doer HttpRequestDoer) ClientOption { - return func(c *Client) error { - c.Client = doer - return nil - } -} - -// WithRequestEditorFn allows setting up a callback function, which will be -// called right before sending the request. This can be used to mutate the request. -func WithRequestEditorFn(fn RequestEditorFn) ClientOption { - return func(c *Client) error { - c.RequestEditors = append(c.RequestEditors, fn) - return nil - } -} - -// The interface specification for the client above. -type ClientInterface interface { - // Test request - Test(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) -} - -func (c *Client) Test(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewTestRequest(c.Server) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -// NewTestRequest generates requests for Test -func NewTestRequest(server string) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/test") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -func (c *Client) applyEditors(ctx context.Context, req *http.Request, additionalEditors []RequestEditorFn) error { - for _, r := range c.RequestEditors { - if err := r(ctx, req); err != nil { - return err - } - } - for _, r := range additionalEditors { - if err := r(ctx, req); err != nil { - return err - } - } - return nil -} - -// ClientWithResponses builds on ClientInterface to offer response payloads -type ClientWithResponses struct { - ClientInterface -} - -// NewClientWithResponses creates a new ClientWithResponses, which wraps -// Client with return type handling -func NewClientWithResponses(server string, opts ...ClientOption) (*ClientWithResponses, error) { - client, err := NewClient(server, opts...) - if err != nil { - return nil, err - } - return &ClientWithResponses{client}, nil -} - -// WithBaseURL overrides the baseURL. -func WithBaseURL(baseURL string) ClientOption { - return func(c *Client) error { - newBaseURL, err := url.Parse(baseURL) - if err != nil { - return err - } - c.Server = newBaseURL.String() - return nil - } -} - -// ClientWithResponsesInterface is the interface specification for the client with responses above. -type ClientWithResponsesInterface interface { - // TestWithResponse request - TestWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*TestResponse, error) -} - -type TestResponse struct { - Body []byte - HTTPResponse *http.Response - JSON200 *Test - ApplicationjsonProfileBar200 *Test - ApplicationjsonProfileFoo200 *Test -} - -// Status returns HTTPResponse.Status -func (r TestResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r TestResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -// TestWithResponse request returning *TestResponse -func (c *ClientWithResponses) TestWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*TestResponse, error) { - rsp, err := c.Test(ctx, reqEditors...) - if err != nil { - return nil, err - } - return ParseTestResponse(rsp) -} - -// ParseTestResponse parses an HTTP response from a TestWithResponse call -func ParseTestResponse(rsp *http.Response) (*TestResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &TestResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - switch { - case rsp.Header.Get("Content-Type") == "application/json" && rsp.StatusCode == 200: - var dest Test - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON200 = &dest - - case rsp.Header.Get("Content-Type") == "application/json; profile=\"Bar\"" && rsp.StatusCode == 200: - var dest Test - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.ApplicationjsonProfileBar200 = &dest - - case rsp.Header.Get("Content-Type") == "application/json; profile=\"Foo\"" && rsp.StatusCode == 200: - var dest Test - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.ApplicationjsonProfileFoo200 = &dest - - } - - return response, nil -} - -// ServerInterface represents all server handlers. -type ServerInterface interface { - - // (GET /test) - Test(c *fiber.Ctx) error -} - -// ServerInterfaceWrapper converts contexts to parameters. -type ServerInterfaceWrapper struct { - Handler ServerInterface -} - -type MiddlewareFunc fiber.Handler - -// Test operation middleware -func (siw *ServerInterfaceWrapper) Test(c *fiber.Ctx) error { - - return siw.Handler.Test(c) -} - -// FiberServerOptions provides options for the Fiber server. -type FiberServerOptions struct { - BaseURL string - Middlewares []MiddlewareFunc -} - -// RegisterHandlers creates http.Handler with routing matching OpenAPI spec. -func RegisterHandlers(router fiber.Router, si ServerInterface) { - RegisterHandlersWithOptions(router, si, FiberServerOptions{}) -} - -// RegisterHandlersWithOptions creates http.Handler with additional options -func RegisterHandlersWithOptions(router fiber.Router, si ServerInterface, options FiberServerOptions) { - wrapper := ServerInterfaceWrapper{ - Handler: si, - } - - for _, m := range options.Middlewares { - router.Use(fiber.Handler(m)) - } - - router.Get(options.BaseURL+"/test", wrapper.Test) - -} - -type TestRequestObject struct { -} - -type TestResponseObject interface { - VisitTestResponse(ctx *fiber.Ctx) error -} - -type Test200JSONResponse Test - -func (response Test200JSONResponse) VisitTestResponse(ctx *fiber.Ctx) error { - ctx.Response().Header.Set("Content-Type", "application/json") - ctx.Status(200) - - return ctx.JSON(&response) -} - -type Test200ApplicationJSONProfileBarResponse Test - -func (response Test200ApplicationJSONProfileBarResponse) VisitTestResponse(ctx *fiber.Ctx) error { - ctx.Response().Header.Set("Content-Type", "application/json; profile=\"Bar\"") - ctx.Status(200) - - return ctx.JSON(&response) -} - -type Test200ApplicationJSONProfileFooResponse Test - -func (response Test200ApplicationJSONProfileFooResponse) VisitTestResponse(ctx *fiber.Ctx) error { - ctx.Response().Header.Set("Content-Type", "application/json; profile=\"Foo\"") - ctx.Status(200) - - return ctx.JSON(&response) -} - -// StrictServerInterface represents all server handlers. -type StrictServerInterface interface { - - // (GET /test) - Test(ctx context.Context, request TestRequestObject) (TestResponseObject, error) -} - -type StrictHandlerFunc func(ctx *fiber.Ctx, args interface{}) (interface{}, error) - -type StrictMiddlewareFunc func(f StrictHandlerFunc, operationID string) StrictHandlerFunc - -func NewStrictHandler(ssi StrictServerInterface, middlewares []StrictMiddlewareFunc) ServerInterface { - return &strictHandler{ssi: ssi, middlewares: middlewares} -} - -type strictHandler struct { - ssi StrictServerInterface - middlewares []StrictMiddlewareFunc -} - -// Test operation middleware -func (sh *strictHandler) Test(ctx *fiber.Ctx) error { - var request TestRequestObject - - handler := func(ctx *fiber.Ctx, request interface{}) (interface{}, error) { - return sh.ssi.Test(ctx.UserContext(), request.(TestRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "Test") - } - - response, err := handler(ctx, request) - - if err != nil { - return fiber.NewError(fiber.StatusBadRequest, err.Error()) - } else if validResponse, ok := response.(TestResponseObject); ok { - if err := validResponse.VisitTestResponse(ctx); err != nil { - return fiber.NewError(fiber.StatusBadRequest, err.Error()) - } - } else if response != nil { - return fmt.Errorf("unexpected response type: %T", response) - } - return nil -} - -// Base64 encoded, gzipped, json marshaled Swagger object -var swaggerSpec = []string{ - - "H4sIAAAAAAAC/6zPMUsEMRAF4L8iT8twWbWL2FgI9pbXxDjr5cjNDMlYyLL/XRIXFizFad4072NmQZKL", - "ChNbQ1jQ0okucayv1KynfSkhQN7OlAzrujpkngWBP0txECWOmhFwf5gOt3DQaKcheNuIDxohSjVaFn55", - "R/jxHSo1FW40GnfT1CMJG/HoRNWS02j5cxPej+zbTaUZAdd+/8JvL/jh92t/Ew9XWmXOhR6PeIr1iH82", - "n0X+YG7zHQAA//9fnz6pkQEAAA==", -} - -// GetSwagger returns the content of the embedded swagger specification file -// or error if failed to decode -func decodeSpec() ([]byte, error) { - zipped, err := base64.StdEncoding.DecodeString(strings.Join(swaggerSpec, "")) - if err != nil { - return nil, fmt.Errorf("error base64 decoding spec: %w", err) - } - zr, err := gzip.NewReader(bytes.NewReader(zipped)) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - var buf bytes.Buffer - _, err = buf.ReadFrom(zr) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - - return buf.Bytes(), nil -} - -var rawSpec = decodeSpecCached() - -// a naive cached of a decoded swagger spec -func decodeSpecCached() func() ([]byte, error) { - data, err := decodeSpec() - return func() ([]byte, error) { - return data, err - } -} - -// Constructs a synthetic filesystem for resolving external references when loading openapi specifications. -func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { - res := make(map[string]func() ([]byte, error)) - if len(pathToFile) > 0 { - res[pathToFile] = rawSpec - } - - return res -} - -// GetSwagger returns the Swagger specification corresponding to the generated code -// in this file. The external references of Swagger specification are resolved. -// The logic of resolving external references is tightly connected to "import-mapping" feature. -// Externally referenced files must be embedded in the corresponding golang packages. -// Urls can be supported but this task was out of the scope. -func GetSwagger() (swagger *openapi3.T, err error) { - resolvePath := PathToRawSpec("") - - loader := openapi3.NewLoader() - loader.IsExternalRefsAllowed = true - loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() - pathToFile = path.Clean(pathToFile) - getSpec, ok := resolvePath[pathToFile] - if !ok { - err1 := fmt.Errorf("path not found: %s", pathToFile) - return nil, err1 - } - return getSpec() - } - var specData []byte - specData, err = rawSpec() - if err != nil { - return - } - swagger, err = loader.LoadFromData(specData) - if err != nil { - return - } - return -} diff --git a/internal/test/issues/issue-1529/strict-fiber/spec.yaml b/internal/test/issues/issue-1529/strict-fiber/spec.yaml deleted file mode 100644 index ca7aae80a3..0000000000 --- a/internal/test/issues/issue-1529/strict-fiber/spec.yaml +++ /dev/null @@ -1,21 +0,0 @@ -openapi: "3.0.1" -components: - schemas: - Test: - type: object -paths: - /test: - get: - operationId: test - responses: - 200: - content: - application/json: - schema: - $ref: "#/components/schemas/Test" - application/json; profile="Foo": - schema: - $ref: "#/components/schemas/Test" - application/json; profile="Bar": - schema: - $ref: "#/components/schemas/Test" diff --git a/internal/test/issues/issue-1529/strict-iris/config.yaml b/internal/test/issues/issue-1529/strict-iris/config.yaml deleted file mode 100644 index 835b035300..0000000000 --- a/internal/test/issues/issue-1529/strict-iris/config.yaml +++ /dev/null @@ -1,9 +0,0 @@ -# yaml-language-server: $schema=../../../../../configuration-schema.json -package: issue1529 -generate: - client: true - models: true - embedded-spec: true - iris-server: true - strict-server: true -output: issue1529.gen.go diff --git a/internal/test/issues/issue-1529/strict-iris/doc.go b/internal/test/issues/issue-1529/strict-iris/doc.go deleted file mode 100644 index 4bf78249fa..0000000000 --- a/internal/test/issues/issue-1529/strict-iris/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -package issue1529 - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml spec.yaml diff --git a/internal/test/issues/issue-1529/strict-iris/issue1529.gen.go b/internal/test/issues/issue-1529/strict-iris/issue1529.gen.go deleted file mode 100644 index a214576e80..0000000000 --- a/internal/test/issues/issue-1529/strict-iris/issue1529.gen.go +++ /dev/null @@ -1,466 +0,0 @@ -// Package issue1529 provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package issue1529 - -import ( - "bytes" - "compress/gzip" - "context" - "encoding/base64" - "encoding/json" - "fmt" - "io" - "net/http" - "net/url" - "path" - "strings" - - "github.com/getkin/kin-openapi/openapi3" - "github.com/kataras/iris/v12" - strictiris "github.com/oapi-codegen/runtime/strictmiddleware/iris" -) - -// Test defines model for Test. -type Test = map[string]interface{} - -// RequestEditorFn is the function signature for the RequestEditor callback function -type RequestEditorFn func(ctx context.Context, req *http.Request) error - -// Doer performs HTTP requests. -// -// The standard http.Client implements this interface. -type HttpRequestDoer interface { - Do(req *http.Request) (*http.Response, error) -} - -// Client which conforms to the OpenAPI3 specification for this service. -type Client struct { - // The endpoint of the server conforming to this interface, with scheme, - // https://api.deepmap.com for example. This can contain a path relative - // to the server, such as https://api.deepmap.com/dev-test, and all the - // paths in the swagger spec will be appended to the server. - Server string - - // Doer for performing requests, typically a *http.Client with any - // customized settings, such as certificate chains. - Client HttpRequestDoer - - // A list of callbacks for modifying requests which are generated before sending over - // the network. - RequestEditors []RequestEditorFn -} - -// ClientOption allows setting custom parameters during construction -type ClientOption func(*Client) error - -// Creates a new Client, with reasonable defaults -func NewClient(server string, opts ...ClientOption) (*Client, error) { - // create a client with sane default values - client := Client{ - Server: server, - } - // mutate client and add all optional params - for _, o := range opts { - if err := o(&client); err != nil { - return nil, err - } - } - // ensure the server URL always has a trailing slash - if !strings.HasSuffix(client.Server, "/") { - client.Server += "/" - } - // create httpClient, if not already present - if client.Client == nil { - client.Client = &http.Client{} - } - return &client, nil -} - -// WithHTTPClient allows overriding the default Doer, which is -// automatically created using http.Client. This is useful for tests. -func WithHTTPClient(doer HttpRequestDoer) ClientOption { - return func(c *Client) error { - c.Client = doer - return nil - } -} - -// WithRequestEditorFn allows setting up a callback function, which will be -// called right before sending the request. This can be used to mutate the request. -func WithRequestEditorFn(fn RequestEditorFn) ClientOption { - return func(c *Client) error { - c.RequestEditors = append(c.RequestEditors, fn) - return nil - } -} - -// The interface specification for the client above. -type ClientInterface interface { - // Test request - Test(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) -} - -func (c *Client) Test(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewTestRequest(c.Server) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -// NewTestRequest generates requests for Test -func NewTestRequest(server string) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/test") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -func (c *Client) applyEditors(ctx context.Context, req *http.Request, additionalEditors []RequestEditorFn) error { - for _, r := range c.RequestEditors { - if err := r(ctx, req); err != nil { - return err - } - } - for _, r := range additionalEditors { - if err := r(ctx, req); err != nil { - return err - } - } - return nil -} - -// ClientWithResponses builds on ClientInterface to offer response payloads -type ClientWithResponses struct { - ClientInterface -} - -// NewClientWithResponses creates a new ClientWithResponses, which wraps -// Client with return type handling -func NewClientWithResponses(server string, opts ...ClientOption) (*ClientWithResponses, error) { - client, err := NewClient(server, opts...) - if err != nil { - return nil, err - } - return &ClientWithResponses{client}, nil -} - -// WithBaseURL overrides the baseURL. -func WithBaseURL(baseURL string) ClientOption { - return func(c *Client) error { - newBaseURL, err := url.Parse(baseURL) - if err != nil { - return err - } - c.Server = newBaseURL.String() - return nil - } -} - -// ClientWithResponsesInterface is the interface specification for the client with responses above. -type ClientWithResponsesInterface interface { - // TestWithResponse request - TestWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*TestResponse, error) -} - -type TestResponse struct { - Body []byte - HTTPResponse *http.Response - JSON200 *Test - ApplicationjsonProfileBar200 *Test - ApplicationjsonProfileFoo200 *Test -} - -// Status returns HTTPResponse.Status -func (r TestResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r TestResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -// TestWithResponse request returning *TestResponse -func (c *ClientWithResponses) TestWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*TestResponse, error) { - rsp, err := c.Test(ctx, reqEditors...) - if err != nil { - return nil, err - } - return ParseTestResponse(rsp) -} - -// ParseTestResponse parses an HTTP response from a TestWithResponse call -func ParseTestResponse(rsp *http.Response) (*TestResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &TestResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - switch { - case rsp.Header.Get("Content-Type") == "application/json" && rsp.StatusCode == 200: - var dest Test - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON200 = &dest - - case rsp.Header.Get("Content-Type") == "application/json; profile=\"Bar\"" && rsp.StatusCode == 200: - var dest Test - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.ApplicationjsonProfileBar200 = &dest - - case rsp.Header.Get("Content-Type") == "application/json; profile=\"Foo\"" && rsp.StatusCode == 200: - var dest Test - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.ApplicationjsonProfileFoo200 = &dest - - } - - return response, nil -} - -// ServerInterface represents all server handlers. -type ServerInterface interface { - - // (GET /test) - Test(ctx iris.Context) -} - -// ServerInterfaceWrapper converts echo contexts to parameters. -type ServerInterfaceWrapper struct { - Handler ServerInterface -} - -type MiddlewareFunc iris.Handler - -// Test converts iris context to params. -func (w *ServerInterfaceWrapper) Test(ctx iris.Context) { - - // Invoke the callback with all the unmarshaled arguments - w.Handler.Test(ctx) -} - -// IrisServerOption is the option for iris server -type IrisServerOptions struct { - BaseURL string - Middlewares []MiddlewareFunc -} - -// RegisterHandlers creates http.Handler with routing matching OpenAPI spec. -func RegisterHandlers(router *iris.Application, si ServerInterface) { - RegisterHandlersWithOptions(router, si, IrisServerOptions{}) -} - -// RegisterHandlersWithOptions creates http.Handler with additional options -func RegisterHandlersWithOptions(router *iris.Application, si ServerInterface, options IrisServerOptions) { - - wrapper := ServerInterfaceWrapper{ - Handler: si, - } - - router.Get(options.BaseURL+"/test", wrapper.Test) - - router.Build() -} - -type TestRequestObject struct { -} - -type TestResponseObject interface { - VisitTestResponse(ctx iris.Context) error -} - -type Test200JSONResponse Test - -func (response Test200JSONResponse) VisitTestResponse(ctx iris.Context) error { - ctx.ResponseWriter().Header().Set("Content-Type", "application/json") - ctx.StatusCode(200) - - return ctx.JSON(&response) -} - -type Test200ApplicationJSONProfileBarResponse Test - -func (response Test200ApplicationJSONProfileBarResponse) VisitTestResponse(ctx iris.Context) error { - ctx.ResponseWriter().Header().Set("Content-Type", "application/json; profile=\"Bar\"") - ctx.StatusCode(200) - - return ctx.JSON(&response) -} - -type Test200ApplicationJSONProfileFooResponse Test - -func (response Test200ApplicationJSONProfileFooResponse) VisitTestResponse(ctx iris.Context) error { - ctx.ResponseWriter().Header().Set("Content-Type", "application/json; profile=\"Foo\"") - ctx.StatusCode(200) - - return ctx.JSON(&response) -} - -// StrictServerInterface represents all server handlers. -type StrictServerInterface interface { - - // (GET /test) - Test(ctx context.Context, request TestRequestObject) (TestResponseObject, error) -} - -type StrictHandlerFunc = strictiris.StrictIrisHandlerFunc -type StrictMiddlewareFunc = strictiris.StrictIrisMiddlewareFunc - -func NewStrictHandler(ssi StrictServerInterface, middlewares []StrictMiddlewareFunc) ServerInterface { - return &strictHandler{ssi: ssi, middlewares: middlewares} -} - -type strictHandler struct { - ssi StrictServerInterface - middlewares []StrictMiddlewareFunc -} - -// Test operation middleware -func (sh *strictHandler) Test(ctx iris.Context) { - var request TestRequestObject - - handler := func(ctx iris.Context, request interface{}) (interface{}, error) { - return sh.ssi.Test(ctx, request.(TestRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "Test") - } - - response, err := handler(ctx, request) - - if err != nil { - ctx.StopWithError(http.StatusBadRequest, err) - return - } else if validResponse, ok := response.(TestResponseObject); ok { - if err := validResponse.VisitTestResponse(ctx); err != nil { - ctx.StopWithError(http.StatusBadRequest, err) - return - } - } else if response != nil { - ctx.Writef("Unexpected response type: %T", response) - return - } -} - -// Base64 encoded, gzipped, json marshaled Swagger object -var swaggerSpec = []string{ - - "H4sIAAAAAAAC/6zPMUsEMRAF4L8iT8twWbWL2FgI9pbXxDjr5cjNDMlYyLL/XRIXFizFad4072NmQZKL", - "ChNbQ1jQ0okucayv1KynfSkhQN7OlAzrujpkngWBP0txECWOmhFwf5gOt3DQaKcheNuIDxohSjVaFn55", - "R/jxHSo1FW40GnfT1CMJG/HoRNWS02j5cxPej+zbTaUZAdd+/8JvL/jh92t/Ew9XWmXOhR6PeIr1iH82", - "n0X+YG7zHQAA//9fnz6pkQEAAA==", -} - -// GetSwagger returns the content of the embedded swagger specification file -// or error if failed to decode -func decodeSpec() ([]byte, error) { - zipped, err := base64.StdEncoding.DecodeString(strings.Join(swaggerSpec, "")) - if err != nil { - return nil, fmt.Errorf("error base64 decoding spec: %w", err) - } - zr, err := gzip.NewReader(bytes.NewReader(zipped)) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - var buf bytes.Buffer - _, err = buf.ReadFrom(zr) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - - return buf.Bytes(), nil -} - -var rawSpec = decodeSpecCached() - -// a naive cached of a decoded swagger spec -func decodeSpecCached() func() ([]byte, error) { - data, err := decodeSpec() - return func() ([]byte, error) { - return data, err - } -} - -// Constructs a synthetic filesystem for resolving external references when loading openapi specifications. -func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { - res := make(map[string]func() ([]byte, error)) - if len(pathToFile) > 0 { - res[pathToFile] = rawSpec - } - - return res -} - -// GetSwagger returns the Swagger specification corresponding to the generated code -// in this file. The external references of Swagger specification are resolved. -// The logic of resolving external references is tightly connected to "import-mapping" feature. -// Externally referenced files must be embedded in the corresponding golang packages. -// Urls can be supported but this task was out of the scope. -func GetSwagger() (swagger *openapi3.T, err error) { - resolvePath := PathToRawSpec("") - - loader := openapi3.NewLoader() - loader.IsExternalRefsAllowed = true - loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() - pathToFile = path.Clean(pathToFile) - getSpec, ok := resolvePath[pathToFile] - if !ok { - err1 := fmt.Errorf("path not found: %s", pathToFile) - return nil, err1 - } - return getSpec() - } - var specData []byte - specData, err = rawSpec() - if err != nil { - return - } - swagger, err = loader.LoadFromData(specData) - if err != nil { - return - } - return -} diff --git a/internal/test/issues/issue-1529/strict-iris/spec.yaml b/internal/test/issues/issue-1529/strict-iris/spec.yaml deleted file mode 100644 index ca7aae80a3..0000000000 --- a/internal/test/issues/issue-1529/strict-iris/spec.yaml +++ /dev/null @@ -1,21 +0,0 @@ -openapi: "3.0.1" -components: - schemas: - Test: - type: object -paths: - /test: - get: - operationId: test - responses: - 200: - content: - application/json: - schema: - $ref: "#/components/schemas/Test" - application/json; profile="Foo": - schema: - $ref: "#/components/schemas/Test" - application/json; profile="Bar": - schema: - $ref: "#/components/schemas/Test" diff --git a/internal/test/issues/issue-1530/config.yaml b/internal/test/issues/issue-1530/config.yaml deleted file mode 100644 index 3cb9f3dd04..0000000000 --- a/internal/test/issues/issue-1530/config.yaml +++ /dev/null @@ -1,4 +0,0 @@ -package: issue1530 -generate: - models: true -output: issue1530.gen.go \ No newline at end of file diff --git a/internal/test/issues/issue-1530/doc.go b/internal/test/issues/issue-1530/doc.go deleted file mode 100644 index c6a0133735..0000000000 --- a/internal/test/issues/issue-1530/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -package issue1530 - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml issue1530.yaml diff --git a/internal/test/issues/issue-1530/issue1530.gen.go b/internal/test/issues/issue-1530/issue1530.gen.go deleted file mode 100644 index 8a60251b2c..0000000000 --- a/internal/test/issues/issue-1530/issue1530.gen.go +++ /dev/null @@ -1,126 +0,0 @@ -// Package issue1530 provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package issue1530 - -import ( - "encoding/json" - "errors" - - "github.com/oapi-codegen/runtime" -) - -// ConfigHttp defines model for ConfigHttp. -type ConfigHttp struct { - ConfigType string `json:"config_type"` - Host string `json:"host"` - Password *string `json:"password,omitempty"` - Port int `json:"port"` - User *string `json:"user,omitempty"` -} - -// ConfigSaveReq defines model for ConfigSaveReq. -type ConfigSaveReq struct { - union json.RawMessage -} - -// ConfigSsh defines model for ConfigSsh. -type ConfigSsh struct { - ConfigType string `json:"config_type"` - Host *string `json:"host,omitempty"` - Port *int `json:"port,omitempty"` - PrivateKey *string `json:"private_key,omitempty"` - User *string `json:"user,omitempty"` -} - -// PostConfigJSONRequestBody defines body for PostConfig for application/json ContentType. -type PostConfigJSONRequestBody = ConfigSaveReq - -// AsConfigHttp returns the union data inside the ConfigSaveReq as a ConfigHttp -func (t ConfigSaveReq) AsConfigHttp() (ConfigHttp, error) { - var body ConfigHttp - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromConfigHttp overwrites any union data inside the ConfigSaveReq as the provided ConfigHttp -func (t *ConfigSaveReq) FromConfigHttp(v ConfigHttp) error { - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeConfigHttp performs a merge with any union data inside the ConfigSaveReq, using the provided ConfigHttp -func (t *ConfigSaveReq) MergeConfigHttp(v ConfigHttp) error { - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -// AsConfigSsh returns the union data inside the ConfigSaveReq as a ConfigSsh -func (t ConfigSaveReq) AsConfigSsh() (ConfigSsh, error) { - var body ConfigSsh - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromConfigSsh overwrites any union data inside the ConfigSaveReq as the provided ConfigSsh -func (t *ConfigSaveReq) FromConfigSsh(v ConfigSsh) error { - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeConfigSsh performs a merge with any union data inside the ConfigSaveReq, using the provided ConfigSsh -func (t *ConfigSaveReq) MergeConfigSsh(v ConfigSsh) error { - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -func (t ConfigSaveReq) Discriminator() (string, error) { - var discriminator struct { - Discriminator string `json:"config_type"` - } - err := json.Unmarshal(t.union, &discriminator) - return discriminator.Discriminator, err -} - -func (t ConfigSaveReq) ValueByDiscriminator() (interface{}, error) { - discriminator, err := t.Discriminator() - if err != nil { - return nil, err - } - switch discriminator { - case "another_server": - return t.AsConfigHttp() - case "apache_server": - return t.AsConfigHttp() - case "ssh_server": - return t.AsConfigSsh() - case "web_server": - return t.AsConfigHttp() - default: - return nil, errors.New("unknown discriminator value: " + discriminator) - } -} - -func (t ConfigSaveReq) MarshalJSON() ([]byte, error) { - b, err := t.union.MarshalJSON() - return b, err -} - -func (t *ConfigSaveReq) UnmarshalJSON(b []byte) error { - err := t.union.UnmarshalJSON(b) - return err -} diff --git a/internal/test/issues/issue-1530/issue1530.yaml b/internal/test/issues/issue-1530/issue1530.yaml deleted file mode 100644 index 222d074b7b..0000000000 --- a/internal/test/issues/issue-1530/issue1530.yaml +++ /dev/null @@ -1,57 +0,0 @@ -paths: - /config: - post: - summary: Save configuration - requestBody: - content: - application/json: - schema: - $ref: "#/components/schemas/ConfigSaveReq" - responses: - "200": - description: Configuration saved successfully -components: - schemas: - ConfigHttp: - type: object - properties: - config_type: - type: string - host: - type: string - port: - type: integer - user: - type: string - password: - type: string - required: - - config_type - - host - - port - ConfigSaveReq: - oneOf: - - $ref: "#/components/schemas/ConfigHttp" - - $ref: "#/components/schemas/ConfigSsh" - discriminator: - propertyName: config_type - mapping: - ssh_server: "#/components/schemas/ConfigSsh" - apache_server: "#/components/schemas/ConfigHttp" - web_server: "#/components/schemas/ConfigHttp" - another_server: "#/components/schemas/ConfigHttp" - ConfigSsh: - type: object - properties: - config_type: - type: string - host: - type: string - port: - type: integer - user: - type: string - private_key: - type: string - required: - - config_type \ No newline at end of file diff --git a/internal/test/issues/issue-1530/issue1530_test.go b/internal/test/issues/issue-1530/issue1530_test.go deleted file mode 100644 index a23f7ed2d8..0000000000 --- a/internal/test/issues/issue-1530/issue1530_test.go +++ /dev/null @@ -1,51 +0,0 @@ -package issue1530_test - -import ( - "testing" - - issue1530 "github.com/oapi-codegen/oapi-codegen/v2/internal/test/issues/issue-1530" - "github.com/stretchr/testify/require" -) - -func TestIssue1530(t *testing.T) { - httpConfigTypes := []string{ - "another_server", - "apache_server", - "web_server", - } - - for _, configType := range httpConfigTypes { - t.Run("http-"+configType, func(t *testing.T) { - saveReq := issue1530.ConfigSaveReq{} - err := saveReq.FromConfigHttp(issue1530.ConfigHttp{ - ConfigType: configType, - Host: "example.com", - }) - require.NoError(t, err) - - cfg, err := saveReq.AsConfigHttp() - require.NoError(t, err) - require.Equal(t, configType, cfg.ConfigType) - - cfgByDiscriminator, err := saveReq.ValueByDiscriminator() - require.NoError(t, err) - require.Equal(t, cfg, cfgByDiscriminator) - }) - } - - t.Run("ssh", func(t *testing.T) { - saveReq := issue1530.ConfigSaveReq{} - err := saveReq.FromConfigSsh(issue1530.ConfigSsh{ - ConfigType: "ssh_server", - }) - require.NoError(t, err) - - cfg, err := saveReq.AsConfigSsh() - require.NoError(t, err) - require.Equal(t, "ssh_server", cfg.ConfigType) - - cfgByDiscriminator, err := saveReq.ValueByDiscriminator() - require.NoError(t, err) - require.Equal(t, cfg, cfgByDiscriminator) - }) -} diff --git a/internal/test/issues/issue-1676/api.yaml b/internal/test/issues/issue-1676/api.yaml deleted file mode 100644 index 717d75afd9..0000000000 --- a/internal/test/issues/issue-1676/api.yaml +++ /dev/null @@ -1,17 +0,0 @@ -openapi: "3.0.0" -info: - version: 1.0.0 - title: Issue 1676 -paths: - /ping: - get: - responses: - '200': - headers: - MyHeader: - schema: - type: string - content: - text/plain: - schema: - type: string diff --git a/internal/test/issues/issue-1676/generate.go b/internal/test/issues/issue-1676/generate.go deleted file mode 100644 index 49aa70b8a9..0000000000 --- a/internal/test/issues/issue-1676/generate.go +++ /dev/null @@ -1,3 +0,0 @@ -package issue1676 - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen -config cfg.yaml api.yaml diff --git a/internal/test/issues/issue-1676/ping.gen.go b/internal/test/issues/issue-1676/ping.gen.go deleted file mode 100644 index dcfddc3bc6..0000000000 --- a/internal/test/issues/issue-1676/ping.gen.go +++ /dev/null @@ -1,246 +0,0 @@ -// Package issue1676 provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package issue1676 - -import ( - "context" - "fmt" - "net/http" - - "github.com/gorilla/mux" - strictnethttp "github.com/oapi-codegen/runtime/strictmiddleware/nethttp" -) - -// ServerInterface represents all server handlers. -type ServerInterface interface { - - // (GET /ping) - GetPing(w http.ResponseWriter, r *http.Request) -} - -// ServerInterfaceWrapper converts contexts to parameters. -type ServerInterfaceWrapper struct { - Handler ServerInterface - HandlerMiddlewares []MiddlewareFunc - ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) -} - -type MiddlewareFunc func(http.Handler) http.Handler - -// GetPing operation middleware -func (siw *ServerInterfaceWrapper) GetPing(w http.ResponseWriter, r *http.Request) { - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.GetPing(w, r) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -type UnescapedCookieParamError struct { - ParamName string - Err error -} - -func (e *UnescapedCookieParamError) Error() string { - return fmt.Sprintf("error unescaping cookie parameter '%s'", e.ParamName) -} - -func (e *UnescapedCookieParamError) Unwrap() error { - return e.Err -} - -type UnmarshalingParamError struct { - ParamName string - Err error -} - -func (e *UnmarshalingParamError) Error() string { - return fmt.Sprintf("Error unmarshaling parameter %s as JSON: %s", e.ParamName, e.Err.Error()) -} - -func (e *UnmarshalingParamError) Unwrap() error { - return e.Err -} - -type RequiredParamError struct { - ParamName string -} - -func (e *RequiredParamError) Error() string { - return fmt.Sprintf("Query argument %s is required, but not found", e.ParamName) -} - -type RequiredHeaderError struct { - ParamName string - Err error -} - -func (e *RequiredHeaderError) Error() string { - return fmt.Sprintf("Header parameter %s is required, but not found", e.ParamName) -} - -func (e *RequiredHeaderError) Unwrap() error { - return e.Err -} - -type InvalidParamFormatError struct { - ParamName string - Err error -} - -func (e *InvalidParamFormatError) Error() string { - return fmt.Sprintf("Invalid format for parameter %s: %s", e.ParamName, e.Err.Error()) -} - -func (e *InvalidParamFormatError) Unwrap() error { - return e.Err -} - -type TooManyValuesForParamError struct { - ParamName string - Count int -} - -func (e *TooManyValuesForParamError) Error() string { - return fmt.Sprintf("Expected one value for %s, got %d", e.ParamName, e.Count) -} - -// Handler creates http.Handler with routing matching OpenAPI spec. -func Handler(si ServerInterface) http.Handler { - return HandlerWithOptions(si, GorillaServerOptions{}) -} - -type GorillaServerOptions struct { - BaseURL string - BaseRouter *mux.Router - Middlewares []MiddlewareFunc - ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) -} - -// HandlerFromMux creates http.Handler with routing matching OpenAPI spec based on the provided mux. -func HandlerFromMux(si ServerInterface, r *mux.Router) http.Handler { - return HandlerWithOptions(si, GorillaServerOptions{ - BaseRouter: r, - }) -} - -func HandlerFromMuxWithBaseURL(si ServerInterface, r *mux.Router, baseURL string) http.Handler { - return HandlerWithOptions(si, GorillaServerOptions{ - BaseURL: baseURL, - BaseRouter: r, - }) -} - -// HandlerWithOptions creates http.Handler with additional options -func HandlerWithOptions(si ServerInterface, options GorillaServerOptions) http.Handler { - r := options.BaseRouter - - if r == nil { - r = mux.NewRouter() - } - if options.ErrorHandlerFunc == nil { - options.ErrorHandlerFunc = func(w http.ResponseWriter, r *http.Request, err error) { - http.Error(w, err.Error(), http.StatusBadRequest) - } - } - wrapper := ServerInterfaceWrapper{ - Handler: si, - HandlerMiddlewares: options.Middlewares, - ErrorHandlerFunc: options.ErrorHandlerFunc, - } - - r.HandleFunc(options.BaseURL+"/ping", wrapper.GetPing).Methods("GET") - - return r -} - -type GetPingRequestObject struct { -} - -type GetPingResponseObject interface { - VisitGetPingResponse(w http.ResponseWriter) error -} - -type GetPing200ResponseHeaders struct { - MyHeader string -} - -type GetPing200TextResponse struct { - Body string - Headers GetPing200ResponseHeaders -} - -func (response GetPing200TextResponse) VisitGetPingResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "text/plain") - w.Header().Set("MyHeader", fmt.Sprint(response.Headers.MyHeader)) - w.WriteHeader(200) - - _, err := w.Write([]byte(response.Body)) - return err -} - -// StrictServerInterface represents all server handlers. -type StrictServerInterface interface { - - // (GET /ping) - GetPing(ctx context.Context, request GetPingRequestObject) (GetPingResponseObject, error) -} - -type StrictHandlerFunc = strictnethttp.StrictHTTPHandlerFunc -type StrictMiddlewareFunc = strictnethttp.StrictHTTPMiddlewareFunc - -type StrictHTTPServerOptions struct { - RequestErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) - ResponseErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) -} - -func NewStrictHandler(ssi StrictServerInterface, middlewares []StrictMiddlewareFunc) ServerInterface { - return &strictHandler{ssi: ssi, middlewares: middlewares, options: StrictHTTPServerOptions{ - RequestErrorHandlerFunc: func(w http.ResponseWriter, r *http.Request, err error) { - http.Error(w, err.Error(), http.StatusBadRequest) - }, - ResponseErrorHandlerFunc: func(w http.ResponseWriter, r *http.Request, err error) { - http.Error(w, err.Error(), http.StatusInternalServerError) - }, - }} -} - -func NewStrictHandlerWithOptions(ssi StrictServerInterface, middlewares []StrictMiddlewareFunc, options StrictHTTPServerOptions) ServerInterface { - return &strictHandler{ssi: ssi, middlewares: middlewares, options: options} -} - -type strictHandler struct { - ssi StrictServerInterface - middlewares []StrictMiddlewareFunc - options StrictHTTPServerOptions -} - -// GetPing operation middleware -func (sh *strictHandler) GetPing(w http.ResponseWriter, r *http.Request) { - var request GetPingRequestObject - - handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { - return sh.ssi.GetPing(ctx, request.(GetPingRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "GetPing") - } - - response, err := handler(r.Context(), w, r, request) - - if err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } else if validResponse, ok := response.(GetPingResponseObject); ok { - if err := validResponse.VisitGetPingResponse(w); err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } - } else if response != nil { - sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) - } -} diff --git a/internal/test/issues/issue-2031/config.yaml b/internal/test/issues/issue-2031/config.yaml deleted file mode 100644 index 495396d560..0000000000 --- a/internal/test/issues/issue-2031/config.yaml +++ /dev/null @@ -1,4 +0,0 @@ -package: issue2031 -generate: - models: true -output: issue2031.gen.go diff --git a/internal/test/issues/issue-2031/generate.go b/internal/test/issues/issue-2031/generate.go deleted file mode 100644 index 1e29681627..0000000000 --- a/internal/test/issues/issue-2031/generate.go +++ /dev/null @@ -1,3 +0,0 @@ -package issue2031 - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml openapi.yaml diff --git a/internal/test/issues/issue-2031/issue2031.gen.go b/internal/test/issues/issue-2031/issue2031.gen.go deleted file mode 100644 index 1ae12da963..0000000000 --- a/internal/test/issues/issue-2031/issue2031.gen.go +++ /dev/null @@ -1,83 +0,0 @@ -// Package issue2031 provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package issue2031 - -import ( - "encoding/json" - "fmt" -) - -// ArrayContainer defines model for ArrayContainer. -type ArrayContainer struct { - Values []string `json:"values,omitempty"` - AdditionalProperties map[string]interface{} `json:"-"` -} - -// Getter for additional properties for ArrayContainer. Returns the specified -// element and whether it was found -func (a ArrayContainer) Get(fieldName string) (value interface{}, found bool) { - if a.AdditionalProperties != nil { - value, found = a.AdditionalProperties[fieldName] - } - return -} - -// Setter for additional properties for ArrayContainer -func (a *ArrayContainer) Set(fieldName string, value interface{}) { - if a.AdditionalProperties == nil { - a.AdditionalProperties = make(map[string]interface{}) - } - a.AdditionalProperties[fieldName] = value -} - -// Override default JSON handling for ArrayContainer to handle AdditionalProperties -func (a *ArrayContainer) UnmarshalJSON(b []byte) error { - object := make(map[string]json.RawMessage) - err := json.Unmarshal(b, &object) - if err != nil { - return err - } - - if raw, found := object["values"]; found { - err = json.Unmarshal(raw, &a.Values) - if err != nil { - return fmt.Errorf("error reading 'values': %w", err) - } - delete(object, "values") - } - - if len(object) != 0 { - a.AdditionalProperties = make(map[string]interface{}) - for fieldName, fieldBuf := range object { - var fieldVal interface{} - err := json.Unmarshal(fieldBuf, &fieldVal) - if err != nil { - return fmt.Errorf("error unmarshaling field %s: %w", fieldName, err) - } - a.AdditionalProperties[fieldName] = fieldVal - } - } - return nil -} - -// Override default JSON handling for ArrayContainer to handle AdditionalProperties -func (a ArrayContainer) MarshalJSON() ([]byte, error) { - var err error - object := make(map[string]json.RawMessage) - - if a.Values != nil { - object["values"], err = json.Marshal(a.Values) - if err != nil { - return nil, fmt.Errorf("error marshaling 'values': %w", err) - } - } - - for fieldName, field := range a.AdditionalProperties { - object[fieldName], err = json.Marshal(field) - if err != nil { - return nil, fmt.Errorf("error marshaling '%s': %w", fieldName, err) - } - } - return json.Marshal(object) -} diff --git a/internal/test/issues/issue-2031/issue2031_test.go b/internal/test/issues/issue-2031/issue2031_test.go deleted file mode 100644 index fe631a8bcf..0000000000 --- a/internal/test/issues/issue-2031/issue2031_test.go +++ /dev/null @@ -1,18 +0,0 @@ -package issue2031 - -import ( - "encoding/json" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestMarshal(t *testing.T) { - value := ArrayContainer{} - content, err := json.Marshal(value) - require.NoError(t, err) - // the _optional array_ should be _omitted_ when null, not marshaled as null - // (which is not valid per the schema) - assert.Equal(t, "{}", string(content)) -} diff --git a/internal/test/issues/issue-2031/openapi.yaml b/internal/test/issues/issue-2031/openapi.yaml deleted file mode 100644 index 54aa5eb404..0000000000 --- a/internal/test/issues/issue-2031/openapi.yaml +++ /dev/null @@ -1,27 +0,0 @@ -openapi: "3.0.0" -info: - version: 1.0.0 - title: Issue 2031 -paths: - /test: - get: - responses: - "200": - description: A list of strings - content: - application/json: - schema: - $ref: "#/components/schemas/ArrayContainer" -components: - schemas: - ArrayContainer: - type: object - # enabling additionalProperties is required to expose one variant of the bug - additionalProperties: true - properties: - # NOTE: the array property is NOT required and NOT nullable - values: - x-go-type-skip-optional-pointer: true - type: array - items: - type: string diff --git a/internal/test/issues/issue-2031/prefer/config.yaml b/internal/test/issues/issue-2031/prefer/config.yaml deleted file mode 100644 index 4ec155a835..0000000000 --- a/internal/test/issues/issue-2031/prefer/config.yaml +++ /dev/null @@ -1,7 +0,0 @@ -package: issue2031 -generate: - models: true - client: true -output-options: - prefer-skip-optional-pointer: true -output: issue2031.gen.go diff --git a/internal/test/issues/issue-2031/prefer/generate.go b/internal/test/issues/issue-2031/prefer/generate.go deleted file mode 100644 index 1e29681627..0000000000 --- a/internal/test/issues/issue-2031/prefer/generate.go +++ /dev/null @@ -1,3 +0,0 @@ -package issue2031 - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml openapi.yaml diff --git a/internal/test/issues/issue-2031/prefer/issue2031_test.go b/internal/test/issues/issue-2031/prefer/issue2031_test.go deleted file mode 100644 index cd0c55c8dd..0000000000 --- a/internal/test/issues/issue-2031/prefer/issue2031_test.go +++ /dev/null @@ -1,63 +0,0 @@ -package issue2031 - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestNewGetTestRequest(t *testing.T) { - t.Run("does not add the user_ids[] parameter if zero value", func(t *testing.T) { - params := GetTestParams{} - - req, err := NewGetTestRequest("https://localhost", ¶ms) - require.NoError(t, err) - - assert.Equal(t, "https://localhost/test", req.URL.String()) - }) - - t.Run("does not add the user_ids[] parameter if nil", func(t *testing.T) { - params := GetTestParams{ - UserIds: nil, - } - - req, err := NewGetTestRequest("https://localhost", ¶ms) - require.NoError(t, err) - - assert.Equal(t, "https://localhost/test", req.URL.String()) - }) - - t.Run("adds the user_ids[] parameter if an explicitly initialised empty array", func(t *testing.T) { - params := GetTestParams{ - UserIds: []int{}, - } - - req, err := NewGetTestRequest("https://localhost", ¶ms) - require.NoError(t, err) - - assert.Equal(t, "https://localhost/test?user_ids%5B%5D=", req.URL.String()) - }) - - t.Run("adds the user_ids[] parameter if array contains a value", func(t *testing.T) { - params := GetTestParams{ - UserIds: []int{1}, - } - - req, err := NewGetTestRequest("https://localhost", ¶ms) - require.NoError(t, err) - - assert.Equal(t, "https://localhost/test?user_ids%5B%5D=1", req.URL.String()) - }) - - t.Run("handles multiple user_ids[] parameters", func(t *testing.T) { - params := GetTestParams{ - UserIds: []int{1, 100}, - } - - req, err := NewGetTestRequest("https://localhost", ¶ms) - require.NoError(t, err) - - assert.Equal(t, "https://localhost/test?user_ids%5B%5D=1&user_ids%5B%5D=100", req.URL.String()) - }) -} diff --git a/internal/test/issues/issue-2031/prefer/openapi.yaml b/internal/test/issues/issue-2031/prefer/openapi.yaml deleted file mode 100644 index d88d8df2fb..0000000000 --- a/internal/test/issues/issue-2031/prefer/openapi.yaml +++ /dev/null @@ -1,17 +0,0 @@ -openapi: "3.0.0" -info: - version: 1.0.0 - title: Issue 2031 -paths: - /test: - get: - parameters: - - name: "user_ids[]" - in: query - schema: - type: array - items: - type: integer - style: form - explode: true - required: false diff --git a/internal/test/issues/issue-2113/config.common.yaml b/internal/test/issues/issue-2113/config.common.yaml deleted file mode 100644 index f9803ed307..0000000000 --- a/internal/test/issues/issue-2113/config.common.yaml +++ /dev/null @@ -1,7 +0,0 @@ -# yaml-language-server: $schema=../../../../configuration-schema.json -package: common -generate: - models: true -output: gen/common/common.gen.go -output-options: - skip-prune: true diff --git a/internal/test/issues/issue-2113/doc.go b/internal/test/issues/issue-2113/doc.go deleted file mode 100644 index 89ddb3d195..0000000000 --- a/internal/test/issues/issue-2113/doc.go +++ /dev/null @@ -1,4 +0,0 @@ -package issue2113 - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.common.yaml common/spec.yaml -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.api.yaml spec.yaml diff --git a/internal/test/issues/issue-2113/issue_test.go b/internal/test/issues/issue-2113/issue_test.go deleted file mode 100644 index 5d5dbbe48c..0000000000 --- a/internal/test/issues/issue-2113/issue_test.go +++ /dev/null @@ -1,22 +0,0 @@ -package issue2113 - -import ( - "testing" - - "github.com/oapi-codegen/oapi-codegen/v2/internal/test/issues/issue-2113/gen/api" - "github.com/oapi-codegen/oapi-codegen/v2/internal/test/issues/issue-2113/gen/common" -) - -// TestExternalRefInResponse verifies that a $ref to an external -// components/responses object correctly qualifies the schema type -// with the external package import. See -// https://github.com/oapi-codegen/oapi-codegen/issues/2113 -func TestExternalRefInResponse(t *testing.T) { - // This will fail to compile if the generated code uses - // ProblemDetails instead of common.ProblemDetails (via the - // externalRef alias) in the default response type. - _ = api.ListThingsdefaultJSONResponse{ - Body: common.ProblemDetails{Title: "err", Status: 500}, - StatusCode: 500, - } -} diff --git a/internal/test/issues/issue-2113/spec.yaml b/internal/test/issues/issue-2113/spec.yaml deleted file mode 100644 index 9f4f50d95d..0000000000 --- a/internal/test/issues/issue-2113/spec.yaml +++ /dev/null @@ -1,21 +0,0 @@ -openapi: "3.0.4" -info: - title: API - version: "0.0.1" -paths: - /things: - get: - operationId: listThings - responses: - "200": - description: OK - content: - application/json: - schema: - type: array - items: - type: string - "400": - $ref: "./common/spec.yaml#/components/responses/StandardError" - default: - $ref: "./common/spec.yaml#/components/responses/StandardError" diff --git a/internal/test/issues/issue-2185/config.yaml b/internal/test/issues/issue-2185/config.yaml deleted file mode 100644 index 71a7ba132e..0000000000 --- a/internal/test/issues/issue-2185/config.yaml +++ /dev/null @@ -1,8 +0,0 @@ -# yaml-language-server: $schema=../../../../configuration-schema.json -package: issue2185 -output: issue2185.gen.go -generate: - models: true -output-options: - skip-prune: true - nullable-type: true diff --git a/internal/test/issues/issue-2185/generate.go b/internal/test/issues/issue-2185/generate.go deleted file mode 100644 index 9f5224eaeb..0000000000 --- a/internal/test/issues/issue-2185/generate.go +++ /dev/null @@ -1,3 +0,0 @@ -package issue2185 - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml spec.yaml diff --git a/internal/test/issues/issue-2185/issue2185.gen.go b/internal/test/issues/issue-2185/issue2185.gen.go deleted file mode 100644 index 6474c9c4d0..0000000000 --- a/internal/test/issues/issue-2185/issue2185.gen.go +++ /dev/null @@ -1,13 +0,0 @@ -// Package issue2185 provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package issue2185 - -import ( - "github.com/oapi-codegen/nullable" -) - -// Container defines model for Container. -type Container struct { - MayBeNull []nullable.Nullable[string] `json:"may-be-null"` -} diff --git a/internal/test/issues/issue-2185/issue2185_test.go b/internal/test/issues/issue-2185/issue2185_test.go deleted file mode 100644 index cc98e2b4d3..0000000000 --- a/internal/test/issues/issue-2185/issue2185_test.go +++ /dev/null @@ -1,19 +0,0 @@ -package issue2185 - -import ( - "testing" - - "github.com/oapi-codegen/nullable" - "github.com/stretchr/testify/require" -) - -func TestContainer_UsesNullableType(t *testing.T) { - c := Container{ - MayBeNull: []nullable.Nullable[string]{ - nullable.NewNullNullable[string](), - }, - } - - require.Len(t, c.MayBeNull, 1) - require.True(t, c.MayBeNull[0].IsNull()) -} diff --git a/internal/test/issues/issue-2185/spec.yaml b/internal/test/issues/issue-2185/spec.yaml deleted file mode 100644 index 814048bc8f..0000000000 --- a/internal/test/issues/issue-2185/spec.yaml +++ /dev/null @@ -1,15 +0,0 @@ -openapi: "3.0.3" -info: - title: test - version: 1.0.0 -components: - schemas: - Container: - required: - - "may-be-null" - properties: - "may-be-null": - type: array - items: - type: string - nullable: true diff --git a/internal/test/issues/issue-2190/config.yaml b/internal/test/issues/issue-2190/config.yaml deleted file mode 100644 index da89951cdc..0000000000 --- a/internal/test/issues/issue-2190/config.yaml +++ /dev/null @@ -1,9 +0,0 @@ -package: issue2190 -output: issue2190.gen.go -generate: - std-http-server: true - strict-server: true - models: true - client: true -output-options: - nullable-type: true diff --git a/internal/test/issues/issue-2190/generate.go b/internal/test/issues/issue-2190/generate.go deleted file mode 100644 index 74169c3fe3..0000000000 --- a/internal/test/issues/issue-2190/generate.go +++ /dev/null @@ -1,3 +0,0 @@ -package issue2190 - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml spec.yaml diff --git a/internal/test/issues/issue-2190/issue2190.gen.go b/internal/test/issues/issue-2190/issue2190.gen.go deleted file mode 100644 index c22e32724c..0000000000 --- a/internal/test/issues/issue-2190/issue2190.gen.go +++ /dev/null @@ -1,486 +0,0 @@ -//go:build go1.22 - -// Package issue2190 provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package issue2190 - -import ( - "context" - "encoding/json" - "fmt" - "io" - "net/http" - "net/url" - "strings" - - strictnethttp "github.com/oapi-codegen/runtime/strictmiddleware/nethttp" -) - -// Success defines model for Success. -type Success = string - -// RequestEditorFn is the function signature for the RequestEditor callback function -type RequestEditorFn func(ctx context.Context, req *http.Request) error - -// Doer performs HTTP requests. -// -// The standard http.Client implements this interface. -type HttpRequestDoer interface { - Do(req *http.Request) (*http.Response, error) -} - -// Client which conforms to the OpenAPI3 specification for this service. -type Client struct { - // The endpoint of the server conforming to this interface, with scheme, - // https://api.deepmap.com for example. This can contain a path relative - // to the server, such as https://api.deepmap.com/dev-test, and all the - // paths in the swagger spec will be appended to the server. - Server string - - // Doer for performing requests, typically a *http.Client with any - // customized settings, such as certificate chains. - Client HttpRequestDoer - - // A list of callbacks for modifying requests which are generated before sending over - // the network. - RequestEditors []RequestEditorFn -} - -// ClientOption allows setting custom parameters during construction -type ClientOption func(*Client) error - -// Creates a new Client, with reasonable defaults -func NewClient(server string, opts ...ClientOption) (*Client, error) { - // create a client with sane default values - client := Client{ - Server: server, - } - // mutate client and add all optional params - for _, o := range opts { - if err := o(&client); err != nil { - return nil, err - } - } - // ensure the server URL always has a trailing slash - if !strings.HasSuffix(client.Server, "/") { - client.Server += "/" - } - // create httpClient, if not already present - if client.Client == nil { - client.Client = &http.Client{} - } - return &client, nil -} - -// WithHTTPClient allows overriding the default Doer, which is -// automatically created using http.Client. This is useful for tests. -func WithHTTPClient(doer HttpRequestDoer) ClientOption { - return func(c *Client) error { - c.Client = doer - return nil - } -} - -// WithRequestEditorFn allows setting up a callback function, which will be -// called right before sending the request. This can be used to mutate the request. -func WithRequestEditorFn(fn RequestEditorFn) ClientOption { - return func(c *Client) error { - c.RequestEditors = append(c.RequestEditors, fn) - return nil - } -} - -// The interface specification for the client above. -type ClientInterface interface { - // GetTest request - GetTest(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) -} - -func (c *Client) GetTest(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewGetTestRequest(c.Server) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -// NewGetTestRequest generates requests for GetTest -func NewGetTestRequest(server string) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/v1/test") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -func (c *Client) applyEditors(ctx context.Context, req *http.Request, additionalEditors []RequestEditorFn) error { - for _, r := range c.RequestEditors { - if err := r(ctx, req); err != nil { - return err - } - } - for _, r := range additionalEditors { - if err := r(ctx, req); err != nil { - return err - } - } - return nil -} - -// ClientWithResponses builds on ClientInterface to offer response payloads -type ClientWithResponses struct { - ClientInterface -} - -// NewClientWithResponses creates a new ClientWithResponses, which wraps -// Client with return type handling -func NewClientWithResponses(server string, opts ...ClientOption) (*ClientWithResponses, error) { - client, err := NewClient(server, opts...) - if err != nil { - return nil, err - } - return &ClientWithResponses{client}, nil -} - -// WithBaseURL overrides the baseURL. -func WithBaseURL(baseURL string) ClientOption { - return func(c *Client) error { - newBaseURL, err := url.Parse(baseURL) - if err != nil { - return err - } - c.Server = newBaseURL.String() - return nil - } -} - -// ClientWithResponsesInterface is the interface specification for the client with responses above. -type ClientWithResponsesInterface interface { - // GetTestWithResponse request - GetTestWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*GetTestResponse, error) -} - -type GetTestResponse struct { - Body []byte - HTTPResponse *http.Response - JSON200 *Success -} - -// Status returns HTTPResponse.Status -func (r GetTestResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r GetTestResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -// GetTestWithResponse request returning *GetTestResponse -func (c *ClientWithResponses) GetTestWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*GetTestResponse, error) { - rsp, err := c.GetTest(ctx, reqEditors...) - if err != nil { - return nil, err - } - return ParseGetTestResponse(rsp) -} - -// ParseGetTestResponse parses an HTTP response from a GetTestWithResponse call -func ParseGetTestResponse(rsp *http.Response) (*GetTestResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &GetTestResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest Success - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON200 = &dest - - } - - return response, nil -} - -// ServerInterface represents all server handlers. -type ServerInterface interface { - - // (GET /v1/test) - GetTest(w http.ResponseWriter, r *http.Request) -} - -// ServerInterfaceWrapper converts contexts to parameters. -type ServerInterfaceWrapper struct { - Handler ServerInterface - HandlerMiddlewares []MiddlewareFunc - ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) -} - -type MiddlewareFunc func(http.Handler) http.Handler - -// GetTest operation middleware -func (siw *ServerInterfaceWrapper) GetTest(w http.ResponseWriter, r *http.Request) { - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.GetTest(w, r) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -type UnescapedCookieParamError struct { - ParamName string - Err error -} - -func (e *UnescapedCookieParamError) Error() string { - return fmt.Sprintf("error unescaping cookie parameter '%s'", e.ParamName) -} - -func (e *UnescapedCookieParamError) Unwrap() error { - return e.Err -} - -type UnmarshalingParamError struct { - ParamName string - Err error -} - -func (e *UnmarshalingParamError) Error() string { - return fmt.Sprintf("Error unmarshaling parameter %s as JSON: %s", e.ParamName, e.Err.Error()) -} - -func (e *UnmarshalingParamError) Unwrap() error { - return e.Err -} - -type RequiredParamError struct { - ParamName string -} - -func (e *RequiredParamError) Error() string { - return fmt.Sprintf("Query argument %s is required, but not found", e.ParamName) -} - -type RequiredHeaderError struct { - ParamName string - Err error -} - -func (e *RequiredHeaderError) Error() string { - return fmt.Sprintf("Header parameter %s is required, but not found", e.ParamName) -} - -func (e *RequiredHeaderError) Unwrap() error { - return e.Err -} - -type InvalidParamFormatError struct { - ParamName string - Err error -} - -func (e *InvalidParamFormatError) Error() string { - return fmt.Sprintf("Invalid format for parameter %s: %s", e.ParamName, e.Err.Error()) -} - -func (e *InvalidParamFormatError) Unwrap() error { - return e.Err -} - -type TooManyValuesForParamError struct { - ParamName string - Count int -} - -func (e *TooManyValuesForParamError) Error() string { - return fmt.Sprintf("Expected one value for %s, got %d", e.ParamName, e.Count) -} - -// Handler creates http.Handler with routing matching OpenAPI spec. -func Handler(si ServerInterface) http.Handler { - return HandlerWithOptions(si, StdHTTPServerOptions{}) -} - -// ServeMux is an abstraction of http.ServeMux. -type ServeMux interface { - HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request)) - ServeHTTP(w http.ResponseWriter, r *http.Request) -} - -type StdHTTPServerOptions struct { - BaseURL string - BaseRouter ServeMux - Middlewares []MiddlewareFunc - ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) -} - -// HandlerFromMux creates http.Handler with routing matching OpenAPI spec based on the provided mux. -func HandlerFromMux(si ServerInterface, m ServeMux) http.Handler { - return HandlerWithOptions(si, StdHTTPServerOptions{ - BaseRouter: m, - }) -} - -func HandlerFromMuxWithBaseURL(si ServerInterface, m ServeMux, baseURL string) http.Handler { - return HandlerWithOptions(si, StdHTTPServerOptions{ - BaseURL: baseURL, - BaseRouter: m, - }) -} - -// HandlerWithOptions creates http.Handler with additional options -func HandlerWithOptions(si ServerInterface, options StdHTTPServerOptions) http.Handler { - m := options.BaseRouter - - if m == nil { - m = http.NewServeMux() - } - if options.ErrorHandlerFunc == nil { - options.ErrorHandlerFunc = func(w http.ResponseWriter, r *http.Request, err error) { - http.Error(w, err.Error(), http.StatusBadRequest) - } - } - - wrapper := ServerInterfaceWrapper{ - Handler: si, - HandlerMiddlewares: options.Middlewares, - ErrorHandlerFunc: options.ErrorHandlerFunc, - } - - m.HandleFunc("GET "+options.BaseURL+"/v1/test", wrapper.GetTest) - - return m -} - -type SuccessJSONResponse string - -type UnauthorizedTextResponse string - -type GetTestRequestObject struct { -} - -type GetTestResponseObject interface { - VisitGetTestResponse(w http.ResponseWriter) error -} - -type GetTest200JSONResponse struct{ SuccessJSONResponse } - -func (response GetTest200JSONResponse) VisitGetTestResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(200) - - return json.NewEncoder(w).Encode(response) -} - -type GetTest401TextResponse UnauthorizedTextResponse - -func (response GetTest401TextResponse) VisitGetTestResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "text/plain") - w.WriteHeader(401) - - _, err := w.Write([]byte(response)) - return err -} - -// StrictServerInterface represents all server handlers. -type StrictServerInterface interface { - - // (GET /v1/test) - GetTest(ctx context.Context, request GetTestRequestObject) (GetTestResponseObject, error) -} - -type StrictHandlerFunc = strictnethttp.StrictHTTPHandlerFunc -type StrictMiddlewareFunc = strictnethttp.StrictHTTPMiddlewareFunc - -type StrictHTTPServerOptions struct { - RequestErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) - ResponseErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) -} - -func NewStrictHandler(ssi StrictServerInterface, middlewares []StrictMiddlewareFunc) ServerInterface { - return &strictHandler{ssi: ssi, middlewares: middlewares, options: StrictHTTPServerOptions{ - RequestErrorHandlerFunc: func(w http.ResponseWriter, r *http.Request, err error) { - http.Error(w, err.Error(), http.StatusBadRequest) - }, - ResponseErrorHandlerFunc: func(w http.ResponseWriter, r *http.Request, err error) { - http.Error(w, err.Error(), http.StatusInternalServerError) - }, - }} -} - -func NewStrictHandlerWithOptions(ssi StrictServerInterface, middlewares []StrictMiddlewareFunc, options StrictHTTPServerOptions) ServerInterface { - return &strictHandler{ssi: ssi, middlewares: middlewares, options: options} -} - -type strictHandler struct { - ssi StrictServerInterface - middlewares []StrictMiddlewareFunc - options StrictHTTPServerOptions -} - -// GetTest operation middleware -func (sh *strictHandler) GetTest(w http.ResponseWriter, r *http.Request) { - var request GetTestRequestObject - - handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { - return sh.ssi.GetTest(ctx, request.(GetTestRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "GetTest") - } - - response, err := handler(r.Context(), w, r, request) - - if err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } else if validResponse, ok := response.(GetTestResponseObject); ok { - if err := validResponse.VisitGetTestResponse(w); err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } - } else if response != nil { - sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) - } -} diff --git a/internal/test/issues/issue-2190/issue2190_test.go b/internal/test/issues/issue-2190/issue2190_test.go deleted file mode 100644 index 8dc7a0b075..0000000000 --- a/internal/test/issues/issue-2190/issue2190_test.go +++ /dev/null @@ -1,37 +0,0 @@ -package issue2190 - -import ( - "net/http/httptest" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -// TestGetTest401TextResponse verifies that the generated VisitGetTestResponse -// method on GetTest401TextResponse produces a valid text/plain 401 response. -// This is a regression test for https://github.com/oapi-codegen/oapi-codegen/issues/2190 -// where the generated code tried to do []byte(response) on a struct type, -// which does not compile. -func TestGetTest401TextResponse(t *testing.T) { - resp := GetTest401TextResponse("Unauthorized") - w := httptest.NewRecorder() - - err := resp.VisitGetTestResponse(w) - require.NoError(t, err) - assert.Equal(t, 401, w.Code) - assert.Equal(t, "text/plain", w.Header().Get("Content-Type")) - assert.Equal(t, "Unauthorized", w.Body.String()) -} - -// TestGetTest200JSONResponse verifies that the 200 JSON response path also works. -func TestGetTest200JSONResponse(t *testing.T) { - resp := GetTest200JSONResponse{SuccessJSONResponse("hello")} - w := httptest.NewRecorder() - - err := resp.VisitGetTestResponse(w) - require.NoError(t, err) - assert.Equal(t, 200, w.Code) - assert.Equal(t, "application/json", w.Header().Get("Content-Type")) - assert.Contains(t, w.Body.String(), "hello") -} diff --git a/internal/test/issues/issue-2190/spec.yaml b/internal/test/issues/issue-2190/spec.yaml deleted file mode 100644 index 2844100e3d..0000000000 --- a/internal/test/issues/issue-2190/spec.yaml +++ /dev/null @@ -1,30 +0,0 @@ -openapi: 3.0.3 -info: - title: test - version: 1.0.0 -servers: - - url: https://te.st -paths: - /v1/test: - get: - operationId: GetTest - responses: - "200": - $ref: "#/components/responses/Success" - "401": - $ref: "#/components/responses/Unauthorized" -components: - responses: - Success: - description: Success - content: - application/json: - schema: - type: string - Unauthorized: - description: Unauthorized - content: - text/plain: - schema: - type: string - example: "Unauthorized" diff --git a/internal/test/issues/issue-2232/config.yaml b/internal/test/issues/issue-2232/config.yaml deleted file mode 100644 index 6368de1d4d..0000000000 --- a/internal/test/issues/issue-2232/config.yaml +++ /dev/null @@ -1,5 +0,0 @@ -package: issue2232 -output: issue2232.gen.go -generate: - std-http-server: true - models: true diff --git a/internal/test/issues/issue-2232/generate.go b/internal/test/issues/issue-2232/generate.go deleted file mode 100644 index f6767c10e1..0000000000 --- a/internal/test/issues/issue-2232/generate.go +++ /dev/null @@ -1,3 +0,0 @@ -package issue2232 - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml spec.yaml diff --git a/internal/test/issues/issue-2232/issue2232.gen.go b/internal/test/issues/issue-2232/issue2232.gen.go deleted file mode 100644 index 1820ba5f29..0000000000 --- a/internal/test/issues/issue-2232/issue2232.gen.go +++ /dev/null @@ -1,260 +0,0 @@ -//go:build go1.22 - -// Package issue2232 provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package issue2232 - -import ( - "fmt" - "net/http" - - "github.com/oapi-codegen/runtime" -) - -// Defines values for GetEndpointParamsEnvParamLevel. -const ( - GetEndpointParamsEnvParamLevelDev GetEndpointParamsEnvParamLevel = "dev" - GetEndpointParamsEnvParamLevelLive GetEndpointParamsEnvParamLevel = "live" -) - -// Valid indicates whether the value is a known member of the GetEndpointParamsEnvParamLevel enum. -func (e GetEndpointParamsEnvParamLevel) Valid() bool { - switch e { - case GetEndpointParamsEnvParamLevelDev: - return true - case GetEndpointParamsEnvParamLevelLive: - return true - default: - return false - } -} - -// Defines values for GetEndpointParamsEnvSchemaLevel. -const ( - GetEndpointParamsEnvSchemaLevelDev GetEndpointParamsEnvSchemaLevel = "dev" - GetEndpointParamsEnvSchemaLevelLive GetEndpointParamsEnvSchemaLevel = "live" -) - -// Valid indicates whether the value is a known member of the GetEndpointParamsEnvSchemaLevel enum. -func (e GetEndpointParamsEnvSchemaLevel) Valid() bool { - switch e { - case GetEndpointParamsEnvSchemaLevelDev: - return true - case GetEndpointParamsEnvSchemaLevelLive: - return true - default: - return false - } -} - -// GetEndpointParams defines parameters for GetEndpoint. -type GetEndpointParams struct { - EnvParamLevel GetEndpointParamsEnvParamLevel `form:"env_param_level" json:"env_param_level" validate:"required,oneof=dev live"` - EnvSchemaLevel GetEndpointParamsEnvSchemaLevel `form:"env_schema_level" json:"env_schema_level" validate:"required,oneof=dev live"` - Limit *int `form:"limit,omitempty" json:"limit,omitempty" validate:"min=0,max=100"` -} - -// GetEndpointParamsEnvParamLevel defines parameters for GetEndpoint. -type GetEndpointParamsEnvParamLevel string - -// GetEndpointParamsEnvSchemaLevel defines parameters for GetEndpoint. -type GetEndpointParamsEnvSchemaLevel string - -// ServerInterface represents all server handlers. -type ServerInterface interface { - - // (GET /v1/endpoint) - GetEndpoint(w http.ResponseWriter, r *http.Request, params GetEndpointParams) -} - -// ServerInterfaceWrapper converts contexts to parameters. -type ServerInterfaceWrapper struct { - Handler ServerInterface - HandlerMiddlewares []MiddlewareFunc - ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) -} - -type MiddlewareFunc func(http.Handler) http.Handler - -// GetEndpoint operation middleware -func (siw *ServerInterfaceWrapper) GetEndpoint(w http.ResponseWriter, r *http.Request) { - - var err error - - // Parameter object where we will unmarshal all parameters from the context - var params GetEndpointParams - - // ------------- Required query parameter "env_param_level" ------------- - - if paramValue := r.URL.Query().Get("env_param_level"); paramValue != "" { - - } else { - siw.ErrorHandlerFunc(w, r, &RequiredParamError{ParamName: "env_param_level"}) - return - } - - err = runtime.BindQueryParameterWithOptions("form", true, true, "env_param_level", r.URL.Query(), ¶ms.EnvParamLevel, runtime.BindQueryParameterOptions{Type: "string", Format: ""}) - if err != nil { - siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "env_param_level", Err: err}) - return - } - - // ------------- Required query parameter "env_schema_level" ------------- - - if paramValue := r.URL.Query().Get("env_schema_level"); paramValue != "" { - - } else { - siw.ErrorHandlerFunc(w, r, &RequiredParamError{ParamName: "env_schema_level"}) - return - } - - err = runtime.BindQueryParameterWithOptions("form", true, true, "env_schema_level", r.URL.Query(), ¶ms.EnvSchemaLevel, runtime.BindQueryParameterOptions{Type: "string", Format: ""}) - if err != nil { - siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "env_schema_level", Err: err}) - return - } - - // ------------- Optional query parameter "limit" ------------- - - err = runtime.BindQueryParameterWithOptions("form", true, false, "limit", r.URL.Query(), ¶ms.Limit, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) - if err != nil { - siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "limit", Err: err}) - return - } - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.GetEndpoint(w, r, params) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -type UnescapedCookieParamError struct { - ParamName string - Err error -} - -func (e *UnescapedCookieParamError) Error() string { - return fmt.Sprintf("error unescaping cookie parameter '%s'", e.ParamName) -} - -func (e *UnescapedCookieParamError) Unwrap() error { - return e.Err -} - -type UnmarshalingParamError struct { - ParamName string - Err error -} - -func (e *UnmarshalingParamError) Error() string { - return fmt.Sprintf("Error unmarshaling parameter %s as JSON: %s", e.ParamName, e.Err.Error()) -} - -func (e *UnmarshalingParamError) Unwrap() error { - return e.Err -} - -type RequiredParamError struct { - ParamName string -} - -func (e *RequiredParamError) Error() string { - return fmt.Sprintf("Query argument %s is required, but not found", e.ParamName) -} - -type RequiredHeaderError struct { - ParamName string - Err error -} - -func (e *RequiredHeaderError) Error() string { - return fmt.Sprintf("Header parameter %s is required, but not found", e.ParamName) -} - -func (e *RequiredHeaderError) Unwrap() error { - return e.Err -} - -type InvalidParamFormatError struct { - ParamName string - Err error -} - -func (e *InvalidParamFormatError) Error() string { - return fmt.Sprintf("Invalid format for parameter %s: %s", e.ParamName, e.Err.Error()) -} - -func (e *InvalidParamFormatError) Unwrap() error { - return e.Err -} - -type TooManyValuesForParamError struct { - ParamName string - Count int -} - -func (e *TooManyValuesForParamError) Error() string { - return fmt.Sprintf("Expected one value for %s, got %d", e.ParamName, e.Count) -} - -// Handler creates http.Handler with routing matching OpenAPI spec. -func Handler(si ServerInterface) http.Handler { - return HandlerWithOptions(si, StdHTTPServerOptions{}) -} - -// ServeMux is an abstraction of http.ServeMux. -type ServeMux interface { - HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request)) - ServeHTTP(w http.ResponseWriter, r *http.Request) -} - -type StdHTTPServerOptions struct { - BaseURL string - BaseRouter ServeMux - Middlewares []MiddlewareFunc - ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) -} - -// HandlerFromMux creates http.Handler with routing matching OpenAPI spec based on the provided mux. -func HandlerFromMux(si ServerInterface, m ServeMux) http.Handler { - return HandlerWithOptions(si, StdHTTPServerOptions{ - BaseRouter: m, - }) -} - -func HandlerFromMuxWithBaseURL(si ServerInterface, m ServeMux, baseURL string) http.Handler { - return HandlerWithOptions(si, StdHTTPServerOptions{ - BaseURL: baseURL, - BaseRouter: m, - }) -} - -// HandlerWithOptions creates http.Handler with additional options -func HandlerWithOptions(si ServerInterface, options StdHTTPServerOptions) http.Handler { - m := options.BaseRouter - - if m == nil { - m = http.NewServeMux() - } - if options.ErrorHandlerFunc == nil { - options.ErrorHandlerFunc = func(w http.ResponseWriter, r *http.Request, err error) { - http.Error(w, err.Error(), http.StatusBadRequest) - } - } - - wrapper := ServerInterfaceWrapper{ - Handler: si, - HandlerMiddlewares: options.Middlewares, - ErrorHandlerFunc: options.ErrorHandlerFunc, - } - - m.HandleFunc("GET "+options.BaseURL+"/v1/endpoint", wrapper.GetEndpoint) - - return m -} diff --git a/internal/test/issues/issue-2232/issue2232_test.go b/internal/test/issues/issue-2232/issue2232_test.go deleted file mode 100644 index a8ae51836e..0000000000 --- a/internal/test/issues/issue-2232/issue2232_test.go +++ /dev/null @@ -1,41 +0,0 @@ -package issue2232 - -import ( - "reflect" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -// TestExtraTagsOnQueryParams verifies that x-oapi-codegen-extra-tags is applied -// to query parameter struct fields regardless of whether the extension is placed -// at the parameter level or at the schema level within the parameter. -// This is a regression test for https://github.com/oapi-codegen/oapi-codegen/issues/2232 -func TestExtraTagsOnQueryParams(t *testing.T) { - paramType := reflect.TypeOf(GetEndpointParams{}) - - t.Run("parameter-level extension", func(t *testing.T) { - field, ok := paramType.FieldByName("EnvParamLevel") - require.True(t, ok, "field EnvParamLevel should exist") - - assert.Equal(t, `required,oneof=dev live`, field.Tag.Get("validate"), - "x-oapi-codegen-extra-tags at parameter level should produce validate tag") - }) - - t.Run("schema-level extension", func(t *testing.T) { - field, ok := paramType.FieldByName("EnvSchemaLevel") - require.True(t, ok, "field EnvSchemaLevel should exist") - - assert.Equal(t, `required,oneof=dev live`, field.Tag.Get("validate"), - "x-oapi-codegen-extra-tags at schema level within a parameter should produce validate tag") - }) - - t.Run("schema-level extension on optional param", func(t *testing.T) { - field, ok := paramType.FieldByName("Limit") - require.True(t, ok, "field Limit should exist") - - assert.Equal(t, `min=0,max=100`, field.Tag.Get("validate"), - "x-oapi-codegen-extra-tags at schema level within an optional parameter should produce validate tag") - }) -} diff --git a/internal/test/issues/issue-2232/spec.yaml b/internal/test/issues/issue-2232/spec.yaml deleted file mode 100644 index 0fea5cba83..0000000000 --- a/internal/test/issues/issue-2232/spec.yaml +++ /dev/null @@ -1,46 +0,0 @@ -openapi: "3.0.3" -info: - title: test - version: 1.0.0 -paths: - /v1/endpoint: - get: - operationId: GetEndpoint - parameters: - - name: env_param_level - in: query - required: true - schema: - type: string - enum: - - dev - - live - x-oapi-codegen-extra-tags: - validate: "required,oneof=dev live" - - name: env_schema_level - in: query - required: true - schema: - type: string - enum: - - dev - - live - x-oapi-codegen-extra-tags: - validate: "required,oneof=dev live" - - name: limit - in: query - required: false - schema: - type: integer - x-oapi-codegen-extra-tags: - validate: "min=0,max=100" - responses: - "200": - description: Success - content: - application/json: - schema: - type: object - properties: - message: - type: string diff --git a/internal/test/issues/issue-312/doc.go b/internal/test/issues/issue-312/doc.go deleted file mode 100644 index 768a4595b8..0000000000 --- a/internal/test/issues/issue-312/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -package issue312 - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml spec.yaml diff --git a/internal/test/issues/issue-312/issue_test.go b/internal/test/issues/issue-312/issue_test.go deleted file mode 100644 index 23a14649dc..0000000000 --- a/internal/test/issues/issue-312/issue_test.go +++ /dev/null @@ -1,127 +0,0 @@ -package issue312 - -import ( - "context" - "errors" - "net/http" - "net/http/httptest" - "testing" - - "github.com/labstack/echo/v4" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/mock" - "github.com/stretchr/testify/require" -) - -const hostname = "http://host" - -func TestClient_WhenPathHasColon_RequestHasCorrectPath(t *testing.T) { - doer := &HTTPRequestDoerMock{} - client, _ := NewClientWithResponses(hostname, WithHTTPClient(doer)) - _ = client - - doer.On("Do", mock.Anything).Return(nil, errors.New("something went wrong")).Run(func(args mock.Arguments) { - req, ok := args.Get(0).(*http.Request) - assert.True(t, ok) - assert.Equal(t, "http://host/pets:validate", req.URL.String()) - }) - - // TODO: this err should be checked, but it defaults to returning the "something went wrong", so we should refactor accordingly - _, _ = client.ValidatePetsWithResponse(context.Background(), ValidatePetsJSONRequestBody{ - Names: []string{"fido"}, - }) - doer.AssertExpectations(t) -} - -func TestClient_WhenPathHasId_RequestHasCorrectPath(t *testing.T) { - doer := &HTTPRequestDoerMock{} - client, _ := NewClientWithResponses(hostname, WithHTTPClient(doer)) - _ = client - - doer.On("Do", mock.Anything).Return(nil, errors.New("something went wrong")).Run(func(args mock.Arguments) { - req, ok := args.Get(0).(*http.Request) - assert.True(t, ok) - assert.Equal(t, "/pets/id", req.URL.Path) - }) - petID := "id" - // TODO: this err should be checked, but it defaults to returning the "something went wrong", so we should refactor accordingly - _, _ = client.GetPetWithResponse(context.Background(), petID) - doer.AssertExpectations(t) -} - -func TestClient_WhenPathHasIdContainingReservedCharacter_RequestHasCorrectPath(t *testing.T) { - doer := &HTTPRequestDoerMock{} - client, _ := NewClientWithResponses(hostname, WithHTTPClient(doer)) - _ = client - - doer.On("Do", mock.Anything).Return(nil, errors.New("something went wrong")).Run(func(args mock.Arguments) { - req, ok := args.Get(0).(*http.Request) - assert.True(t, ok) - assert.Equal(t, "http://host/pets/id1%2Fid2", req.URL.String()) - }) - petID := "id1/id2" - // TODO: this err should be checked, but it defaults to returning the "something went wrong", so we should refactor accordingly - _, _ = client.GetPetWithResponse(context.Background(), petID) - doer.AssertExpectations(t) -} - -func TestClient_ServerUnescapesEscapedArg(t *testing.T) { - - e := echo.New() - m := &MockClient{} - RegisterHandlers(e, m) - - svr := httptest.NewServer(e) - defer svr.Close() - - // We'll make a function in the mock client which records the value of - // the petId variable - receivedPetID := "" - m.getPet = func(ctx echo.Context, petId string) error { - receivedPetID = petId - return ctx.NoContent(http.StatusOK) - } - - client, err := NewClientWithResponses(svr.URL) - require.NoError(t, err) - - petID := "id1/id2" - response, err := client.GetPetWithResponse(context.Background(), petID) - require.NoError(t, err) - require.Equal(t, http.StatusOK, response.StatusCode()) - assert.Equal(t, petID, receivedPetID) -} - -// HTTPRequestDoerMock mocks the interface HttpRequestDoerMock. -type HTTPRequestDoerMock struct { - mock.Mock -} - -func (m *HTTPRequestDoerMock) Do(req *http.Request) (*http.Response, error) { - args := m.Called(req) - if args.Get(0) == nil { - return nil, args.Error(1) - } - return args.Get(0).(*http.Response), args.Error(1) -} - -// An implementation of the server interface which helps us check server -// expectations for funky paths and parameters. -type MockClient struct { - getPet func(ctx echo.Context, petId string) error - validatePets func(ctx echo.Context) error -} - -func (m *MockClient) GetPet(ctx echo.Context, petId string) error { - if m.getPet != nil { - return m.getPet(ctx, petId) - } - return ctx.NoContent(http.StatusNotImplemented) -} - -func (m *MockClient) ValidatePets(ctx echo.Context) error { - if m.validatePets != nil { - return m.validatePets(ctx) - } - return ctx.NoContent(http.StatusNotImplemented) -} diff --git a/internal/test/issues/issue-52/issue.gen.go b/internal/test/issues/issue-52/issue.gen.go deleted file mode 100644 index f024999d6a..0000000000 --- a/internal/test/issues/issue-52/issue.gen.go +++ /dev/null @@ -1,391 +0,0 @@ -// Package issue52 provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package issue52 - -import ( - "bytes" - "compress/gzip" - "context" - "encoding/base64" - "encoding/json" - "fmt" - "io" - "net/http" - "net/url" - "path" - "strings" - - "github.com/getkin/kin-openapi/openapi3" - "github.com/labstack/echo/v4" -) - -// ArrayValue defines model for ArrayValue. -type ArrayValue = []Value - -// Document defines model for Document. -type Document struct { - Fields *map[string]Value `json:"fields,omitempty"` -} - -// Value defines model for Value. -type Value struct { - ArrayValue *ArrayValue `json:"arrayValue,omitempty"` - StringValue *string `json:"stringValue,omitempty"` -} - -// RequestEditorFn is the function signature for the RequestEditor callback function -type RequestEditorFn func(ctx context.Context, req *http.Request) error - -// Doer performs HTTP requests. -// -// The standard http.Client implements this interface. -type HttpRequestDoer interface { - Do(req *http.Request) (*http.Response, error) -} - -// Client which conforms to the OpenAPI3 specification for this service. -type Client struct { - // The endpoint of the server conforming to this interface, with scheme, - // https://api.deepmap.com for example. This can contain a path relative - // to the server, such as https://api.deepmap.com/dev-test, and all the - // paths in the swagger spec will be appended to the server. - Server string - - // Doer for performing requests, typically a *http.Client with any - // customized settings, such as certificate chains. - Client HttpRequestDoer - - // A list of callbacks for modifying requests which are generated before sending over - // the network. - RequestEditors []RequestEditorFn -} - -// ClientOption allows setting custom parameters during construction -type ClientOption func(*Client) error - -// Creates a new Client, with reasonable defaults -func NewClient(server string, opts ...ClientOption) (*Client, error) { - // create a client with sane default values - client := Client{ - Server: server, - } - // mutate client and add all optional params - for _, o := range opts { - if err := o(&client); err != nil { - return nil, err - } - } - // ensure the server URL always has a trailing slash - if !strings.HasSuffix(client.Server, "/") { - client.Server += "/" - } - // create httpClient, if not already present - if client.Client == nil { - client.Client = &http.Client{} - } - return &client, nil -} - -// WithHTTPClient allows overriding the default Doer, which is -// automatically created using http.Client. This is useful for tests. -func WithHTTPClient(doer HttpRequestDoer) ClientOption { - return func(c *Client) error { - c.Client = doer - return nil - } -} - -// WithRequestEditorFn allows setting up a callback function, which will be -// called right before sending the request. This can be used to mutate the request. -func WithRequestEditorFn(fn RequestEditorFn) ClientOption { - return func(c *Client) error { - c.RequestEditors = append(c.RequestEditors, fn) - return nil - } -} - -// The interface specification for the client above. -type ClientInterface interface { - // ExampleGet request - ExampleGet(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) -} - -func (c *Client) ExampleGet(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewExampleGetRequest(c.Server) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -// NewExampleGetRequest generates requests for ExampleGet -func NewExampleGetRequest(server string) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/example") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -func (c *Client) applyEditors(ctx context.Context, req *http.Request, additionalEditors []RequestEditorFn) error { - for _, r := range c.RequestEditors { - if err := r(ctx, req); err != nil { - return err - } - } - for _, r := range additionalEditors { - if err := r(ctx, req); err != nil { - return err - } - } - return nil -} - -// ClientWithResponses builds on ClientInterface to offer response payloads -type ClientWithResponses struct { - ClientInterface -} - -// NewClientWithResponses creates a new ClientWithResponses, which wraps -// Client with return type handling -func NewClientWithResponses(server string, opts ...ClientOption) (*ClientWithResponses, error) { - client, err := NewClient(server, opts...) - if err != nil { - return nil, err - } - return &ClientWithResponses{client}, nil -} - -// WithBaseURL overrides the baseURL. -func WithBaseURL(baseURL string) ClientOption { - return func(c *Client) error { - newBaseURL, err := url.Parse(baseURL) - if err != nil { - return err - } - c.Server = newBaseURL.String() - return nil - } -} - -// ClientWithResponsesInterface is the interface specification for the client with responses above. -type ClientWithResponsesInterface interface { - // ExampleGetWithResponse request - ExampleGetWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*ExampleGetResponse, error) -} - -type ExampleGetResponse struct { - Body []byte - HTTPResponse *http.Response - JSON200 *Document -} - -// Status returns HTTPResponse.Status -func (r ExampleGetResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r ExampleGetResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -// ExampleGetWithResponse request returning *ExampleGetResponse -func (c *ClientWithResponses) ExampleGetWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*ExampleGetResponse, error) { - rsp, err := c.ExampleGet(ctx, reqEditors...) - if err != nil { - return nil, err - } - return ParseExampleGetResponse(rsp) -} - -// ParseExampleGetResponse parses an HTTP response from a ExampleGetWithResponse call -func ParseExampleGetResponse(rsp *http.Response) (*ExampleGetResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &ExampleGetResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest Document - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON200 = &dest - - } - - return response, nil -} - -// ServerInterface represents all server handlers. -type ServerInterface interface { - - // (GET /example) - ExampleGet(ctx echo.Context) error -} - -// ServerInterfaceWrapper converts echo contexts to parameters. -type ServerInterfaceWrapper struct { - Handler ServerInterface -} - -// ExampleGet converts echo context to params. -func (w *ServerInterfaceWrapper) ExampleGet(ctx echo.Context) error { - var err error - - // Invoke the callback with all the unmarshaled arguments - err = w.Handler.ExampleGet(ctx) - return err -} - -// This is a simple interface which specifies echo.Route addition functions which -// are present on both echo.Echo and echo.Group, since we want to allow using -// either of them for path registration -type EchoRouter interface { - CONNECT(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - DELETE(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - GET(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - HEAD(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - OPTIONS(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - PATCH(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - POST(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - PUT(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - TRACE(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route -} - -// RegisterHandlers adds each server route to the EchoRouter. -func RegisterHandlers(router EchoRouter, si ServerInterface) { - RegisterHandlersWithBaseURL(router, si, "") -} - -// Registers handlers, and prepends BaseURL to the paths, so that the paths -// can be served under a prefix. -func RegisterHandlersWithBaseURL(router EchoRouter, si ServerInterface, baseURL string) { - - wrapper := ServerInterfaceWrapper{ - Handler: si, - } - - router.GET(baseURL+"/example", wrapper.ExampleGet) - -} - -// Base64 encoded, gzipped, json marshaled Swagger object -var swaggerSpec = []string{ - - "H4sIAAAAAAAC/5RSwU7rMBD8lWjfO0ZJXt/NNyQQQgjBiROXxd42Lo5t2ZuKqsq/o3XaQgQCcYo92Zmd", - "He8BdBhi8OQ5gzpA1j0NWI4XKeH+Ed1IcrNMQ4H/JlqDgj/tO7E9stq5eqqB95FAAYqE3C+DHgfyLAIx", - "hUiJLRW5tSVnygmNsWyDR/ewqPhNw/C8Jc0wfUZqOI+yNICLMb9r9iGQqYbMyfrNmXhsN6NfGRDI+nWQ", - "YkNZJxtlWlBwhy9U5TFRxT1ylUiPKdsdVaKQK0xU9eiNI1PN1t3+yUMNbNlJB3rFITqCGnaU8qzZNV3z", - "T2yGSB6jBQX/m65ZQQ0RuS+TtyeiOsCGytuIOoqtGwMKrub/18RQQ6Icg89zaKuuk48Ono+vijE6qwu3", - "3WbxcFqmn2I970aJaBnN/a2g0zS9BQAA//+hEzLlqAIAAA==", -} - -// GetSwagger returns the content of the embedded swagger specification file -// or error if failed to decode -func decodeSpec() ([]byte, error) { - zipped, err := base64.StdEncoding.DecodeString(strings.Join(swaggerSpec, "")) - if err != nil { - return nil, fmt.Errorf("error base64 decoding spec: %w", err) - } - zr, err := gzip.NewReader(bytes.NewReader(zipped)) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - var buf bytes.Buffer - _, err = buf.ReadFrom(zr) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - - return buf.Bytes(), nil -} - -var rawSpec = decodeSpecCached() - -// a naive cached of a decoded swagger spec -func decodeSpecCached() func() ([]byte, error) { - data, err := decodeSpec() - return func() ([]byte, error) { - return data, err - } -} - -// Constructs a synthetic filesystem for resolving external references when loading openapi specifications. -func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { - res := make(map[string]func() ([]byte, error)) - if len(pathToFile) > 0 { - res[pathToFile] = rawSpec - } - - return res -} - -// GetSwagger returns the Swagger specification corresponding to the generated code -// in this file. The external references of Swagger specification are resolved. -// The logic of resolving external references is tightly connected to "import-mapping" feature. -// Externally referenced files must be embedded in the corresponding golang packages. -// Urls can be supported but this task was out of the scope. -func GetSwagger() (swagger *openapi3.T, err error) { - resolvePath := PathToRawSpec("") - - loader := openapi3.NewLoader() - loader.IsExternalRefsAllowed = true - loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() - pathToFile = path.Clean(pathToFile) - getSpec, ok := resolvePath[pathToFile] - if !ok { - err1 := fmt.Errorf("path not found: %s", pathToFile) - return nil, err1 - } - return getSpec() - } - var specData []byte - specData, err = rawSpec() - if err != nil { - return - } - swagger, err = loader.LoadFromData(specData) - if err != nil { - return - } - return -} diff --git a/internal/test/issues/issue-52/issue_test.go b/internal/test/issues/issue-52/issue_test.go deleted file mode 100644 index 0288c2aead..0000000000 --- a/internal/test/issues/issue-52/issue_test.go +++ /dev/null @@ -1,31 +0,0 @@ -package issue52 - -import ( - _ "embed" - "testing" - - "github.com/getkin/kin-openapi/openapi3" - "github.com/oapi-codegen/oapi-codegen/v2/pkg/codegen" - "github.com/stretchr/testify/require" -) - -//go:embed spec.yaml -var spec []byte - -func TestIssue(t *testing.T) { - swagger, err := openapi3.NewLoader().LoadFromData(spec) - require.NoError(t, err) - - opts := codegen.Configuration{ - PackageName: "issue52", - Generate: codegen.GenerateOptions{ - EchoServer: true, - Client: true, - Models: true, - EmbeddedSpec: true, - }, - } - - _, err = codegen.Generate(swagger, opts) - require.NoError(t, err) -} diff --git a/internal/test/issues/issue-52/spec.yaml b/internal/test/issues/issue-52/spec.yaml deleted file mode 100644 index d44a63e692..0000000000 --- a/internal/test/issues/issue-52/spec.yaml +++ /dev/null @@ -1,37 +0,0 @@ -openapi: 3.0.2 -info: - version: '0.0.1' - title: example - description: | - Make sure that recursive types are handled properly -paths: - /example: - get: - operationId: exampleGet - responses: - '200': - description: "OK" - content: - 'application/json': - schema: - $ref: '#/components/schemas/Document' -components: - schemas: - Document: - type: object - properties: - fields: - type: object - additionalProperties: - $ref: '#/components/schemas/Value' - Value: - type: object - properties: - stringValue: - type: string - arrayValue: - $ref: '#/components/schemas/ArrayValue' - ArrayValue: - type: array - items: - $ref: '#/components/schemas/Value' diff --git a/internal/test/issues/issue-579/gen.go b/internal/test/issues/issue-579/gen.go deleted file mode 100644 index 7b198d0cdf..0000000000 --- a/internal/test/issues/issue-579/gen.go +++ /dev/null @@ -1,3 +0,0 @@ -package issue579 - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --package=issue579 --generate=types,skip-prune --alias-types -o issue.gen.go spec.yaml diff --git a/internal/test/issues/issue-579/issue.gen.go b/internal/test/issues/issue-579/issue.gen.go deleted file mode 100644 index 54326646d9..0000000000 --- a/internal/test/issues/issue-579/issue.gen.go +++ /dev/null @@ -1,17 +0,0 @@ -// Package issue579 provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package issue579 - -import ( - openapi_types "github.com/oapi-codegen/runtime/types" -) - -// AliasedDate defines model for AliasedDate. -type AliasedDate = openapi_types.Date - -// Pet defines model for Pet. -type Pet struct { - Born *AliasedDate `json:"born,omitempty"` - BornAt *openapi_types.Date `json:"born_at,omitempty"` -} diff --git a/internal/test/issues/issue-579/issue_test.go b/internal/test/issues/issue-579/issue_test.go deleted file mode 100644 index 7c92a42205..0000000000 --- a/internal/test/issues/issue-579/issue_test.go +++ /dev/null @@ -1,14 +0,0 @@ -package issue579 - -import ( - "encoding/json" - "testing" - - "github.com/stretchr/testify/require" -) - -func TestAliasedDate(t *testing.T) { - pet := Pet{} - err := json.Unmarshal([]byte(`{"born": "2022-05-19", "born_at": "2022-05-20"}`), &pet) - require.NoError(t, err) -} diff --git a/internal/test/issues/issue-579/spec.yaml b/internal/test/issues/issue-579/spec.yaml deleted file mode 100644 index 2bf359c4dc..0000000000 --- a/internal/test/issues/issue-579/spec.yaml +++ /dev/null @@ -1,27 +0,0 @@ -openapi: "3.0.0" -info: - version: 1.0.0 - title: Issue 579 test -paths: - /placeholder: - get: - responses: - 200: - description: placeholder - content: - text/plain: - schema: - type: string -components: - schemas: - Pet: - type: object - properties: - born: - $ref: "#/components/schemas/AliasedDate" - born_at: - type: string - format: date - AliasedDate: - type: string - format: date diff --git a/internal/test/issues/issue-832/config.yaml b/internal/test/issues/issue-832/config.yaml deleted file mode 100644 index 446d7a14e6..0000000000 --- a/internal/test/issues/issue-832/config.yaml +++ /dev/null @@ -1,6 +0,0 @@ -# yaml-language-server: $schema=../../../../configuration-schema.json -package: issue_832 -generate: - models: true - embedded-spec: true -output: issue.gen.go diff --git a/internal/test/issues/issue-832/generate.go b/internal/test/issues/issue-832/generate.go deleted file mode 100644 index 79b06c7131..0000000000 --- a/internal/test/issues/issue-832/generate.go +++ /dev/null @@ -1,3 +0,0 @@ -package issue_832 - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml spec.yaml diff --git a/internal/test/issues/issue-832/issue.gen.go b/internal/test/issues/issue-832/issue.gen.go deleted file mode 100644 index 4a5aa56a3d..0000000000 --- a/internal/test/issues/issue-832/issue.gen.go +++ /dev/null @@ -1,137 +0,0 @@ -// Package issue_832 provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package issue_832 - -import ( - "bytes" - "compress/gzip" - "encoding/base64" - "fmt" - "net/url" - "path" - "strings" - - "github.com/getkin/kin-openapi/openapi3" -) - -// Defines values for Document_Status. -const ( - Four Document_Status = "four" - One Document_Status = "one" - Three Document_Status = "three" - Two Document_Status = "two" -) - -// Valid indicates whether the value is a known member of the Document_Status enum. -func (e Document_Status) Valid() bool { - switch e { - case Four: - return true - case One: - return true - case Three: - return true - case Two: - return true - default: - return false - } -} - -// Document defines model for Document. -type Document struct { - Name *string `json:"name,omitempty"` - Status *Document_Status `json:"status,omitempty"` -} - -// Document_Status defines model for Document.status. -type Document_Status string - -// DocumentStatus defines model for DocumentStatus. -type DocumentStatus struct { - Value *string `json:"value,omitempty"` -} - -// Base64 encoded, gzipped, json marshaled Swagger object -var swaggerSpec = []string{ - - "H4sIAAAAAAAC/7ySz0/rMAzH/5XK7x27tq/vljMIIYQ47AgIhdRbM9o4Styxaer/jpxuReOHxIlL4zq2", - "vx/HPoCh3pNDxxHUAaJpsdfJvCAz9OhYbB/IY2CL6cbpHuXkvUdQEDlYt4Yxh8iahxSCbuhB3QM5hBz4", - "leTbBpS/FQ0BHvMP6TnsFmtaiHMxCcwET8up7jjOSfS8QcOieQpaztrnsFvdDV/Rfq4lLutWJMENRhOs", - "Z0sOFNzqF8ziEDDjVnMW0Awh2i1mUiFmOmDWatd02GSTeLd/cNKx5U4UcKd730nvWwxxqlkVVfFPGiCP", - "TnsLCv4XVVFDDl5zm9jLU6I6wBrTJKS6FqzrBhRcTvdXyJBDwOjJxantuqrkMOT4OEPtfWdNyi03URhO", - "4xbrb8AVKPhTvu9DeVyGct6E9ETnT3N3I94xn1nrH8DWv0E7L813zOP4FgAA//8tucJ2/gIAAA==", -} - -// GetSwagger returns the content of the embedded swagger specification file -// or error if failed to decode -func decodeSpec() ([]byte, error) { - zipped, err := base64.StdEncoding.DecodeString(strings.Join(swaggerSpec, "")) - if err != nil { - return nil, fmt.Errorf("error base64 decoding spec: %w", err) - } - zr, err := gzip.NewReader(bytes.NewReader(zipped)) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - var buf bytes.Buffer - _, err = buf.ReadFrom(zr) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - - return buf.Bytes(), nil -} - -var rawSpec = decodeSpecCached() - -// a naive cached of a decoded swagger spec -func decodeSpecCached() func() ([]byte, error) { - data, err := decodeSpec() - return func() ([]byte, error) { - return data, err - } -} - -// Constructs a synthetic filesystem for resolving external references when loading openapi specifications. -func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { - res := make(map[string]func() ([]byte, error)) - if len(pathToFile) > 0 { - res[pathToFile] = rawSpec - } - - return res -} - -// GetSwagger returns the Swagger specification corresponding to the generated code -// in this file. The external references of Swagger specification are resolved. -// The logic of resolving external references is tightly connected to "import-mapping" feature. -// Externally referenced files must be embedded in the corresponding golang packages. -// Urls can be supported but this task was out of the scope. -func GetSwagger() (swagger *openapi3.T, err error) { - resolvePath := PathToRawSpec("") - - loader := openapi3.NewLoader() - loader.IsExternalRefsAllowed = true - loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() - pathToFile = path.Clean(pathToFile) - getSpec, ok := resolvePath[pathToFile] - if !ok { - err1 := fmt.Errorf("path not found: %s", pathToFile) - return nil, err1 - } - return getSpec() - } - var specData []byte - specData, err = rawSpec() - if err != nil { - return - } - swagger, err = loader.LoadFromData(specData) - if err != nil { - return - } - return -} diff --git a/internal/test/issues/issue-832/spec.yaml b/internal/test/issues/issue-832/spec.yaml deleted file mode 100644 index b000edde7e..0000000000 --- a/internal/test/issues/issue-832/spec.yaml +++ /dev/null @@ -1,43 +0,0 @@ -openapi: 3.0.2 -info: - version: '0.0.1' - title: example - description: | - Make sure that recursive types are handled properly -paths: - /example: - get: - operationId: exampleGet - responses: - '200': - description: "OK" - content: - 'application/json': - schema: - $ref: '#/components/schemas/Document' - /example2: - get: - operationId: exampleGet2 - responses: - '200': - description: "OK" - content: - 'application/json': - schema: - $ref: '#/components/schemas/DocumentStatus' -components: - schemas: - Document: - type: object - properties: - name: - type: string - status: - x-go-type-name: Document_Status - type: string - enum: [one, two, three, four] - DocumentStatus: - type: object - properties: - value: - type: string diff --git a/internal/test/issues/issue-936/gen.go b/internal/test/issues/issue-936/gen.go deleted file mode 100644 index f1e62f42f1..0000000000 --- a/internal/test/issues/issue-936/gen.go +++ /dev/null @@ -1,3 +0,0 @@ -package issue936 - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=server.config.yaml spec.yaml diff --git a/internal/test/issues/issue-936/server.config.yaml b/internal/test/issues/issue-936/server.config.yaml deleted file mode 100644 index 76b85471ab..0000000000 --- a/internal/test/issues/issue-936/server.config.yaml +++ /dev/null @@ -1,7 +0,0 @@ -# yaml-language-server: $schema=../../../../configuration-schema.json -package: issue936 -output: api.gen.go -generate: - models: true -compatibility: - circular-reference-limit: 4 diff --git a/internal/test/issues/issue-936/spec.yaml b/internal/test/issues/issue-936/spec.yaml deleted file mode 100644 index 8d9a7cf1d8..0000000000 --- a/internal/test/issues/issue-936/spec.yaml +++ /dev/null @@ -1,60 +0,0 @@ -# Via https://github.com/getkin/kin-openapi/blob/b31a4bb2dcd523b1477da8854f0f75859cd314b3/openapi3/testdata/recursiveRef/issue615.yml -openapi: "3.0.3" -info: - title: Deep recursive cyclic refs example - version: "1.0" -paths: - /foo: {} -components: - schemas: - FilterColumnIncludes: - type: object - properties: - $includes: - $ref: '#/components/schemas/FilterPredicate' - additionalProperties: false - maxProperties: 1 - minProperties: 1 - FilterPredicate: - oneOf: - - $ref: '#/components/schemas/FilterValue' - - type: array - items: - $ref: '#/components/schemas/FilterPredicate' - minLength: 1 - - $ref: '#/components/schemas/FilterPredicateOp' - - $ref: '#/components/schemas/FilterPredicateRangeOp' - FilterPredicateOp: - type: object - properties: - $any: - oneOf: - - type: array - items: - $ref: '#/components/schemas/FilterPredicate' - $none: - oneOf: - - $ref: '#/components/schemas/FilterPredicate' - - type: array - items: - $ref: '#/components/schemas/FilterPredicate' - additionalProperties: false - maxProperties: 1 - minProperties: 1 - FilterPredicateRangeOp: - type: object - properties: - $lt: - $ref: '#/components/schemas/FilterRangeValue' - additionalProperties: false - maxProperties: 2 - minProperties: 2 - FilterRangeValue: - oneOf: - - type: number - - type: string - FilterValue: - oneOf: - - type: number - - type: string - - type: boolean diff --git a/internal/test/issues/issue-grab_import_names/config.yaml b/internal/test/issues/issue-grab_import_names/config.yaml deleted file mode 100644 index 85e3f15e69..0000000000 --- a/internal/test/issues/issue-grab_import_names/config.yaml +++ /dev/null @@ -1,8 +0,0 @@ -# yaml-language-server: $schema=../../../../configuration-schema.json -package: grabimportnames -generate: - echo-server: true - client: true - models: true - embedded-spec: true -output: issue.gen.go diff --git a/internal/test/issues/issue-grab_import_names/doc.go b/internal/test/issues/issue-grab_import_names/doc.go deleted file mode 100644 index e986569fcb..0000000000 --- a/internal/test/issues/issue-grab_import_names/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -package grabimportnames - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml spec.yaml diff --git a/internal/test/issues/issue-grab_import_names/issue_test.go b/internal/test/issues/issue-grab_import_names/issue_test.go deleted file mode 100644 index 7d299fa22a..0000000000 --- a/internal/test/issues/issue-grab_import_names/issue_test.go +++ /dev/null @@ -1,28 +0,0 @@ -package grabimportnames - -import ( - "testing" - - "github.com/getkin/kin-openapi/openapi3" - "github.com/oapi-codegen/oapi-codegen/v2/pkg/codegen" - "github.com/stretchr/testify/require" -) - -func TestLineComments(t *testing.T) { - swagger, err := openapi3.NewLoader().LoadFromFile("spec.yaml") - require.NoError(t, err) - - opts := codegen.Configuration{ - PackageName: "grabimportnames", - Generate: codegen.GenerateOptions{ - EchoServer: true, - Client: true, - Models: true, - EmbeddedSpec: true, - }, - } - - code, err := codegen.Generate(swagger, opts) - require.NoError(t, err) - require.NotContains(t, code, `"openapi_types"`) -} diff --git a/internal/test/issues/issue-grab_import_names/spec.yaml b/internal/test/issues/issue-grab_import_names/spec.yaml deleted file mode 100644 index 902d7443e6..0000000000 --- a/internal/test/issues/issue-grab_import_names/spec.yaml +++ /dev/null @@ -1,30 +0,0 @@ -openapi: 3.0.2 - -info: - title: ... - version: 0.0.0 - -paths: - /foo: - get: - parameters: - - name: Foo - in: header - description: base64. bytes. chi. context. echo. errors. fmt. gzip. http. io. json. openapi3. - schema: - type: string - required: false - - name: Bar - in: header - description: openapi_types. path. runtime. strings. time.Duration time.Time url. xml. yaml. - schema: - type: string - required: false - description: ... - responses: - 200: - description: ... - content: - application/json: - schema: - type: string diff --git a/internal/test/issues/issue-head-digit-of-httpheader/config.yaml b/internal/test/issues/issue-head-digit-of-httpheader/config.yaml deleted file mode 100644 index 37457c892a..0000000000 --- a/internal/test/issues/issue-head-digit-of-httpheader/config.yaml +++ /dev/null @@ -1,8 +0,0 @@ ---- -# yaml-language-server: $schema=../../../../configuration-schema.json -package: headdigitofhttpheader -generate: - strict-server: true -output: issue.gen.go -output-options: - skip-prune: true diff --git a/internal/test/issues/issue-head-digit-of-httpheader/doc.go b/internal/test/issues/issue-head-digit-of-httpheader/doc.go deleted file mode 100644 index 63904053bf..0000000000 --- a/internal/test/issues/issue-head-digit-of-httpheader/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -package headdigitofhttpheader - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml spec.yaml diff --git a/internal/test/issues/issue-head-digit-of-httpheader/issue.gen.go b/internal/test/issues/issue-head-digit-of-httpheader/issue.gen.go deleted file mode 100644 index 6eadcef68e..0000000000 --- a/internal/test/issues/issue-head-digit-of-httpheader/issue.gen.go +++ /dev/null @@ -1,11 +0,0 @@ -// Package headdigitofhttpheader provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package headdigitofhttpheader - -type N200ResponseHeaders struct { - N000Foo string -} -type N200Response struct { - Headers N200ResponseHeaders -} diff --git a/internal/test/issues/issue-head-digit-of-httpheader/spec.yaml b/internal/test/issues/issue-head-digit-of-httpheader/spec.yaml deleted file mode 100644 index b6a960ac0c..0000000000 --- a/internal/test/issues/issue-head-digit-of-httpheader/spec.yaml +++ /dev/null @@ -1,16 +0,0 @@ -openapi: 3.0.2 -info: - version: "0.0.1" -paths: - /foo: - get: - responses: - 200: - $ref: "#/components/responses/200" -components: - responses: - "200": - headers: - "000-foo": - schema: - type: string diff --git a/internal/test/issues/issue-head-digit-of-operation-id/config.yaml b/internal/test/issues/issue-head-digit-of-operation-id/config.yaml deleted file mode 100644 index 9ac5a0a128..0000000000 --- a/internal/test/issues/issue-head-digit-of-operation-id/config.yaml +++ /dev/null @@ -1,8 +0,0 @@ ---- -# yaml-language-server: $schema=../../../../configuration-schema.json -package: head_digit_of_operation_id -generate: - strict-server: true -output: issue.gen.go -output-options: - skip-prune: true diff --git a/internal/test/issues/issue-head-digit-of-operation-id/doc.go b/internal/test/issues/issue-head-digit-of-operation-id/doc.go deleted file mode 100644 index fb08e63e86..0000000000 --- a/internal/test/issues/issue-head-digit-of-operation-id/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -package head_digit_of_operation_id - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml spec.yaml diff --git a/internal/test/issues/issue-head-digit-of-operation-id/issue.gen.go b/internal/test/issues/issue-head-digit-of-operation-id/issue.gen.go deleted file mode 100644 index 00c0844afc..0000000000 --- a/internal/test/issues/issue-head-digit-of-operation-id/issue.gen.go +++ /dev/null @@ -1,4 +0,0 @@ -// Package head_digit_of_operation_id provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package head_digit_of_operation_id diff --git a/internal/test/issues/issue-head-digit-of-operation-id/spec.yaml b/internal/test/issues/issue-head-digit-of-operation-id/spec.yaml deleted file mode 100644 index 59efb77502..0000000000 --- a/internal/test/issues/issue-head-digit-of-operation-id/spec.yaml +++ /dev/null @@ -1,7 +0,0 @@ -openapi: 3.0.2 -info: - version: "0.0.1" -paths: - /3gpp/foo: - get: - operationId: 3GPPFoo diff --git a/internal/test/issues/issue-illegal_enum_names/config.yaml b/internal/test/issues/issue-illegal_enum_names/config.yaml deleted file mode 100644 index e8bbe0e352..0000000000 --- a/internal/test/issues/issue-illegal_enum_names/config.yaml +++ /dev/null @@ -1,8 +0,0 @@ -# yaml-language-server: $schema=../../../../configuration-schema.json -package: illegalenumnames -generate: - echo-server: true - client: true - models: true - embedded-spec: true -output: issue.gen.go diff --git a/internal/test/issues/issue-illegal_enum_names/doc.go b/internal/test/issues/issue-illegal_enum_names/doc.go deleted file mode 100644 index d8fb076b49..0000000000 --- a/internal/test/issues/issue-illegal_enum_names/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -package illegalenumnames - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml spec.yaml diff --git a/internal/test/issues/issue-illegal_enum_names/issue.gen.go b/internal/test/issues/issue-illegal_enum_names/issue.gen.go deleted file mode 100644 index 0c29ab71eb..0000000000 --- a/internal/test/issues/issue-illegal_enum_names/issue.gen.go +++ /dev/null @@ -1,421 +0,0 @@ -// Package illegalenumnames provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package illegalenumnames - -import ( - "bytes" - "compress/gzip" - "context" - "encoding/base64" - "encoding/json" - "fmt" - "io" - "net/http" - "net/url" - "path" - "strings" - - "github.com/getkin/kin-openapi/openapi3" - "github.com/labstack/echo/v4" -) - -// Defines values for Bar. -const ( - BarBar Bar = "Bar" - BarEmpty Bar = "" - BarFoo Bar = "Foo" - BarFoo1 Bar = " Foo" - BarFoo2 Bar = " Foo " - BarFooBar Bar = "Foo Bar" - BarFooBar1 Bar = "Foo-Bar" - BarN1 Bar = "1" - BarN1Foo Bar = "1Foo" - BarUnderscoreFoo Bar = "_Foo_" -) - -// Valid indicates whether the value is a known member of the Bar enum. -func (e Bar) Valid() bool { - switch e { - case BarBar: - return true - case BarEmpty: - return true - case BarFoo: - return true - case BarFoo1: - return true - case BarFoo2: - return true - case BarFooBar: - return true - case BarFooBar1: - return true - case BarN1: - return true - case BarN1Foo: - return true - case BarUnderscoreFoo: - return true - default: - return false - } -} - -// Bar defines model for Bar. -type Bar string - -// RequestEditorFn is the function signature for the RequestEditor callback function -type RequestEditorFn func(ctx context.Context, req *http.Request) error - -// Doer performs HTTP requests. -// -// The standard http.Client implements this interface. -type HttpRequestDoer interface { - Do(req *http.Request) (*http.Response, error) -} - -// Client which conforms to the OpenAPI3 specification for this service. -type Client struct { - // The endpoint of the server conforming to this interface, with scheme, - // https://api.deepmap.com for example. This can contain a path relative - // to the server, such as https://api.deepmap.com/dev-test, and all the - // paths in the swagger spec will be appended to the server. - Server string - - // Doer for performing requests, typically a *http.Client with any - // customized settings, such as certificate chains. - Client HttpRequestDoer - - // A list of callbacks for modifying requests which are generated before sending over - // the network. - RequestEditors []RequestEditorFn -} - -// ClientOption allows setting custom parameters during construction -type ClientOption func(*Client) error - -// Creates a new Client, with reasonable defaults -func NewClient(server string, opts ...ClientOption) (*Client, error) { - // create a client with sane default values - client := Client{ - Server: server, - } - // mutate client and add all optional params - for _, o := range opts { - if err := o(&client); err != nil { - return nil, err - } - } - // ensure the server URL always has a trailing slash - if !strings.HasSuffix(client.Server, "/") { - client.Server += "/" - } - // create httpClient, if not already present - if client.Client == nil { - client.Client = &http.Client{} - } - return &client, nil -} - -// WithHTTPClient allows overriding the default Doer, which is -// automatically created using http.Client. This is useful for tests. -func WithHTTPClient(doer HttpRequestDoer) ClientOption { - return func(c *Client) error { - c.Client = doer - return nil - } -} - -// WithRequestEditorFn allows setting up a callback function, which will be -// called right before sending the request. This can be used to mutate the request. -func WithRequestEditorFn(fn RequestEditorFn) ClientOption { - return func(c *Client) error { - c.RequestEditors = append(c.RequestEditors, fn) - return nil - } -} - -// The interface specification for the client above. -type ClientInterface interface { - // GetFoo request - GetFoo(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) -} - -func (c *Client) GetFoo(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewGetFooRequest(c.Server) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -// NewGetFooRequest generates requests for GetFoo -func NewGetFooRequest(server string) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/foo") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -func (c *Client) applyEditors(ctx context.Context, req *http.Request, additionalEditors []RequestEditorFn) error { - for _, r := range c.RequestEditors { - if err := r(ctx, req); err != nil { - return err - } - } - for _, r := range additionalEditors { - if err := r(ctx, req); err != nil { - return err - } - } - return nil -} - -// ClientWithResponses builds on ClientInterface to offer response payloads -type ClientWithResponses struct { - ClientInterface -} - -// NewClientWithResponses creates a new ClientWithResponses, which wraps -// Client with return type handling -func NewClientWithResponses(server string, opts ...ClientOption) (*ClientWithResponses, error) { - client, err := NewClient(server, opts...) - if err != nil { - return nil, err - } - return &ClientWithResponses{client}, nil -} - -// WithBaseURL overrides the baseURL. -func WithBaseURL(baseURL string) ClientOption { - return func(c *Client) error { - newBaseURL, err := url.Parse(baseURL) - if err != nil { - return err - } - c.Server = newBaseURL.String() - return nil - } -} - -// ClientWithResponsesInterface is the interface specification for the client with responses above. -type ClientWithResponsesInterface interface { - // GetFooWithResponse request - GetFooWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*GetFooResponse, error) -} - -type GetFooResponse struct { - Body []byte - HTTPResponse *http.Response - JSON200 *[]Bar -} - -// Status returns HTTPResponse.Status -func (r GetFooResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r GetFooResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -// GetFooWithResponse request returning *GetFooResponse -func (c *ClientWithResponses) GetFooWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*GetFooResponse, error) { - rsp, err := c.GetFoo(ctx, reqEditors...) - if err != nil { - return nil, err - } - return ParseGetFooResponse(rsp) -} - -// ParseGetFooResponse parses an HTTP response from a GetFooWithResponse call -func ParseGetFooResponse(rsp *http.Response) (*GetFooResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &GetFooResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest []Bar - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON200 = &dest - - } - - return response, nil -} - -// ServerInterface represents all server handlers. -type ServerInterface interface { - - // (GET /foo) - GetFoo(ctx echo.Context) error -} - -// ServerInterfaceWrapper converts echo contexts to parameters. -type ServerInterfaceWrapper struct { - Handler ServerInterface -} - -// GetFoo converts echo context to params. -func (w *ServerInterfaceWrapper) GetFoo(ctx echo.Context) error { - var err error - - // Invoke the callback with all the unmarshaled arguments - err = w.Handler.GetFoo(ctx) - return err -} - -// This is a simple interface which specifies echo.Route addition functions which -// are present on both echo.Echo and echo.Group, since we want to allow using -// either of them for path registration -type EchoRouter interface { - CONNECT(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - DELETE(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - GET(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - HEAD(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - OPTIONS(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - PATCH(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - POST(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - PUT(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - TRACE(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route -} - -// RegisterHandlers adds each server route to the EchoRouter. -func RegisterHandlers(router EchoRouter, si ServerInterface) { - RegisterHandlersWithBaseURL(router, si, "") -} - -// Registers handlers, and prepends BaseURL to the paths, so that the paths -// can be served under a prefix. -func RegisterHandlersWithBaseURL(router EchoRouter, si ServerInterface, baseURL string) { - - wrapper := ServerInterfaceWrapper{ - Handler: si, - } - - router.GET(baseURL+"/foo", wrapper.GetFoo) - -} - -// Base64 encoded, gzipped, json marshaled Swagger object -var swaggerSpec = []string{ - - "H4sIAAAAAAAC/0xQQU4DMQz8SjVwDNml3HLkUMQbEKqirbcN6tpRYpCqKn9HzkIhl5kkHtszV0yyZGFi", - "rQhX1OlES+z0ORYD4s8F4Q1w2InA9ffONzf2sLLH/wWb9WKwgcN+J7K3Grw76CUTAqqWxEe01hwSz2Lj", - "NOnZ/rz3cPiiUpMwAkY/+hHNQTJxzAkBT370WzjkqKe+8TBL73EkNZBMJWoSfj0g4IV03ahQzcKVumQ7", - "jgaTsBJ3Vcz5nKauGz6qzf5NxVhSWrrwvtCMgLvhL7/hJ7zBAmg3l7GUeFlNHqhOJWVdLZnF1s93AAAA", - "//9U8KAOhgEAAA==", -} - -// GetSwagger returns the content of the embedded swagger specification file -// or error if failed to decode -func decodeSpec() ([]byte, error) { - zipped, err := base64.StdEncoding.DecodeString(strings.Join(swaggerSpec, "")) - if err != nil { - return nil, fmt.Errorf("error base64 decoding spec: %w", err) - } - zr, err := gzip.NewReader(bytes.NewReader(zipped)) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - var buf bytes.Buffer - _, err = buf.ReadFrom(zr) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - - return buf.Bytes(), nil -} - -var rawSpec = decodeSpecCached() - -// a naive cached of a decoded swagger spec -func decodeSpecCached() func() ([]byte, error) { - data, err := decodeSpec() - return func() ([]byte, error) { - return data, err - } -} - -// Constructs a synthetic filesystem for resolving external references when loading openapi specifications. -func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { - res := make(map[string]func() ([]byte, error)) - if len(pathToFile) > 0 { - res[pathToFile] = rawSpec - } - - return res -} - -// GetSwagger returns the Swagger specification corresponding to the generated code -// in this file. The external references of Swagger specification are resolved. -// The logic of resolving external references is tightly connected to "import-mapping" feature. -// Externally referenced files must be embedded in the corresponding golang packages. -// Urls can be supported but this task was out of the scope. -func GetSwagger() (swagger *openapi3.T, err error) { - resolvePath := PathToRawSpec("") - - loader := openapi3.NewLoader() - loader.IsExternalRefsAllowed = true - loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() - pathToFile = path.Clean(pathToFile) - getSpec, ok := resolvePath[pathToFile] - if !ok { - err1 := fmt.Errorf("path not found: %s", pathToFile) - return nil, err1 - } - return getSpec() - } - var specData []byte - specData, err = rawSpec() - if err != nil { - return - } - swagger, err = loader.LoadFromData(specData) - if err != nil { - return - } - return -} diff --git a/internal/test/issues/issue-illegal_enum_names/issue_test.go b/internal/test/issues/issue-illegal_enum_names/issue_test.go deleted file mode 100644 index 77d4eb416c..0000000000 --- a/internal/test/issues/issue-illegal_enum_names/issue_test.go +++ /dev/null @@ -1,59 +0,0 @@ -package illegalenumnames - -import ( - "go/ast" - "go/parser" - "go/token" - "testing" - - "github.com/getkin/kin-openapi/openapi3" - "github.com/oapi-codegen/oapi-codegen/v2/pkg/codegen" - "github.com/stretchr/testify/require" -) - -func TestIllegalEnumNames(t *testing.T) { - swagger, err := openapi3.NewLoader().LoadFromFile("spec.yaml") - require.NoError(t, err) - - opts := codegen.Configuration{ - PackageName: "illegalenumnames", - Generate: codegen.GenerateOptions{ - EchoServer: true, - Client: true, - Models: true, - EmbeddedSpec: true, - }, - } - - code, err := codegen.Generate(swagger, opts) - require.NoError(t, err) - - f, err := parser.ParseFile(token.NewFileSet(), "", code, parser.AllErrors) - require.NoError(t, err) - - constDefs := make(map[string]string) - for _, d := range f.Decls { - switch decl := d.(type) { - case *ast.GenDecl: - if token.CONST == decl.Tok { - for _, s := range decl.Specs { - switch spec := s.(type) { - case *ast.ValueSpec: - constDefs[spec.Names[0].Name] = spec.Names[0].Obj.Decl.(*ast.ValueSpec).Values[0].(*ast.BasicLit).Value - } - } - } - } - } - - require.Equal(t, `""`, constDefs["BarEmpty"]) - require.Equal(t, `"Bar"`, constDefs["BarBar"]) - require.Equal(t, `"Foo"`, constDefs["BarFoo"]) - require.Equal(t, `"Foo Bar"`, constDefs["BarFooBar"]) - require.Equal(t, `"Foo-Bar"`, constDefs["BarFooBar1"]) - require.Equal(t, `"1Foo"`, constDefs["BarN1Foo"]) - require.Equal(t, `" Foo"`, constDefs["BarFoo1"]) - require.Equal(t, `" Foo "`, constDefs["BarFoo2"]) - require.Equal(t, `"_Foo_"`, constDefs["BarUnderscoreFoo"]) - require.Equal(t, `"1"`, constDefs["BarN1"]) -} diff --git a/internal/test/issues/issue-illegal_enum_names/spec.yaml b/internal/test/issues/issue-illegal_enum_names/spec.yaml deleted file mode 100644 index d222a57e72..0000000000 --- a/internal/test/issues/issue-illegal_enum_names/spec.yaml +++ /dev/null @@ -1,35 +0,0 @@ -openapi: 3.0.2 - -info: - title: ... - version: 0.0.0 - -paths: - /foo: - get: - responses: - 200: - description: ... - content: - application/json: - schema: - type: array - items: - $ref: '#/components/schemas/Bar' - -components: - schemas: - Bar: - type: string - enum: - - '' - - Foo - - Bar - - Foo Bar - - Foo-Bar - - 1Foo - - Bar # A swagger validator would catch this duplicate value - - ' Foo' - - ' Foo ' - - _Foo_ - - "1" diff --git a/internal/test/issues/issue-removed-external-ref/config.base.yaml b/internal/test/issues/issue-removed-external-ref/config.base.yaml deleted file mode 100644 index 14faed834b..0000000000 --- a/internal/test/issues/issue-removed-external-ref/config.base.yaml +++ /dev/null @@ -1,13 +0,0 @@ ---- -# yaml-language-server: $schema=../../../../configuration-schema.json -package: spec_base -generate: - chi-server: true - strict-server: true - models: true -import-mapping: - spec-ext.yaml: "github.com/oapi-codegen/oapi-codegen/v2/internal/test/issues/issue-removed-external-ref/gen/spec_ext" -output: gen/spec_base/issue.gen.go -output-options: - skip-prune: true - # skip-fmt: true diff --git a/internal/test/issues/issue-removed-external-ref/config.ext.yaml b/internal/test/issues/issue-removed-external-ref/config.ext.yaml deleted file mode 100644 index efb166ed2f..0000000000 --- a/internal/test/issues/issue-removed-external-ref/config.ext.yaml +++ /dev/null @@ -1,11 +0,0 @@ ---- -# yaml-language-server: $schema=../../../../configuration-schema.json -package: spec_ext -generate: - chi-server: true - strict-server: true - models: true -output: gen/spec_ext/issue.gen.go -output-options: - skip-prune: true - # skip-fmt: true diff --git a/internal/test/issues/issue-removed-external-ref/doc.go b/internal/test/issues/issue-removed-external-ref/doc.go deleted file mode 100644 index 6af4d981ff..0000000000 --- a/internal/test/issues/issue-removed-external-ref/doc.go +++ /dev/null @@ -1,4 +0,0 @@ -package head_digit_of_httpheader - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.ext.yaml spec-ext.yaml -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.base.yaml spec-base.yaml diff --git a/internal/test/issues/issue-removed-external-ref/gen/spec_base/.gitempty b/internal/test/issues/issue-removed-external-ref/gen/spec_base/.gitempty deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/internal/test/issues/issue-removed-external-ref/gen/spec_base/issue.gen.go b/internal/test/issues/issue-removed-external-ref/gen/spec_base/issue.gen.go deleted file mode 100644 index 1a1c761002..0000000000 --- a/internal/test/issues/issue-removed-external-ref/gen/spec_base/issue.gen.go +++ /dev/null @@ -1,333 +0,0 @@ -// Package spec_base provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package spec_base - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - - "github.com/go-chi/chi/v5" - externalRef0 "github.com/oapi-codegen/oapi-codegen/v2/internal/test/issues/issue-removed-external-ref/gen/spec_ext" - strictnethttp "github.com/oapi-codegen/runtime/strictmiddleware/nethttp" -) - -// DirectBar defines model for DirectBar. -type DirectBar = externalRef0.Foo - -// PackedBar defines model for PackedBar. -type PackedBar struct { - Core *externalRef0.Foo `json:"core,omitempty"` - Directd *DirectBar `json:"directd,omitempty"` - Id *string `json:"id,omitempty"` -} - -// ServerInterface represents all server handlers. -type ServerInterface interface { - - // (POST /invalidExtRefTrouble) - PostInvalidExtRefTrouble(w http.ResponseWriter, r *http.Request) - - // (POST /noTrouble) - PostNoTrouble(w http.ResponseWriter, r *http.Request) -} - -// Unimplemented server implementation that returns http.StatusNotImplemented for each endpoint. - -type Unimplemented struct{} - -// (POST /invalidExtRefTrouble) -func (_ Unimplemented) PostInvalidExtRefTrouble(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusNotImplemented) -} - -// (POST /noTrouble) -func (_ Unimplemented) PostNoTrouble(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusNotImplemented) -} - -// ServerInterfaceWrapper converts contexts to parameters. -type ServerInterfaceWrapper struct { - Handler ServerInterface - HandlerMiddlewares []MiddlewareFunc - ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) -} - -type MiddlewareFunc func(http.Handler) http.Handler - -// PostInvalidExtRefTrouble operation middleware -func (siw *ServerInterfaceWrapper) PostInvalidExtRefTrouble(w http.ResponseWriter, r *http.Request) { - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.PostInvalidExtRefTrouble(w, r) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -// PostNoTrouble operation middleware -func (siw *ServerInterfaceWrapper) PostNoTrouble(w http.ResponseWriter, r *http.Request) { - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.PostNoTrouble(w, r) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -type UnescapedCookieParamError struct { - ParamName string - Err error -} - -func (e *UnescapedCookieParamError) Error() string { - return fmt.Sprintf("error unescaping cookie parameter '%s'", e.ParamName) -} - -func (e *UnescapedCookieParamError) Unwrap() error { - return e.Err -} - -type UnmarshalingParamError struct { - ParamName string - Err error -} - -func (e *UnmarshalingParamError) Error() string { - return fmt.Sprintf("Error unmarshaling parameter %s as JSON: %s", e.ParamName, e.Err.Error()) -} - -func (e *UnmarshalingParamError) Unwrap() error { - return e.Err -} - -type RequiredParamError struct { - ParamName string -} - -func (e *RequiredParamError) Error() string { - return fmt.Sprintf("Query argument %s is required, but not found", e.ParamName) -} - -type RequiredHeaderError struct { - ParamName string - Err error -} - -func (e *RequiredHeaderError) Error() string { - return fmt.Sprintf("Header parameter %s is required, but not found", e.ParamName) -} - -func (e *RequiredHeaderError) Unwrap() error { - return e.Err -} - -type InvalidParamFormatError struct { - ParamName string - Err error -} - -func (e *InvalidParamFormatError) Error() string { - return fmt.Sprintf("Invalid format for parameter %s: %s", e.ParamName, e.Err.Error()) -} - -func (e *InvalidParamFormatError) Unwrap() error { - return e.Err -} - -type TooManyValuesForParamError struct { - ParamName string - Count int -} - -func (e *TooManyValuesForParamError) Error() string { - return fmt.Sprintf("Expected one value for %s, got %d", e.ParamName, e.Count) -} - -// Handler creates http.Handler with routing matching OpenAPI spec. -func Handler(si ServerInterface) http.Handler { - return HandlerWithOptions(si, ChiServerOptions{}) -} - -type ChiServerOptions struct { - BaseURL string - BaseRouter chi.Router - Middlewares []MiddlewareFunc - ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) -} - -// HandlerFromMux creates http.Handler with routing matching OpenAPI spec based on the provided mux. -func HandlerFromMux(si ServerInterface, r chi.Router) http.Handler { - return HandlerWithOptions(si, ChiServerOptions{ - BaseRouter: r, - }) -} - -func HandlerFromMuxWithBaseURL(si ServerInterface, r chi.Router, baseURL string) http.Handler { - return HandlerWithOptions(si, ChiServerOptions{ - BaseURL: baseURL, - BaseRouter: r, - }) -} - -// HandlerWithOptions creates http.Handler with additional options -func HandlerWithOptions(si ServerInterface, options ChiServerOptions) http.Handler { - r := options.BaseRouter - - if r == nil { - r = chi.NewRouter() - } - if options.ErrorHandlerFunc == nil { - options.ErrorHandlerFunc = func(w http.ResponseWriter, r *http.Request, err error) { - http.Error(w, err.Error(), http.StatusBadRequest) - } - } - wrapper := ServerInterfaceWrapper{ - Handler: si, - HandlerMiddlewares: options.Middlewares, - ErrorHandlerFunc: options.ErrorHandlerFunc, - } - - r.Group(func(r chi.Router) { - r.Post(options.BaseURL+"/invalidExtRefTrouble", wrapper.PostInvalidExtRefTrouble) - }) - r.Group(func(r chi.Router) { - r.Post(options.BaseURL+"/noTrouble", wrapper.PostNoTrouble) - }) - - return r -} - -type PostInvalidExtRefTroubleRequestObject struct { -} - -type PostInvalidExtRefTroubleResponseObject interface { - VisitPostInvalidExtRefTroubleResponse(w http.ResponseWriter) error -} - -type PostInvalidExtRefTrouble300JSONResponse struct{ externalRef0.Pascal } - -func (response PostInvalidExtRefTrouble300JSONResponse) VisitPostInvalidExtRefTroubleResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(300) - - return json.NewEncoder(w).Encode(response) -} - -type PostNoTroubleRequestObject struct { -} - -type PostNoTroubleResponseObject interface { - VisitPostNoTroubleResponse(w http.ResponseWriter) error -} - -type PostNoTrouble200JSONResponse struct { - DirectBar *DirectBar `json:"directBar,omitempty"` - DirectFoo *externalRef0.Foo `json:"directFoo,omitempty"` - IndirectFoo *PackedBar `json:"indirectFoo,omitempty"` - Name *string `json:"name,omitempty"` -} - -func (response PostNoTrouble200JSONResponse) VisitPostNoTroubleResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(200) - - return json.NewEncoder(w).Encode(response) -} - -// StrictServerInterface represents all server handlers. -type StrictServerInterface interface { - - // (POST /invalidExtRefTrouble) - PostInvalidExtRefTrouble(ctx context.Context, request PostInvalidExtRefTroubleRequestObject) (PostInvalidExtRefTroubleResponseObject, error) - - // (POST /noTrouble) - PostNoTrouble(ctx context.Context, request PostNoTroubleRequestObject) (PostNoTroubleResponseObject, error) -} - -type StrictHandlerFunc = strictnethttp.StrictHTTPHandlerFunc -type StrictMiddlewareFunc = strictnethttp.StrictHTTPMiddlewareFunc - -type StrictHTTPServerOptions struct { - RequestErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) - ResponseErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) -} - -func NewStrictHandler(ssi StrictServerInterface, middlewares []StrictMiddlewareFunc) ServerInterface { - return &strictHandler{ssi: ssi, middlewares: middlewares, options: StrictHTTPServerOptions{ - RequestErrorHandlerFunc: func(w http.ResponseWriter, r *http.Request, err error) { - http.Error(w, err.Error(), http.StatusBadRequest) - }, - ResponseErrorHandlerFunc: func(w http.ResponseWriter, r *http.Request, err error) { - http.Error(w, err.Error(), http.StatusInternalServerError) - }, - }} -} - -func NewStrictHandlerWithOptions(ssi StrictServerInterface, middlewares []StrictMiddlewareFunc, options StrictHTTPServerOptions) ServerInterface { - return &strictHandler{ssi: ssi, middlewares: middlewares, options: options} -} - -type strictHandler struct { - ssi StrictServerInterface - middlewares []StrictMiddlewareFunc - options StrictHTTPServerOptions -} - -// PostInvalidExtRefTrouble operation middleware -func (sh *strictHandler) PostInvalidExtRefTrouble(w http.ResponseWriter, r *http.Request) { - var request PostInvalidExtRefTroubleRequestObject - - handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { - return sh.ssi.PostInvalidExtRefTrouble(ctx, request.(PostInvalidExtRefTroubleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "PostInvalidExtRefTrouble") - } - - response, err := handler(r.Context(), w, r, request) - - if err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } else if validResponse, ok := response.(PostInvalidExtRefTroubleResponseObject); ok { - if err := validResponse.VisitPostInvalidExtRefTroubleResponse(w); err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } - } else if response != nil { - sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) - } -} - -// PostNoTrouble operation middleware -func (sh *strictHandler) PostNoTrouble(w http.ResponseWriter, r *http.Request) { - var request PostNoTroubleRequestObject - - handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { - return sh.ssi.PostNoTrouble(ctx, request.(PostNoTroubleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "PostNoTrouble") - } - - response, err := handler(r.Context(), w, r, request) - - if err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } else if validResponse, ok := response.(PostNoTroubleResponseObject); ok { - if err := validResponse.VisitPostNoTroubleResponse(w); err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } - } else if response != nil { - sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) - } -} diff --git a/internal/test/issues/issue-removed-external-ref/gen/spec_ext/.gitempty b/internal/test/issues/issue-removed-external-ref/gen/spec_ext/.gitempty deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/internal/test/issues/issue-removed-external-ref/gen/spec_ext/issue.gen.go b/internal/test/issues/issue-removed-external-ref/gen/spec_ext/issue.gen.go deleted file mode 100644 index 881f8be12b..0000000000 --- a/internal/test/issues/issue-removed-external-ref/gen/spec_ext/issue.gen.go +++ /dev/null @@ -1,195 +0,0 @@ -// Package spec_ext provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package spec_ext - -import ( - "fmt" - "net/http" - - "github.com/go-chi/chi/v5" - strictnethttp "github.com/oapi-codegen/runtime/strictmiddleware/nethttp" -) - -// CamelSchema defines model for CamelSchema. -type CamelSchema struct { - Id *string `json:"id,omitempty"` -} - -// Foo defines model for Foo. -type Foo struct { - CamelSchema *CamelSchema `json:"CamelSchema,omitempty"` - InternalAttr *string `json:"internalAttr,omitempty"` - PascalSchema *PascalSchema `json:"pascalSchema,omitempty"` -} - -// PascalSchema defines model for pascalSchema. -type PascalSchema struct { - Id *string `json:"id,omitempty"` -} - -// Pascal defines model for pascal. -type Pascal = PascalSchema - -// ServerInterface represents all server handlers. -type ServerInterface interface { -} - -// Unimplemented server implementation that returns http.StatusNotImplemented for each endpoint. - -type Unimplemented struct{} - -// ServerInterfaceWrapper converts contexts to parameters. -type ServerInterfaceWrapper struct { - Handler ServerInterface - HandlerMiddlewares []MiddlewareFunc - ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) -} - -type MiddlewareFunc func(http.Handler) http.Handler - -type UnescapedCookieParamError struct { - ParamName string - Err error -} - -func (e *UnescapedCookieParamError) Error() string { - return fmt.Sprintf("error unescaping cookie parameter '%s'", e.ParamName) -} - -func (e *UnescapedCookieParamError) Unwrap() error { - return e.Err -} - -type UnmarshalingParamError struct { - ParamName string - Err error -} - -func (e *UnmarshalingParamError) Error() string { - return fmt.Sprintf("Error unmarshaling parameter %s as JSON: %s", e.ParamName, e.Err.Error()) -} - -func (e *UnmarshalingParamError) Unwrap() error { - return e.Err -} - -type RequiredParamError struct { - ParamName string -} - -func (e *RequiredParamError) Error() string { - return fmt.Sprintf("Query argument %s is required, but not found", e.ParamName) -} - -type RequiredHeaderError struct { - ParamName string - Err error -} - -func (e *RequiredHeaderError) Error() string { - return fmt.Sprintf("Header parameter %s is required, but not found", e.ParamName) -} - -func (e *RequiredHeaderError) Unwrap() error { - return e.Err -} - -type InvalidParamFormatError struct { - ParamName string - Err error -} - -func (e *InvalidParamFormatError) Error() string { - return fmt.Sprintf("Invalid format for parameter %s: %s", e.ParamName, e.Err.Error()) -} - -func (e *InvalidParamFormatError) Unwrap() error { - return e.Err -} - -type TooManyValuesForParamError struct { - ParamName string - Count int -} - -func (e *TooManyValuesForParamError) Error() string { - return fmt.Sprintf("Expected one value for %s, got %d", e.ParamName, e.Count) -} - -// Handler creates http.Handler with routing matching OpenAPI spec. -func Handler(si ServerInterface) http.Handler { - return HandlerWithOptions(si, ChiServerOptions{}) -} - -type ChiServerOptions struct { - BaseURL string - BaseRouter chi.Router - Middlewares []MiddlewareFunc - ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) -} - -// HandlerFromMux creates http.Handler with routing matching OpenAPI spec based on the provided mux. -func HandlerFromMux(si ServerInterface, r chi.Router) http.Handler { - return HandlerWithOptions(si, ChiServerOptions{ - BaseRouter: r, - }) -} - -func HandlerFromMuxWithBaseURL(si ServerInterface, r chi.Router, baseURL string) http.Handler { - return HandlerWithOptions(si, ChiServerOptions{ - BaseURL: baseURL, - BaseRouter: r, - }) -} - -// HandlerWithOptions creates http.Handler with additional options -func HandlerWithOptions(si ServerInterface, options ChiServerOptions) http.Handler { - r := options.BaseRouter - - if r == nil { - r = chi.NewRouter() - } - if options.ErrorHandlerFunc == nil { - options.ErrorHandlerFunc = func(w http.ResponseWriter, r *http.Request, err error) { - http.Error(w, err.Error(), http.StatusBadRequest) - } - } - - return r -} - -type PascalJSONResponse PascalSchema - -// StrictServerInterface represents all server handlers. -type StrictServerInterface interface { -} - -type StrictHandlerFunc = strictnethttp.StrictHTTPHandlerFunc -type StrictMiddlewareFunc = strictnethttp.StrictHTTPMiddlewareFunc - -type StrictHTTPServerOptions struct { - RequestErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) - ResponseErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) -} - -func NewStrictHandler(ssi StrictServerInterface, middlewares []StrictMiddlewareFunc) ServerInterface { - return &strictHandler{ssi: ssi, middlewares: middlewares, options: StrictHTTPServerOptions{ - RequestErrorHandlerFunc: func(w http.ResponseWriter, r *http.Request, err error) { - http.Error(w, err.Error(), http.StatusBadRequest) - }, - ResponseErrorHandlerFunc: func(w http.ResponseWriter, r *http.Request, err error) { - http.Error(w, err.Error(), http.StatusInternalServerError) - }, - }} -} - -func NewStrictHandlerWithOptions(ssi StrictServerInterface, middlewares []StrictMiddlewareFunc, options StrictHTTPServerOptions) ServerInterface { - return &strictHandler{ssi: ssi, middlewares: middlewares, options: options} -} - -type strictHandler struct { - ssi StrictServerInterface - middlewares []StrictMiddlewareFunc - options StrictHTTPServerOptions -} diff --git a/internal/test/issues/issue-removed-external-ref/spec-base.yaml b/internal/test/issues/issue-removed-external-ref/spec-base.yaml deleted file mode 100644 index 36f285cc30..0000000000 --- a/internal/test/issues/issue-removed-external-ref/spec-base.yaml +++ /dev/null @@ -1,41 +0,0 @@ -eopenapi: 3.0.2 -info: - version: "0.0.1" -paths: - /noTrouble: - post: - responses: - 200: - description: ... - content: - application/json: - schema: - type: object - properties: - directFoo: - $ref: "spec-ext.yaml#/components/schemas/Foo" - directBar: - $ref: "#/components/schemas/DirectBar" - indirectFoo: - $ref: "#/components/schemas/PackedBar" - name: - type: string - /invalidExtRefTrouble: - post: - responses: - 300: - $ref: "spec-ext.yaml#/components/responses/pascal" - -components: - schemas: - DirectBar: - $ref: "spec-ext.yaml#/components/schemas/Foo" - PackedBar: - type: object - properties: - id: - type: string - core: - $ref: "spec-ext.yaml#/components/schemas/Foo" - directd: - $ref: "#/components/schemas/DirectBar" diff --git a/internal/test/issues/issue-removed-external-ref/spec-ext.yaml b/internal/test/issues/issue-removed-external-ref/spec-ext.yaml deleted file mode 100644 index 4fd3b4ed34..0000000000 --- a/internal/test/issues/issue-removed-external-ref/spec-ext.yaml +++ /dev/null @@ -1,30 +0,0 @@ -openapi: 3.0.2 -info: - version: "0.0.1" -components: - schemas: - CamelSchema: - type: object - properties: - id: - type: string - pascalSchema: - type: object - properties: - id: - type: string - Foo: - type: object - properties: - internalAttr: - type: string - CamelSchema: - $ref: "#/components/schemas/CamelSchema" - pascalSchema: - $ref: "#/components/schemas/pascalSchema" - responses: - "pascal": - content: - application/json: - schema: - $ref: "#/components/schemas/pascalSchema" diff --git a/internal/test/issues/issue1469/config.yaml b/internal/test/issues/issue1469/config.yaml deleted file mode 100644 index 0995b5f9fc..0000000000 --- a/internal/test/issues/issue1469/config.yaml +++ /dev/null @@ -1,5 +0,0 @@ -# yaml-language-server: $schema=../../../../configuration-schema.json -package: issue1469 -generate: - fiber-server: true -output: main.gen.go diff --git a/internal/test/issues/issue1469/doc.go b/internal/test/issues/issue1469/doc.go deleted file mode 100644 index d72f419f61..0000000000 --- a/internal/test/issues/issue1469/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -package issue1469 - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml spec.yaml diff --git a/internal/test/issues/issue1469/main.gen.go b/internal/test/issues/issue1469/main.gen.go deleted file mode 100644 index 11f87b0c4f..0000000000 --- a/internal/test/issues/issue1469/main.gen.go +++ /dev/null @@ -1,53 +0,0 @@ -// Package issue1469 provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package issue1469 - -import ( - "github.com/gofiber/fiber/v2" -) - -// ServerInterface represents all server handlers. -type ServerInterface interface { - - // (GET /test) - Test(c *fiber.Ctx) error -} - -// ServerInterfaceWrapper converts contexts to parameters. -type ServerInterfaceWrapper struct { - Handler ServerInterface -} - -type MiddlewareFunc fiber.Handler - -// Test operation middleware -func (siw *ServerInterfaceWrapper) Test(c *fiber.Ctx) error { - - return siw.Handler.Test(c) -} - -// FiberServerOptions provides options for the Fiber server. -type FiberServerOptions struct { - BaseURL string - Middlewares []MiddlewareFunc -} - -// RegisterHandlers creates http.Handler with routing matching OpenAPI spec. -func RegisterHandlers(router fiber.Router, si ServerInterface) { - RegisterHandlersWithOptions(router, si, FiberServerOptions{}) -} - -// RegisterHandlersWithOptions creates http.Handler with additional options -func RegisterHandlersWithOptions(router fiber.Router, si ServerInterface, options FiberServerOptions) { - wrapper := ServerInterfaceWrapper{ - Handler: si, - } - - for _, m := range options.Middlewares { - router.Use(fiber.Handler(m)) - } - - router.Get(options.BaseURL+"/test", wrapper.Test) - -} diff --git a/internal/test/issues/issue1469/main_test.go b/internal/test/issues/issue1469/main_test.go deleted file mode 100644 index 3af67244a9..0000000000 --- a/internal/test/issues/issue1469/main_test.go +++ /dev/null @@ -1,35 +0,0 @@ -package issue1469 - -import ( - "testing" - - "github.com/gofiber/fiber/v2" - "github.com/stretchr/testify/assert" -) - -type impl struct{} - -// (GET /test) -func (i *impl) Test(c *fiber.Ctx) error { - panic("not implemented") // TODO: Implement -} - -func TestIssue1469(t *testing.T) { - server := &impl{} - - r := fiber.New() - - assert.NotPanics(t, func() { - RegisterHandlers(r, server) - }) - - assert.NotPanics(t, func() { - RegisterHandlersWithOptions(r, server, FiberServerOptions{ - Middlewares: []MiddlewareFunc{ - func(c *fiber.Ctx) error { - return nil - }, - }, - }) - }) -} diff --git a/internal/test/issues/issue1469/spec.yaml b/internal/test/issues/issue1469/spec.yaml deleted file mode 100644 index 69a8a3e280..0000000000 --- a/internal/test/issues/issue1469/spec.yaml +++ /dev/null @@ -1,13 +0,0 @@ -openapi: "3.0.1" -paths: - /test: - get: - operationId: test - requestBody: - content: - application/json: - schema: - type: object - responses: - 200: - description: good diff --git a/internal/test/issues/issue1561/config.yaml b/internal/test/issues/issue1561/config.yaml deleted file mode 100644 index e1df8f3b7e..0000000000 --- a/internal/test/issues/issue1561/config.yaml +++ /dev/null @@ -1,8 +0,0 @@ -# yaml-language-server: $schema=../../../../configuration-schema.json -package: issue1561 -generate: - models: true -output: issue1561.gen.go -output-options: - skip-prune: true - prefer-skip-optional-pointer-on-container-types: true diff --git a/internal/test/issues/issue1561/generate.go b/internal/test/issues/issue1561/generate.go deleted file mode 100644 index 21cf1d305d..0000000000 --- a/internal/test/issues/issue1561/generate.go +++ /dev/null @@ -1,3 +0,0 @@ -package issue1561 - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml openapi.yaml diff --git a/internal/test/issues/issue1561/issue1561.gen.go b/internal/test/issues/issue1561/issue1561.gen.go deleted file mode 100644 index f011e318c1..0000000000 --- a/internal/test/issues/issue1561/issue1561.gen.go +++ /dev/null @@ -1,21 +0,0 @@ -// Package issue1561 provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package issue1561 - -// Pong defines model for Pong. -type Pong struct { - Ping string `json:"ping"` -} - -// ResponseBody defines model for ResponseBody. -type ResponseBody struct { - AMap map[string]Pong `json:"a_map,omitempty"` - ASlice []Pong `json:"a_slice,omitempty"` - ASliceWithAdditionalProps []map[string]Pong `json:"a_slice_with_additional_props,omitempty"` - AdditionalProps map[string]Pong `json:"additional_props,omitempty"` - Bytes []byte `json:"bytes,omitempty"` - BytesWithOverride *[]byte `json:"bytes_with_override,omitempty"` - RequiredSlice []Pong `json:"required_slice"` - UnknownObject map[string]interface{} `json:"unknown_object,omitempty"` -} diff --git a/internal/test/issues/issue1561/issue1561_test.go b/internal/test/issues/issue1561/issue1561_test.go deleted file mode 100644 index 0873793feb..0000000000 --- a/internal/test/issues/issue1561/issue1561_test.go +++ /dev/null @@ -1,64 +0,0 @@ -package issue1561 - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestResponseBody_DoesNotHaveOptionalPointerToContainerTypes(t *testing.T) { - pong0 := Pong{ - Ping: "0th", - } - - pong1 := Pong{ - Ping: "1th", - } - - slice := []Pong{ - pong0, - pong1, - } - - m := map[string]Pong{ - "0": pong0, - "1": pong1, - } - - byteData := []byte("some bytes") - - body := ResponseBody{ - RequiredSlice: slice, - ASlice: slice, - AMap: m, - UnknownObject: map[string]any{}, - AdditionalProps: m, - ASliceWithAdditionalProps: []map[string]Pong{m}, - Bytes: byteData, - BytesWithOverride: &byteData, - } - - assert.NotNil(t, body.RequiredSlice) - assert.NotZero(t, body.RequiredSlice) - - assert.NotNil(t, body.ASlice) - assert.NotZero(t, body.ASlice) - - assert.NotNil(t, body.AMap) - assert.NotZero(t, body.AMap) - - assert.NotNil(t, body.UnknownObject) - assert.Empty(t, body.UnknownObject) - - assert.NotNil(t, body.AdditionalProps) - assert.NotZero(t, body.AdditionalProps) - - assert.NotNil(t, body.ASliceWithAdditionalProps) - assert.NotZero(t, body.ASliceWithAdditionalProps) - - assert.NotNil(t, body.Bytes) - assert.NotZero(t, body.Bytes) - - assert.NotNil(t, body.BytesWithOverride) - assert.NotZero(t, body.BytesWithOverride) -} diff --git a/internal/test/issues/issue1561/openapi.yaml b/internal/test/issues/issue1561/openapi.yaml deleted file mode 100644 index 4e5cf771c0..0000000000 --- a/internal/test/issues/issue1561/openapi.yaml +++ /dev/null @@ -1,49 +0,0 @@ -openapi: "3.0.0" -info: - version: 1.0.0 - title: "When using `prefer-skip-optional-pointer-on-container-types`, container types do not have an 'optional pointer'" -paths: -components: - schemas: - ResponseBody: - type: object - required: - - required_slice - properties: - required_slice: - type: array - items: - $ref: '#/components/schemas/Pong' - a_slice: - type: array - items: - $ref: '#/components/schemas/Pong' - a_map: - additionalProperties: - $ref: '#/components/schemas/Pong' - unknown_object: - type: object - additional_props: - type: object - additionalProperties: - $ref: '#/components/schemas/Pong' - a_slice_with_additional_props: - type: array - items: - additionalProperties: - $ref: '#/components/schemas/Pong' - bytes: - type: string - format: byte - bytes_with_override: - type: string - format: byte - x-go-type-skip-optional-pointer: false - Pong: - type: object - required: - - ping - properties: - ping: - type: string - example: pong diff --git a/internal/test/issues/issue1767/config.yaml b/internal/test/issues/issue1767/config.yaml deleted file mode 100644 index c1bfe0b5b6..0000000000 --- a/internal/test/issues/issue1767/config.yaml +++ /dev/null @@ -1,7 +0,0 @@ -# yaml-language-server: $schema=../../../../configuration-schema.json -package: issue1767 -generate: - models: true -output: issue1767.gen.go -output-options: - skip-prune: true diff --git a/internal/test/issues/issue1767/generate.go b/internal/test/issues/issue1767/generate.go deleted file mode 100644 index 3f8e1ef572..0000000000 --- a/internal/test/issues/issue1767/generate.go +++ /dev/null @@ -1,3 +0,0 @@ -package issue1767 - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml openapi.yaml diff --git a/internal/test/issues/issue1767/issue1767.gen.go b/internal/test/issues/issue1767/issue1767.gen.go deleted file mode 100644 index 1e7bdaddbb..0000000000 --- a/internal/test/issues/issue1767/issue1767.gen.go +++ /dev/null @@ -1,17 +0,0 @@ -// Package issue1767 provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package issue1767 - -import ( - openapi_types "github.com/oapi-codegen/runtime/types" -) - -// Alarm Alarm Information -type Alarm struct { - // UnderscoreId Identifier of the Alarm. - UnderscoreId *openapi_types.UUID `json:"_id,omitempty"` - - // Id Identifier of the Alarm. - Id *openapi_types.UUID `json:"id,omitempty"` -} diff --git a/internal/test/issues/issue1767/openapi.yaml b/internal/test/issues/issue1767/openapi.yaml deleted file mode 100644 index 5964395ed0..0000000000 --- a/internal/test/issues/issue1767/openapi.yaml +++ /dev/null @@ -1,20 +0,0 @@ -openapi: "3.0.0" -info: - version: 1.0.0 - title: "An underscore in the name of a field is remapped to `Underscore`" -paths: -components: - schemas: - Alarm: - description: | - Alarm Information - type: object - properties: - _id: - description: Identifier of the Alarm. - type: string - format: uuid - id: - description: Identifier of the Alarm. - type: string - format: uuid diff --git a/internal/test/issues/issue1825/config.yaml b/internal/test/issues/issue1825/config.yaml deleted file mode 100644 index 2df08d4b71..0000000000 --- a/internal/test/issues/issue1825/config.yaml +++ /dev/null @@ -1,11 +0,0 @@ -package: issue1825 -generate: - models: true - embedded-spec: true -import-mapping: - ../packageA/spec.yaml: github.com/oapi-codegen/oapi-codegen/v2/internal/test/issues/issue1825/packageA -output: issue1825.gen.go -output-options: - skip-prune: true - overlay: - path: overlay.yaml diff --git a/internal/test/issues/issue1825/doc.go b/internal/test/issues/issue1825/doc.go deleted file mode 100644 index 664a3ae916..0000000000 --- a/internal/test/issues/issue1825/doc.go +++ /dev/null @@ -1,5 +0,0 @@ -package issue1825 - -// We place the spec in a subdirectory, as this requires us to initialize the resolver kin-openapi's loader -// If this is not done, the generator would fail with an `encountered disallowed external reference` error. -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml spec/spec.yaml diff --git a/internal/test/issues/issue1825/issue1825.gen.go b/internal/test/issues/issue1825/issue1825.gen.go deleted file mode 100644 index 679963f84c..0000000000 --- a/internal/test/issues/issue1825/issue1825.gen.go +++ /dev/null @@ -1,110 +0,0 @@ -// Package issue1825 provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package issue1825 - -import ( - "bytes" - "compress/gzip" - "encoding/base64" - "fmt" - "net/url" - "path" - "strings" - - "github.com/getkin/kin-openapi/openapi3" - externalRef0 "github.com/oapi-codegen/oapi-codegen/v2/internal/test/issues/issue1825/packageA" -) - -// Container defines model for Container. -type Container struct { - ObjectA *externalRef0.ObjectA `json:"object_a,omitempty"` - ObjectB *map[string]interface{} `json:"object_b,omitempty"` -} - -// Base64 encoded, gzipped, json marshaled Swagger object -var swaggerSpec = []string{ - - "H4sIAAAAAAAC/4SP0U7DMAxF/8Xw2K2TeOvbxAfAH1Re6m2G1rESd2Ka8u/IWQcIkPaUWNf33OsLhDhp", - "FBLL0F0ghyNNWL/PUQxZKPmgKSolY6pS3L1RsB79/5hoDx08tN+gdqG0iuEdD7Tts1LoX6prC6W5AXb3", - "AF97pfxy4TCwcRQcX39UszRTA3ZWgm5Z97j/e/w5S3Aifxd/tsRy8GgPZ9nHKrKNrkIDJ0qZo1yHj1U8", - "URrxvELVkWm4EuZgc6LhJtbjlQSVoYOn9Wa9Ae9nR29QymcAAAD//5P9oGCQAQAA", -} - -// GetSwagger returns the content of the embedded swagger specification file -// or error if failed to decode -func decodeSpec() ([]byte, error) { - zipped, err := base64.StdEncoding.DecodeString(strings.Join(swaggerSpec, "")) - if err != nil { - return nil, fmt.Errorf("error base64 decoding spec: %w", err) - } - zr, err := gzip.NewReader(bytes.NewReader(zipped)) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - var buf bytes.Buffer - _, err = buf.ReadFrom(zr) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - - return buf.Bytes(), nil -} - -var rawSpec = decodeSpecCached() - -// a naive cached of a decoded swagger spec -func decodeSpecCached() func() ([]byte, error) { - data, err := decodeSpec() - return func() ([]byte, error) { - return data, err - } -} - -// Constructs a synthetic filesystem for resolving external references when loading openapi specifications. -func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { - res := make(map[string]func() ([]byte, error)) - if len(pathToFile) > 0 { - res[pathToFile] = rawSpec - } - - for rawPath, rawFunc := range externalRef0.PathToRawSpec(path.Join(path.Dir(pathToFile), "../packageA/spec.yaml")) { - if _, ok := res[rawPath]; ok { - // it is not possible to compare functions in golang, so always overwrite the old value - } - res[rawPath] = rawFunc - } - return res -} - -// GetSwagger returns the Swagger specification corresponding to the generated code -// in this file. The external references of Swagger specification are resolved. -// The logic of resolving external references is tightly connected to "import-mapping" feature. -// Externally referenced files must be embedded in the corresponding golang packages. -// Urls can be supported but this task was out of the scope. -func GetSwagger() (swagger *openapi3.T, err error) { - resolvePath := PathToRawSpec("") - - loader := openapi3.NewLoader() - loader.IsExternalRefsAllowed = true - loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() - pathToFile = path.Clean(pathToFile) - getSpec, ok := resolvePath[pathToFile] - if !ok { - err1 := fmt.Errorf("path not found: %s", pathToFile) - return nil, err1 - } - return getSpec() - } - var specData []byte - specData, err = rawSpec() - if err != nil { - return - } - swagger, err = loader.LoadFromData(specData) - if err != nil { - return - } - return -} diff --git a/internal/test/issues/issue1825/object_b.json b/internal/test/issues/issue1825/object_b.json deleted file mode 100644 index cdd7fc12af..0000000000 --- a/internal/test/issues/issue1825/object_b.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "type": "object", - "properties": {}, - "additionalProperties": true -} diff --git a/internal/test/issues/issue1825/overlay.yaml b/internal/test/issues/issue1825/overlay.yaml deleted file mode 100644 index 55011983fe..0000000000 --- a/internal/test/issues/issue1825/overlay.yaml +++ /dev/null @@ -1,10 +0,0 @@ -overlay: 1.0.0 -info: - title: Overlay example - version: 0.0.0 -actions: - - target: "$" - description: Add a property to the info dictionary - update: - info: - x-overlay-applied: structured-overlay diff --git a/internal/test/issues/issue1825/overlay_test.go b/internal/test/issues/issue1825/overlay_test.go deleted file mode 100644 index 115a878fad..0000000000 --- a/internal/test/issues/issue1825/overlay_test.go +++ /dev/null @@ -1,14 +0,0 @@ -package issue1825 - -import ( - "testing" - - "github.com/stretchr/testify/require" -) - -func TestOverlayApply(t *testing.T) { - spec, err := GetSwagger() - require.NoError(t, err) - - require.Equal(t, spec.Info.Extensions["x-overlay-applied"], "structured-overlay") -} diff --git a/internal/test/issues/issue1825/packageA/config.yaml b/internal/test/issues/issue1825/packageA/config.yaml deleted file mode 100644 index e84dbfad74..0000000000 --- a/internal/test/issues/issue1825/packageA/config.yaml +++ /dev/null @@ -1,7 +0,0 @@ -package: packagea -generate: - models: true - embedded-spec: true -output-options: - skip-prune: true -output: externalref.gen.go diff --git a/internal/test/issues/issue1825/packageA/doc.go b/internal/test/issues/issue1825/packageA/doc.go deleted file mode 100644 index f05471ffbb..0000000000 --- a/internal/test/issues/issue1825/packageA/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -package packagea - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml spec.yaml diff --git a/internal/test/issues/issue1825/packageA/externalref.gen.go b/internal/test/issues/issue1825/packageA/externalref.gen.go deleted file mode 100644 index b2d5ca870b..0000000000 --- a/internal/test/issues/issue1825/packageA/externalref.gen.go +++ /dev/null @@ -1,100 +0,0 @@ -// Package packagea provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package packagea - -import ( - "bytes" - "compress/gzip" - "encoding/base64" - "fmt" - "net/url" - "path" - "strings" - - "github.com/getkin/kin-openapi/openapi3" -) - -// ObjectA defines model for ObjectA. -type ObjectA struct { - Name *string `json:"name,omitempty"` -} - -// Base64 encoded, gzipped, json marshaled Swagger object -var swaggerSpec = []string{ - - "H4sIAAAAAAAC/yTJwQ0CMQxE0V7mnApyowJqCNHAGm1sKzYHtNreUZa5zJfegW7DTakZqAeibxztyvvj", - "zZ63lT7NOVN4gbbB9fl1oiJyir5wrhWIPg1VP/teYE5tLqhAgbfc4i/nLwAA//+kHCeTdgAAAA==", -} - -// GetSwagger returns the content of the embedded swagger specification file -// or error if failed to decode -func decodeSpec() ([]byte, error) { - zipped, err := base64.StdEncoding.DecodeString(strings.Join(swaggerSpec, "")) - if err != nil { - return nil, fmt.Errorf("error base64 decoding spec: %w", err) - } - zr, err := gzip.NewReader(bytes.NewReader(zipped)) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - var buf bytes.Buffer - _, err = buf.ReadFrom(zr) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - - return buf.Bytes(), nil -} - -var rawSpec = decodeSpecCached() - -// a naive cached of a decoded swagger spec -func decodeSpecCached() func() ([]byte, error) { - data, err := decodeSpec() - return func() ([]byte, error) { - return data, err - } -} - -// Constructs a synthetic filesystem for resolving external references when loading openapi specifications. -func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { - res := make(map[string]func() ([]byte, error)) - if len(pathToFile) > 0 { - res[pathToFile] = rawSpec - } - - return res -} - -// GetSwagger returns the Swagger specification corresponding to the generated code -// in this file. The external references of Swagger specification are resolved. -// The logic of resolving external references is tightly connected to "import-mapping" feature. -// Externally referenced files must be embedded in the corresponding golang packages. -// Urls can be supported but this task was out of the scope. -func GetSwagger() (swagger *openapi3.T, err error) { - resolvePath := PathToRawSpec("") - - loader := openapi3.NewLoader() - loader.IsExternalRefsAllowed = true - loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() - pathToFile = path.Clean(pathToFile) - getSpec, ok := resolvePath[pathToFile] - if !ok { - err1 := fmt.Errorf("path not found: %s", pathToFile) - return nil, err1 - } - return getSpec() - } - var specData []byte - specData, err = rawSpec() - if err != nil { - return - } - swagger, err = loader.LoadFromData(specData) - if err != nil { - return - } - return -} diff --git a/internal/test/issues/issue1825/packageA/spec.yaml b/internal/test/issues/issue1825/packageA/spec.yaml deleted file mode 100644 index 303c509938..0000000000 --- a/internal/test/issues/issue1825/packageA/spec.yaml +++ /dev/null @@ -1,6 +0,0 @@ -components: - schemas: - ObjectA: - properties: - name: - type: string diff --git a/internal/test/issues/issue1825/spec/spec.yaml b/internal/test/issues/issue1825/spec/spec.yaml deleted file mode 100644 index 3a29a23582..0000000000 --- a/internal/test/issues/issue1825/spec/spec.yaml +++ /dev/null @@ -1,11 +0,0 @@ -openapi: "3.0.0" -info: {} -paths: {} -components: - schemas: - Container: - properties: - object_a: - $ref: ../packageA/spec.yaml#/components/schemas/ObjectA - object_b: - $ref: ../object_b.json diff --git a/internal/test/issues/issue193/config.yaml b/internal/test/issues/issue193/config.yaml deleted file mode 100644 index 908d772c69..0000000000 --- a/internal/test/issues/issue193/config.yaml +++ /dev/null @@ -1,6 +0,0 @@ -package: issue52 -generate: - models: true -output: issue.gen.go -output-options: - skip-prune: true diff --git a/internal/test/issues/issue193/generate.go b/internal/test/issues/issue193/generate.go deleted file mode 100644 index 3d239ebdcf..0000000000 --- a/internal/test/issues/issue193/generate.go +++ /dev/null @@ -1,3 +0,0 @@ -package issue52 - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml spec.yaml diff --git a/internal/test/issues/issue193/issue.gen.go b/internal/test/issues/issue193/issue.gen.go deleted file mode 100644 index eec8a25dfc..0000000000 --- a/internal/test/issues/issue193/issue.gen.go +++ /dev/null @@ -1,113 +0,0 @@ -// Package issue52 provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package issue52 - -import ( - "encoding/json" - "fmt" -) - -// Person defines model for Person. -type Person struct { - Age *float32 `json:"age,omitempty"` - Metadata string `json:"metadata"` - Name *string `json:"name,omitempty"` - AdditionalProperties map[string]interface{} `json:"-"` -} - -// Getter for additional properties for Person. Returns the specified -// element and whether it was found -func (a Person) Get(fieldName string) (value interface{}, found bool) { - if a.AdditionalProperties != nil { - value, found = a.AdditionalProperties[fieldName] - } - return -} - -// Setter for additional properties for Person -func (a *Person) Set(fieldName string, value interface{}) { - if a.AdditionalProperties == nil { - a.AdditionalProperties = make(map[string]interface{}) - } - a.AdditionalProperties[fieldName] = value -} - -// Override default JSON handling for Person to handle AdditionalProperties -func (a *Person) UnmarshalJSON(b []byte) error { - object := make(map[string]json.RawMessage) - err := json.Unmarshal(b, &object) - if err != nil { - return err - } - - if raw, found := object["age"]; found { - err = json.Unmarshal(raw, &a.Age) - if err != nil { - return fmt.Errorf("error reading 'age': %w", err) - } - delete(object, "age") - } - - if raw, found := object["metadata"]; found { - err = json.Unmarshal(raw, &a.Metadata) - if err != nil { - return fmt.Errorf("error reading 'metadata': %w", err) - } - delete(object, "metadata") - } - - if raw, found := object["name"]; found { - err = json.Unmarshal(raw, &a.Name) - if err != nil { - return fmt.Errorf("error reading 'name': %w", err) - } - delete(object, "name") - } - - if len(object) != 0 { - a.AdditionalProperties = make(map[string]interface{}) - for fieldName, fieldBuf := range object { - var fieldVal interface{} - err := json.Unmarshal(fieldBuf, &fieldVal) - if err != nil { - return fmt.Errorf("error unmarshaling field %s: %w", fieldName, err) - } - a.AdditionalProperties[fieldName] = fieldVal - } - } - return nil -} - -// Override default JSON handling for Person to handle AdditionalProperties -func (a Person) MarshalJSON() ([]byte, error) { - var err error - object := make(map[string]json.RawMessage) - - if a.Age != nil { - object["age"], err = json.Marshal(a.Age) - if err != nil { - return nil, fmt.Errorf("error marshaling 'age': %w", err) - } - } - - object["metadata"], err = json.Marshal(a.Metadata) - if err != nil { - return nil, fmt.Errorf("error marshaling 'metadata': %w", err) - } - - if a.Name != nil { - object["name"], err = json.Marshal(a.Name) - if err != nil { - return nil, fmt.Errorf("error marshaling 'name': %w", err) - } - } - - for fieldName, field := range a.AdditionalProperties { - object[fieldName], err = json.Marshal(field) - if err != nil { - return nil, fmt.Errorf("error marshaling '%s': %w", fieldName, err) - } - } - return json.Marshal(object) -} diff --git a/internal/test/issues/issue193/spec.yaml b/internal/test/issues/issue193/spec.yaml deleted file mode 100644 index 4002ffbca5..0000000000 --- a/internal/test/issues/issue193/spec.yaml +++ /dev/null @@ -1,26 +0,0 @@ -openapi: 3.0.0 -info: - title: test schema - -paths: - -components: - schemas: - Person: - allOf: - # common fields - - type: object - additionalProperties: true - required: - - metadata - properties: - metadata: - type: string - # person specific fields - - type: object - additionalProperties: true - properties: - name: - type: string - age: - type: number diff --git a/internal/test/issues/issue1957/config.yaml b/internal/test/issues/issue1957/config.yaml deleted file mode 100644 index 42b31a19f6..0000000000 --- a/internal/test/issues/issue1957/config.yaml +++ /dev/null @@ -1,6 +0,0 @@ -package: issue1957 -generate: - models: true -output: issue1957.gen.go -output-options: - skip-prune: true diff --git a/internal/test/issues/issue1957/generate.go b/internal/test/issues/issue1957/generate.go deleted file mode 100644 index 1a7c0002be..0000000000 --- a/internal/test/issues/issue1957/generate.go +++ /dev/null @@ -1,3 +0,0 @@ -package issue1957 - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml openapi.yaml diff --git a/internal/test/issues/issue1957/issue1957.gen.go b/internal/test/issues/issue1957/issue1957.gen.go deleted file mode 100644 index ee2c7adb75..0000000000 --- a/internal/test/issues/issue1957/issue1957.gen.go +++ /dev/null @@ -1,27 +0,0 @@ -// Package issue1957 provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package issue1957 - -import ( - googleuuid "github.com/google/uuid" -) - -// ID defines model for ID. -type ID = googleuuid.UUID - -// TypeWithAllOf defines model for TypeWithAllOf. -type TypeWithAllOf struct { - Id googleuuid.UUID `json:"id,omitempty"` -} - -// TypeWithOptionalField defines model for TypeWithOptionalField. -type TypeWithOptionalField struct { - At googleuuid.UUID `json:"at,omitempty"` - AtRequired googleuuid.UUID `json:"at_required"` -} - -// GetRootParams defines parameters for GetRoot. -type GetRootParams struct { - At googleuuid.UUID `form:"at,omitempty" json:"at,omitempty"` -} diff --git a/internal/test/issues/issue1957/issue1957_test.go b/internal/test/issues/issue1957/issue1957_test.go deleted file mode 100644 index de99ccca36..0000000000 --- a/internal/test/issues/issue1957/issue1957_test.go +++ /dev/null @@ -1,54 +0,0 @@ -package issue1957 - -import ( - "testing" - - "github.com/google/uuid" - "github.com/stretchr/testify/require" -) - -func TestGeneratedCode(t *testing.T) { - t.Run("For an object", func(t *testing.T) { - t.Run("A required field should be a non-pointer", func(t *testing.T) { - theType := TypeWithOptionalField{ - AtRequired: uuid.New(), - } - - require.NotZero(t, theType.AtRequired) - }) - - t.Run("An optional field with x-go-type-skip-optional-pointer should be a non-pointer", func(t *testing.T) { - theType := TypeWithOptionalField{ - AtRequired: uuid.New(), - } - - require.NotZero(t, theType.AtRequired) - }) - }) - - t.Run("For a query parameter", func(t *testing.T) { - t.Run("An optional field with x-go-type-skip-optional-pointer should be a non-pointer", func(t *testing.T) { - - u := uuid.New() - - theType := GetRootParams{ - At: u, - } - - require.NotZero(t, theType.At) - }) - }) - - t.Run("For a field with an AllOf", func(t *testing.T) { - t.Run("An optional field with x-go-type-skip-optional-pointer should be a non-pointer", func(t *testing.T) { - - u := uuid.New() - - theType := TypeWithAllOf{ - Id: u, - } - - require.NotZero(t, theType.Id) - }) - }) -} diff --git a/internal/test/issues/issue1957/openapi.yaml b/internal/test/issues/issue1957/openapi.yaml deleted file mode 100644 index 729c71dac9..0000000000 --- a/internal/test/issues/issue1957/openapi.yaml +++ /dev/null @@ -1,55 +0,0 @@ -openapi: "3.0.0" -info: - version: 1.0.0 - title: "x-go-type and x-go-type-skip-optional-pointer should be possible to use together" -paths: - /root: - get: - operationId: getRoot - parameters: - - in: query - name: at - schema: - type: string - format: date-time - x-go-type-skip-optional-pointer: true - x-go-type: googleuuid.UUID - x-go-type-import: - path: github.com/google/uuid - name: googleuuid - responses: - "200": - description: Some data -components: - schemas: - TypeWithOptionalField: - type: object - properties: - at: - type: string - x-go-type-skip-optional-pointer: true - x-go-type: googleuuid.UUID - x-go-type-import: - path: github.com/google/uuid - name: googleuuid - at_required: - type: string - x-go-type: googleuuid.UUID - x-go-type-import: - path: github.com/google/uuid - name: googleuuid - required: - - at_required - ID: - type: string - x-go-type: googleuuid.UUID - x-go-type-import: - path: github.com/google/uuid - name: googleuuid - TypeWithAllOf: - type: object - properties: - id: - allOf: - - $ref: '#/components/schemas/ID' - - x-go-type-skip-optional-pointer: true diff --git a/internal/test/issues/issue240/api.yaml b/internal/test/issues/issue240/api.yaml deleted file mode 100644 index 5945b63dd7..0000000000 --- a/internal/test/issues/issue240/api.yaml +++ /dev/null @@ -1,47 +0,0 @@ -openapi: "3.0.0" -info: - version: 1.0.0 - title: Generate models -paths: - /client: - get: - operationId: getClient - responses: - 200: - content: - application/json: - schema: - $ref: "#/components/schemas/ClientType" - put: - operationId: updateClient - responses: - 400: - content: - application/json: - schema: - type: object - properties: - code: - type: string - required: - - code -components: - schemas: - ClientType: - type: object - required: - - name - properties: - name: - type: string - # NOTE that this is not generated by default because it's not referenced. If you want it, you need to use the following YAML configuration: - # - # output-options: - # skip-prune: true - Unreferenced: - type: object - required: - - id - properties: - id: - type: int diff --git a/internal/test/issues/issue240/cfg.yaml b/internal/test/issues/issue240/cfg.yaml deleted file mode 100644 index e3143764a0..0000000000 --- a/internal/test/issues/issue240/cfg.yaml +++ /dev/null @@ -1,8 +0,0 @@ -# yaml-language-server: $schema=../../../../configuration-schema.json -package: issue240 -output: client.gen.go -generate: - models: true - client: true -output-options: - client-response-bytes-function: true diff --git a/internal/test/issues/issue240/client.gen.go b/internal/test/issues/issue240/client.gen.go deleted file mode 100644 index 8a0a533589..0000000000 --- a/internal/test/issues/issue240/client.gen.go +++ /dev/null @@ -1,355 +0,0 @@ -// Package issue240 provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package issue240 - -import ( - "context" - "encoding/json" - "fmt" - "io" - "net/http" - "net/url" - "strings" -) - -// ClientType defines model for ClientType. -type ClientType struct { - Name string `json:"name"` -} - -// RequestEditorFn is the function signature for the RequestEditor callback function -type RequestEditorFn func(ctx context.Context, req *http.Request) error - -// Doer performs HTTP requests. -// -// The standard http.Client implements this interface. -type HttpRequestDoer interface { - Do(req *http.Request) (*http.Response, error) -} - -// Client which conforms to the OpenAPI3 specification for this service. -type Client struct { - // The endpoint of the server conforming to this interface, with scheme, - // https://api.deepmap.com for example. This can contain a path relative - // to the server, such as https://api.deepmap.com/dev-test, and all the - // paths in the swagger spec will be appended to the server. - Server string - - // Doer for performing requests, typically a *http.Client with any - // customized settings, such as certificate chains. - Client HttpRequestDoer - - // A list of callbacks for modifying requests which are generated before sending over - // the network. - RequestEditors []RequestEditorFn -} - -// ClientOption allows setting custom parameters during construction -type ClientOption func(*Client) error - -// Creates a new Client, with reasonable defaults -func NewClient(server string, opts ...ClientOption) (*Client, error) { - // create a client with sane default values - client := Client{ - Server: server, - } - // mutate client and add all optional params - for _, o := range opts { - if err := o(&client); err != nil { - return nil, err - } - } - // ensure the server URL always has a trailing slash - if !strings.HasSuffix(client.Server, "/") { - client.Server += "/" - } - // create httpClient, if not already present - if client.Client == nil { - client.Client = &http.Client{} - } - return &client, nil -} - -// WithHTTPClient allows overriding the default Doer, which is -// automatically created using http.Client. This is useful for tests. -func WithHTTPClient(doer HttpRequestDoer) ClientOption { - return func(c *Client) error { - c.Client = doer - return nil - } -} - -// WithRequestEditorFn allows setting up a callback function, which will be -// called right before sending the request. This can be used to mutate the request. -func WithRequestEditorFn(fn RequestEditorFn) ClientOption { - return func(c *Client) error { - c.RequestEditors = append(c.RequestEditors, fn) - return nil - } -} - -// The interface specification for the client above. -type ClientInterface interface { - // GetClient request - GetClient(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) - - // UpdateClient request - UpdateClient(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) -} - -func (c *Client) GetClient(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewGetClientRequest(c.Server) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) UpdateClient(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewUpdateClientRequest(c.Server) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -// NewGetClientRequest generates requests for GetClient -func NewGetClientRequest(server string) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/client") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -// NewUpdateClientRequest generates requests for UpdateClient -func NewUpdateClientRequest(server string) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/client") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("PUT", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -func (c *Client) applyEditors(ctx context.Context, req *http.Request, additionalEditors []RequestEditorFn) error { - for _, r := range c.RequestEditors { - if err := r(ctx, req); err != nil { - return err - } - } - for _, r := range additionalEditors { - if err := r(ctx, req); err != nil { - return err - } - } - return nil -} - -// ClientWithResponses builds on ClientInterface to offer response payloads -type ClientWithResponses struct { - ClientInterface -} - -// NewClientWithResponses creates a new ClientWithResponses, which wraps -// Client with return type handling -func NewClientWithResponses(server string, opts ...ClientOption) (*ClientWithResponses, error) { - client, err := NewClient(server, opts...) - if err != nil { - return nil, err - } - return &ClientWithResponses{client}, nil -} - -// WithBaseURL overrides the baseURL. -func WithBaseURL(baseURL string) ClientOption { - return func(c *Client) error { - newBaseURL, err := url.Parse(baseURL) - if err != nil { - return err - } - c.Server = newBaseURL.String() - return nil - } -} - -// ClientWithResponsesInterface is the interface specification for the client with responses above. -type ClientWithResponsesInterface interface { - // GetClientWithResponse request - GetClientWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*GetClientResponse, error) - - // UpdateClientWithResponse request - UpdateClientWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*UpdateClientResponse, error) -} - -type GetClientResponse struct { - Body []byte - HTTPResponse *http.Response - JSON200 *ClientType -} - -// Status returns HTTPResponse.Status -func (r GetClientResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r GetClientResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -// Bytes is a convenience method to retrieve the raw bytes from the HTTP response -func (r GetClientResponse) Bytes() []byte { - return r.Body -} - -type UpdateClientResponse struct { - Body []byte - HTTPResponse *http.Response - JSON400 *struct { - Code string `json:"code"` - } -} - -// Status returns HTTPResponse.Status -func (r UpdateClientResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r UpdateClientResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -// Bytes is a convenience method to retrieve the raw bytes from the HTTP response -func (r UpdateClientResponse) Bytes() []byte { - return r.Body -} - -// GetClientWithResponse request returning *GetClientResponse -func (c *ClientWithResponses) GetClientWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*GetClientResponse, error) { - rsp, err := c.GetClient(ctx, reqEditors...) - if err != nil { - return nil, err - } - return ParseGetClientResponse(rsp) -} - -// UpdateClientWithResponse request returning *UpdateClientResponse -func (c *ClientWithResponses) UpdateClientWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*UpdateClientResponse, error) { - rsp, err := c.UpdateClient(ctx, reqEditors...) - if err != nil { - return nil, err - } - return ParseUpdateClientResponse(rsp) -} - -// ParseGetClientResponse parses an HTTP response from a GetClientWithResponse call -func ParseGetClientResponse(rsp *http.Response) (*GetClientResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &GetClientResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest ClientType - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON200 = &dest - - } - - return response, nil -} - -// ParseUpdateClientResponse parses an HTTP response from a UpdateClientWithResponse call -func ParseUpdateClientResponse(rsp *http.Response) (*UpdateClientResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &UpdateClientResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: - var dest struct { - Code string `json:"code"` - } - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON400 = &dest - - } - - return response, nil -} diff --git a/internal/test/issues/issue240/generate.go b/internal/test/issues/issue240/generate.go deleted file mode 100644 index a107ac4597..0000000000 --- a/internal/test/issues/issue240/generate.go +++ /dev/null @@ -1,3 +0,0 @@ -package issue240 - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen -config cfg.yaml api.yaml diff --git a/internal/test/issues/issue609/config.yaml b/internal/test/issues/issue609/config.yaml deleted file mode 100644 index a9c4b93879..0000000000 --- a/internal/test/issues/issue609/config.yaml +++ /dev/null @@ -1,7 +0,0 @@ -# yaml-language-server: $schema=../../../../configuration-schema.json -package: issue609 -generate: - models: true -output: issue609.gen.go -output-options: - skip-prune: true diff --git a/internal/test/issues/issue609/generate.go b/internal/test/issues/issue609/generate.go deleted file mode 100644 index ade5eb92fb..0000000000 --- a/internal/test/issues/issue609/generate.go +++ /dev/null @@ -1,3 +0,0 @@ -package issue609 - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml openapi.yaml diff --git a/internal/test/issues/issue609/issue609.gen.go b/internal/test/issues/issue609/issue609.gen.go deleted file mode 100644 index a5d76e500d..0000000000 --- a/internal/test/issues/issue609/issue609.gen.go +++ /dev/null @@ -1,9 +0,0 @@ -// Package issue609 provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package issue609 - -// ResponseBody defines model for ResponseBody. -type ResponseBody struct { - Unknown interface{} `json:"unknown,omitempty"` -} diff --git a/internal/test/issues/issue609/openapi.yaml b/internal/test/issues/issue609/openapi.yaml deleted file mode 100644 index d7dae7fdf3..0000000000 --- a/internal/test/issues/issue609/openapi.yaml +++ /dev/null @@ -1,11 +0,0 @@ -openapi: "3.0.0" -info: - version: 1.0.0 - title: "Referencing an optional field, which has no information about the type it is will generate an `interface{}`, without the 'optional pointer'" -paths: -components: - schemas: - ResponseBody: - type: object - properties: - unknown: {} diff --git a/internal/test/outputoptions/disabletypealiases/config.yaml b/internal/test/outputoptions/disabletypealiases/config.yaml deleted file mode 100644 index b82daa271a..0000000000 --- a/internal/test/outputoptions/disabletypealiases/config.yaml +++ /dev/null @@ -1,9 +0,0 @@ -# yaml-language-server: $schema=../../../../configuration-schema.json -package: types -generate: - models: true -output: types.gen.go -output-options: - skip-prune: true - disable-type-aliases-for-type: - - array diff --git a/internal/test/outputoptions/disabletypealiases/spec.yaml b/internal/test/outputoptions/disabletypealiases/spec.yaml deleted file mode 100644 index e073eb3c64..0000000000 --- a/internal/test/outputoptions/disabletypealiases/spec.yaml +++ /dev/null @@ -1,13 +0,0 @@ -components: - schemas: - my_item: - type: object - properties: - name: - type: string - age: - type: integer - example: - type: array - items: - $ref: '#/components/schemas/my_item' diff --git a/internal/test/outputoptions/disabletypealiases/types.gen.go b/internal/test/outputoptions/disabletypealiases/types.gen.go deleted file mode 100644 index f2537cfba5..0000000000 --- a/internal/test/outputoptions/disabletypealiases/types.gen.go +++ /dev/null @@ -1,13 +0,0 @@ -// Package types provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package types - -// Example defines model for example. -type Example []MyItem - -// MyItem defines model for my_item. -type MyItem struct { - Age *int `json:"age,omitempty"` - Name *string `json:"name,omitempty"` -} diff --git a/internal/test/outputoptions/disabletypealiases/types_ext.go b/internal/test/outputoptions/disabletypealiases/types_ext.go deleted file mode 100644 index 49103fd7f9..0000000000 --- a/internal/test/outputoptions/disabletypealiases/types_ext.go +++ /dev/null @@ -1,5 +0,0 @@ -package types - -// MustCompile will only compile if the type it's defined on has type aliases disabled -func (*Example) MustCompile() { -} diff --git a/internal/test/outputoptions/name-normalizer/spec.yaml b/internal/test/outputoptions/name-normalizer/spec.yaml deleted file mode 100644 index 524ecb70ad..0000000000 --- a/internal/test/outputoptions/name-normalizer/spec.yaml +++ /dev/null @@ -1,64 +0,0 @@ -openapi: "3.0.0" -info: - version: 1.0.0 - title: Example code for the `name-normalizer` output option -paths: - /api/pets/{petId}: - get: - summary: Get pet given identifier. - operationId: getHttpPet - parameters: - - name: petId - in: path - required: true - schema: - type: string - responses: - '200': - description: valid pet - content: - application/json: - schema: - $ref: '#/components/schemas/Pet' -components: - schemas: - Pet: - type: object - required: - - uuid - - name - properties: - uuid: - type: string - description: The pet uuid. - name: - type: string - description: The name of the pet. - Error: - required: - - code - - message - properties: - code: - type: integer - format: int32 - description: Error code - message: - type: string - description: Error message - OneOf2things: - description: "Notice that the `things` is not capitalised" - oneOf: - - type: object - required: - - id - properties: - id: - type: integer - - type: object - required: - - id - properties: - id: - type: string - format: uuid diff --git a/internal/test/outputoptions/name-normalizer/to-camel-case-with-additional-initialisms/config.yaml b/internal/test/outputoptions/name-normalizer/to-camel-case-with-additional-initialisms/config.yaml deleted file mode 100644 index 1e0ffb5655..0000000000 --- a/internal/test/outputoptions/name-normalizer/to-camel-case-with-additional-initialisms/config.yaml +++ /dev/null @@ -1,13 +0,0 @@ -# yaml-language-server: $schema=../../../../../configuration-schema.json -package: tocamelcasewithadditionalinitialisms -generate: - gorilla-server: true - client: true - models: true - embedded-spec: true -output: name_normalizer.gen.go -output-options: - skip-prune: true - name-normalizer: ToCamelCaseWithInitialisms - additional-initialisms: - - NAME diff --git a/internal/test/outputoptions/name-normalizer/to-camel-case-with-additional-initialisms/generate.go b/internal/test/outputoptions/name-normalizer/to-camel-case-with-additional-initialisms/generate.go deleted file mode 100644 index c5611adbd0..0000000000 --- a/internal/test/outputoptions/name-normalizer/to-camel-case-with-additional-initialisms/generate.go +++ /dev/null @@ -1,3 +0,0 @@ -package tocamelcasewithadditionalinitialisms - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml ../spec.yaml diff --git a/internal/test/outputoptions/name-normalizer/to-camel-case-with-additional-initialisms/name_normalizer.gen.go b/internal/test/outputoptions/name-normalizer/to-camel-case-with-additional-initialisms/name_normalizer.gen.go deleted file mode 100644 index 8d02762813..0000000000 --- a/internal/test/outputoptions/name-normalizer/to-camel-case-with-additional-initialisms/name_normalizer.gen.go +++ /dev/null @@ -1,590 +0,0 @@ -// Package tocamelcasewithadditionalinitialisms provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package tocamelcasewithadditionalinitialisms - -import ( - "bytes" - "compress/gzip" - "context" - "encoding/base64" - "encoding/json" - "fmt" - "io" - "net/http" - "net/url" - "path" - "strings" - - "github.com/getkin/kin-openapi/openapi3" - "github.com/gorilla/mux" - "github.com/oapi-codegen/runtime" - openapi_types "github.com/oapi-codegen/runtime/types" -) - -// Error defines model for Error. -type Error struct { - // Code Error code - Code int32 `json:"code"` - - // Message Error message - Message string `json:"message"` -} - -// OneOf2Things Notice that the `things` is not capitalised -type OneOf2Things struct { - union json.RawMessage -} - -// OneOf2Things0 defines model for . -type OneOf2Things0 struct { - ID int `json:"id"` -} - -// OneOf2Things1 defines model for . -type OneOf2Things1 struct { - ID openapi_types.UUID `json:"id"` -} - -// Pet defines model for Pet. -type Pet struct { - // NAME The name of the pet. - NAME string `json:"name"` - - // UUID The pet uuid. - UUID string `json:"uuid"` -} - -// AsOneOf2Things0 returns the union data inside the OneOf2Things as a OneOf2Things0 -func (t OneOf2Things) AsOneOf2Things0() (OneOf2Things0, error) { - var body OneOf2Things0 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromOneOf2Things0 overwrites any union data inside the OneOf2Things as the provided OneOf2Things0 -func (t *OneOf2Things) FromOneOf2Things0(v OneOf2Things0) error { - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeOneOf2Things0 performs a merge with any union data inside the OneOf2Things, using the provided OneOf2Things0 -func (t *OneOf2Things) MergeOneOf2Things0(v OneOf2Things0) error { - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -// AsOneOf2Things1 returns the union data inside the OneOf2Things as a OneOf2Things1 -func (t OneOf2Things) AsOneOf2Things1() (OneOf2Things1, error) { - var body OneOf2Things1 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromOneOf2Things1 overwrites any union data inside the OneOf2Things as the provided OneOf2Things1 -func (t *OneOf2Things) FromOneOf2Things1(v OneOf2Things1) error { - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeOneOf2Things1 performs a merge with any union data inside the OneOf2Things, using the provided OneOf2Things1 -func (t *OneOf2Things) MergeOneOf2Things1(v OneOf2Things1) error { - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -func (t OneOf2Things) MarshalJSON() ([]byte, error) { - b, err := t.union.MarshalJSON() - return b, err -} - -func (t *OneOf2Things) UnmarshalJSON(b []byte) error { - err := t.union.UnmarshalJSON(b) - return err -} - -// RequestEditorFn is the function signature for the RequestEditor callback function -type RequestEditorFn func(ctx context.Context, req *http.Request) error - -// Doer performs HTTP requests. -// -// The standard http.Client implements this interface. -type HttpRequestDoer interface { - Do(req *http.Request) (*http.Response, error) -} - -// Client which conforms to the OpenAPI3 specification for this service. -type Client struct { - // The endpoint of the server conforming to this interface, with scheme, - // https://api.deepmap.com for example. This can contain a path relative - // to the server, such as https://api.deepmap.com/dev-test, and all the - // paths in the swagger spec will be appended to the server. - Server string - - // Doer for performing requests, typically a *http.Client with any - // customized settings, such as certificate chains. - Client HttpRequestDoer - - // A list of callbacks for modifying requests which are generated before sending over - // the network. - RequestEditors []RequestEditorFn -} - -// ClientOption allows setting custom parameters during construction -type ClientOption func(*Client) error - -// Creates a new Client, with reasonable defaults -func NewClient(server string, opts ...ClientOption) (*Client, error) { - // create a client with sane default values - client := Client{ - Server: server, - } - // mutate client and add all optional params - for _, o := range opts { - if err := o(&client); err != nil { - return nil, err - } - } - // ensure the server URL always has a trailing slash - if !strings.HasSuffix(client.Server, "/") { - client.Server += "/" - } - // create httpClient, if not already present - if client.Client == nil { - client.Client = &http.Client{} - } - return &client, nil -} - -// WithHTTPClient allows overriding the default Doer, which is -// automatically created using http.Client. This is useful for tests. -func WithHTTPClient(doer HttpRequestDoer) ClientOption { - return func(c *Client) error { - c.Client = doer - return nil - } -} - -// WithRequestEditorFn allows setting up a callback function, which will be -// called right before sending the request. This can be used to mutate the request. -func WithRequestEditorFn(fn RequestEditorFn) ClientOption { - return func(c *Client) error { - c.RequestEditors = append(c.RequestEditors, fn) - return nil - } -} - -// The interface specification for the client above. -type ClientInterface interface { - // GetHTTPPet request - GetHTTPPet(ctx context.Context, petID string, reqEditors ...RequestEditorFn) (*http.Response, error) -} - -func (c *Client) GetHTTPPet(ctx context.Context, petID string, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewGetHTTPPetRequest(c.Server, petID) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -// NewGetHTTPPetRequest generates requests for GetHTTPPet -func NewGetHTTPPetRequest(server string, petID string) (*http.Request, error) { - var err error - - var pathParam0 string - - pathParam0, err = runtime.StyleParamWithOptions("simple", false, "petId", petID, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) - if err != nil { - return nil, err - } - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/api/pets/%s", pathParam0) - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -func (c *Client) applyEditors(ctx context.Context, req *http.Request, additionalEditors []RequestEditorFn) error { - for _, r := range c.RequestEditors { - if err := r(ctx, req); err != nil { - return err - } - } - for _, r := range additionalEditors { - if err := r(ctx, req); err != nil { - return err - } - } - return nil -} - -// ClientWithResponses builds on ClientInterface to offer response payloads -type ClientWithResponses struct { - ClientInterface -} - -// NewClientWithResponses creates a new ClientWithResponses, which wraps -// Client with return type handling -func NewClientWithResponses(server string, opts ...ClientOption) (*ClientWithResponses, error) { - client, err := NewClient(server, opts...) - if err != nil { - return nil, err - } - return &ClientWithResponses{client}, nil -} - -// WithBaseURL overrides the baseURL. -func WithBaseURL(baseURL string) ClientOption { - return func(c *Client) error { - newBaseURL, err := url.Parse(baseURL) - if err != nil { - return err - } - c.Server = newBaseURL.String() - return nil - } -} - -// ClientWithResponsesInterface is the interface specification for the client with responses above. -type ClientWithResponsesInterface interface { - // GetHTTPPetWithResponse request - GetHTTPPetWithResponse(ctx context.Context, petID string, reqEditors ...RequestEditorFn) (*GetHTTPPetResponse, error) -} - -type GetHTTPPetResponse struct { - Body []byte - HTTPResponse *http.Response - JSON200 *Pet -} - -// Status returns HTTPResponse.Status -func (r GetHTTPPetResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r GetHTTPPetResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -// GetHTTPPetWithResponse request returning *GetHTTPPetResponse -func (c *ClientWithResponses) GetHTTPPetWithResponse(ctx context.Context, petID string, reqEditors ...RequestEditorFn) (*GetHTTPPetResponse, error) { - rsp, err := c.GetHTTPPet(ctx, petID, reqEditors...) - if err != nil { - return nil, err - } - return ParseGetHTTPPetResponse(rsp) -} - -// ParseGetHTTPPetResponse parses an HTTP response from a GetHTTPPetWithResponse call -func ParseGetHTTPPetResponse(rsp *http.Response) (*GetHTTPPetResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &GetHTTPPetResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest Pet - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON200 = &dest - - } - - return response, nil -} - -// ServerInterface represents all server handlers. -type ServerInterface interface { - // Get pet given identifier. - // (GET /api/pets/{petId}) - GetHTTPPet(w http.ResponseWriter, r *http.Request, petID string) -} - -// ServerInterfaceWrapper converts contexts to parameters. -type ServerInterfaceWrapper struct { - Handler ServerInterface - HandlerMiddlewares []MiddlewareFunc - ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) -} - -type MiddlewareFunc func(http.Handler) http.Handler - -// GetHTTPPet operation middleware -func (siw *ServerInterfaceWrapper) GetHTTPPet(w http.ResponseWriter, r *http.Request) { - - var err error - - // ------------- Path parameter "petId" ------------- - var petID string - - err = runtime.BindStyledParameterWithOptions("simple", "petId", mux.Vars(r)["petId"], &petID, runtime.BindStyledParameterOptions{Explode: false, Required: true, Type: "string", Format: ""}) - if err != nil { - siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "petId", Err: err}) - return - } - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.GetHTTPPet(w, r, petID) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -type UnescapedCookieParamError struct { - ParamName string - Err error -} - -func (e *UnescapedCookieParamError) Error() string { - return fmt.Sprintf("error unescaping cookie parameter '%s'", e.ParamName) -} - -func (e *UnescapedCookieParamError) Unwrap() error { - return e.Err -} - -type UnmarshalingParamError struct { - ParamName string - Err error -} - -func (e *UnmarshalingParamError) Error() string { - return fmt.Sprintf("Error unmarshaling parameter %s as JSON: %s", e.ParamName, e.Err.Error()) -} - -func (e *UnmarshalingParamError) Unwrap() error { - return e.Err -} - -type RequiredParamError struct { - ParamName string -} - -func (e *RequiredParamError) Error() string { - return fmt.Sprintf("Query argument %s is required, but not found", e.ParamName) -} - -type RequiredHeaderError struct { - ParamName string - Err error -} - -func (e *RequiredHeaderError) Error() string { - return fmt.Sprintf("Header parameter %s is required, but not found", e.ParamName) -} - -func (e *RequiredHeaderError) Unwrap() error { - return e.Err -} - -type InvalidParamFormatError struct { - ParamName string - Err error -} - -func (e *InvalidParamFormatError) Error() string { - return fmt.Sprintf("Invalid format for parameter %s: %s", e.ParamName, e.Err.Error()) -} - -func (e *InvalidParamFormatError) Unwrap() error { - return e.Err -} - -type TooManyValuesForParamError struct { - ParamName string - Count int -} - -func (e *TooManyValuesForParamError) Error() string { - return fmt.Sprintf("Expected one value for %s, got %d", e.ParamName, e.Count) -} - -// Handler creates http.Handler with routing matching OpenAPI spec. -func Handler(si ServerInterface) http.Handler { - return HandlerWithOptions(si, GorillaServerOptions{}) -} - -type GorillaServerOptions struct { - BaseURL string - BaseRouter *mux.Router - Middlewares []MiddlewareFunc - ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) -} - -// HandlerFromMux creates http.Handler with routing matching OpenAPI spec based on the provided mux. -func HandlerFromMux(si ServerInterface, r *mux.Router) http.Handler { - return HandlerWithOptions(si, GorillaServerOptions{ - BaseRouter: r, - }) -} - -func HandlerFromMuxWithBaseURL(si ServerInterface, r *mux.Router, baseURL string) http.Handler { - return HandlerWithOptions(si, GorillaServerOptions{ - BaseURL: baseURL, - BaseRouter: r, - }) -} - -// HandlerWithOptions creates http.Handler with additional options -func HandlerWithOptions(si ServerInterface, options GorillaServerOptions) http.Handler { - r := options.BaseRouter - - if r == nil { - r = mux.NewRouter() - } - if options.ErrorHandlerFunc == nil { - options.ErrorHandlerFunc = func(w http.ResponseWriter, r *http.Request, err error) { - http.Error(w, err.Error(), http.StatusBadRequest) - } - } - wrapper := ServerInterfaceWrapper{ - Handler: si, - HandlerMiddlewares: options.Middlewares, - ErrorHandlerFunc: options.ErrorHandlerFunc, - } - - r.HandleFunc(options.BaseURL+"/api/pets/{petId}", wrapper.GetHTTPPet).Methods("GET") - - return r -} - -// Base64 encoded, gzipped, json marshaled Swagger object -var swaggerSpec = []string{ - - "H4sIAAAAAAAC/4RTTW/bPAz+KwLf96jZWXrzvdh6WXvIrQgQzaJtFrakSXSwLvB/HyglWZZk6CWRRerR", - "8yEeoPVT8A4dJ2gOkNoBJ5OXjzH6KIsQfcDIhHm79Rbl32JqIwUm76ApzSrXNHQ+ToahAXL8sAYN/B6w", - "fGKPERYNE6Zk+n8Cncrno4kjuR6WRUPEHzNFtNC8wvHCU/t20fDs8Llb80CuT7fw3zxTi4oHw4oHVLvS", - "uFOUlPOsWhOIzUgJLWjwggXN67UHZOX3WtUVN7KwPfP339+wZVj0faizY/NM9kPVd5FF+wvybWDOTHd8", - "3gyopKJ8l40IyNXtxboQuns6ICupVh/yPYrKRG6JSze5zmdLiUepPf40UxgxPyjV+ViyEoBPTqwa6RfG", - "nfIzh5mVL7Q07DGmQvBztapWwt8HdCYQNPCQtzQEw0M2pjaB6oCc6kNAfrKLbPbFQjHQCOqThQa+IH/d", - "bF7EXjkfzYSMMeWXQXKdYJ4UNpDR4NIDjjPq43BdPJ2zX1tpTsG7VDJbr1Zl1hyjy4RMCCO1mVL9lkTj", - "4QLv/4gdNPBf/Wea6+Mo18I6m/x3hHszkpUQc1xpniYT34vWHG1Pe3SKLDqmjjBWArL8DgAA//+VcR3v", - "MAQAAA==", -} - -// GetSwagger returns the content of the embedded swagger specification file -// or error if failed to decode -func decodeSpec() ([]byte, error) { - zipped, err := base64.StdEncoding.DecodeString(strings.Join(swaggerSpec, "")) - if err != nil { - return nil, fmt.Errorf("error base64 decoding spec: %w", err) - } - zr, err := gzip.NewReader(bytes.NewReader(zipped)) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - var buf bytes.Buffer - _, err = buf.ReadFrom(zr) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - - return buf.Bytes(), nil -} - -var rawSpec = decodeSpecCached() - -// a naive cached of a decoded swagger spec -func decodeSpecCached() func() ([]byte, error) { - data, err := decodeSpec() - return func() ([]byte, error) { - return data, err - } -} - -// Constructs a synthetic filesystem for resolving external references when loading openapi specifications. -func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { - res := make(map[string]func() ([]byte, error)) - if len(pathToFile) > 0 { - res[pathToFile] = rawSpec - } - - return res -} - -// GetSwagger returns the Swagger specification corresponding to the generated code -// in this file. The external references of Swagger specification are resolved. -// The logic of resolving external references is tightly connected to "import-mapping" feature. -// Externally referenced files must be embedded in the corresponding golang packages. -// Urls can be supported but this task was out of the scope. -func GetSwagger() (swagger *openapi3.T, err error) { - resolvePath := PathToRawSpec("") - - loader := openapi3.NewLoader() - loader.IsExternalRefsAllowed = true - loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() - pathToFile = path.Clean(pathToFile) - getSpec, ok := resolvePath[pathToFile] - if !ok { - err1 := fmt.Errorf("path not found: %s", pathToFile) - return nil, err1 - } - return getSpec() - } - var specData []byte - specData, err = rawSpec() - if err != nil { - return - } - swagger, err = loader.LoadFromData(specData) - if err != nil { - return - } - return -} diff --git a/internal/test/outputoptions/name-normalizer/to-camel-case-with-additional-initialisms/name_normalizer_test.go b/internal/test/outputoptions/name-normalizer/to-camel-case-with-additional-initialisms/name_normalizer_test.go deleted file mode 100644 index 82d3b2d478..0000000000 --- a/internal/test/outputoptions/name-normalizer/to-camel-case-with-additional-initialisms/name_normalizer_test.go +++ /dev/null @@ -1,24 +0,0 @@ -package tocamelcasewithadditionalinitialisms - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestGenCodeHasCorrectNames(t *testing.T) { - pet := &Pet{} - assert.Equal(t, "", pet.NAME) - assert.Equal(t, "", pet.UUID) - - uri := "https://my-api.com/some-base-url/v1/" - client, err := NewClient(uri) - assert.Nil(t, err) - assert.NotNil(t, client.GetHTTPPet) - - server := &ServerInterfaceWrapper{} - assert.NotNil(t, server.GetHTTPPet) - - oneOf := OneOf2Things{} - assert.Zero(t, oneOf) -} diff --git a/internal/test/outputoptions/name-normalizer/to-camel-case-with-digits/config.yaml b/internal/test/outputoptions/name-normalizer/to-camel-case-with-digits/config.yaml deleted file mode 100644 index 59b69a9de3..0000000000 --- a/internal/test/outputoptions/name-normalizer/to-camel-case-with-digits/config.yaml +++ /dev/null @@ -1,11 +0,0 @@ -# yaml-language-server: $schema=../../../../../configuration-schema.json -package: tocamelcasewithdigits -generate: - gorilla-server: true - client: true - models: true - embedded-spec: true -output: name_normalizer.gen.go -output-options: - skip-prune: true - name-normalizer: ToCamelCaseWithDigits diff --git a/internal/test/outputoptions/name-normalizer/to-camel-case-with-digits/generate.go b/internal/test/outputoptions/name-normalizer/to-camel-case-with-digits/generate.go deleted file mode 100644 index 4b4d2e44e6..0000000000 --- a/internal/test/outputoptions/name-normalizer/to-camel-case-with-digits/generate.go +++ /dev/null @@ -1,3 +0,0 @@ -package tocamelcasewithdigits - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml ../spec.yaml diff --git a/internal/test/outputoptions/name-normalizer/to-camel-case-with-digits/name_normalizer.gen.go b/internal/test/outputoptions/name-normalizer/to-camel-case-with-digits/name_normalizer.gen.go deleted file mode 100644 index 206ddbf64d..0000000000 --- a/internal/test/outputoptions/name-normalizer/to-camel-case-with-digits/name_normalizer.gen.go +++ /dev/null @@ -1,590 +0,0 @@ -// Package tocamelcasewithdigits provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package tocamelcasewithdigits - -import ( - "bytes" - "compress/gzip" - "context" - "encoding/base64" - "encoding/json" - "fmt" - "io" - "net/http" - "net/url" - "path" - "strings" - - "github.com/getkin/kin-openapi/openapi3" - "github.com/gorilla/mux" - "github.com/oapi-codegen/runtime" - openapi_types "github.com/oapi-codegen/runtime/types" -) - -// Error defines model for Error. -type Error struct { - // Code Error code - Code int32 `json:"code"` - - // Message Error message - Message string `json:"message"` -} - -// OneOf2Things Notice that the `things` is not capitalised -type OneOf2Things struct { - union json.RawMessage -} - -// OneOf2Things0 defines model for . -type OneOf2Things0 struct { - Id int `json:"id"` -} - -// OneOf2Things1 defines model for . -type OneOf2Things1 struct { - Id openapi_types.UUID `json:"id"` -} - -// Pet defines model for Pet. -type Pet struct { - // Name The name of the pet. - Name string `json:"name"` - - // Uuid The pet uuid. - Uuid string `json:"uuid"` -} - -// AsOneOf2Things0 returns the union data inside the OneOf2Things as a OneOf2Things0 -func (t OneOf2Things) AsOneOf2Things0() (OneOf2Things0, error) { - var body OneOf2Things0 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromOneOf2Things0 overwrites any union data inside the OneOf2Things as the provided OneOf2Things0 -func (t *OneOf2Things) FromOneOf2Things0(v OneOf2Things0) error { - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeOneOf2Things0 performs a merge with any union data inside the OneOf2Things, using the provided OneOf2Things0 -func (t *OneOf2Things) MergeOneOf2Things0(v OneOf2Things0) error { - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -// AsOneOf2Things1 returns the union data inside the OneOf2Things as a OneOf2Things1 -func (t OneOf2Things) AsOneOf2Things1() (OneOf2Things1, error) { - var body OneOf2Things1 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromOneOf2Things1 overwrites any union data inside the OneOf2Things as the provided OneOf2Things1 -func (t *OneOf2Things) FromOneOf2Things1(v OneOf2Things1) error { - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeOneOf2Things1 performs a merge with any union data inside the OneOf2Things, using the provided OneOf2Things1 -func (t *OneOf2Things) MergeOneOf2Things1(v OneOf2Things1) error { - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -func (t OneOf2Things) MarshalJSON() ([]byte, error) { - b, err := t.union.MarshalJSON() - return b, err -} - -func (t *OneOf2Things) UnmarshalJSON(b []byte) error { - err := t.union.UnmarshalJSON(b) - return err -} - -// RequestEditorFn is the function signature for the RequestEditor callback function -type RequestEditorFn func(ctx context.Context, req *http.Request) error - -// Doer performs HTTP requests. -// -// The standard http.Client implements this interface. -type HttpRequestDoer interface { - Do(req *http.Request) (*http.Response, error) -} - -// Client which conforms to the OpenAPI3 specification for this service. -type Client struct { - // The endpoint of the server conforming to this interface, with scheme, - // https://api.deepmap.com for example. This can contain a path relative - // to the server, such as https://api.deepmap.com/dev-test, and all the - // paths in the swagger spec will be appended to the server. - Server string - - // Doer for performing requests, typically a *http.Client with any - // customized settings, such as certificate chains. - Client HttpRequestDoer - - // A list of callbacks for modifying requests which are generated before sending over - // the network. - RequestEditors []RequestEditorFn -} - -// ClientOption allows setting custom parameters during construction -type ClientOption func(*Client) error - -// Creates a new Client, with reasonable defaults -func NewClient(server string, opts ...ClientOption) (*Client, error) { - // create a client with sane default values - client := Client{ - Server: server, - } - // mutate client and add all optional params - for _, o := range opts { - if err := o(&client); err != nil { - return nil, err - } - } - // ensure the server URL always has a trailing slash - if !strings.HasSuffix(client.Server, "/") { - client.Server += "/" - } - // create httpClient, if not already present - if client.Client == nil { - client.Client = &http.Client{} - } - return &client, nil -} - -// WithHTTPClient allows overriding the default Doer, which is -// automatically created using http.Client. This is useful for tests. -func WithHTTPClient(doer HttpRequestDoer) ClientOption { - return func(c *Client) error { - c.Client = doer - return nil - } -} - -// WithRequestEditorFn allows setting up a callback function, which will be -// called right before sending the request. This can be used to mutate the request. -func WithRequestEditorFn(fn RequestEditorFn) ClientOption { - return func(c *Client) error { - c.RequestEditors = append(c.RequestEditors, fn) - return nil - } -} - -// The interface specification for the client above. -type ClientInterface interface { - // GetHttpPet request - GetHttpPet(ctx context.Context, petId string, reqEditors ...RequestEditorFn) (*http.Response, error) -} - -func (c *Client) GetHttpPet(ctx context.Context, petId string, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewGetHttpPetRequest(c.Server, petId) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -// NewGetHttpPetRequest generates requests for GetHttpPet -func NewGetHttpPetRequest(server string, petId string) (*http.Request, error) { - var err error - - var pathParam0 string - - pathParam0, err = runtime.StyleParamWithOptions("simple", false, "petId", petId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) - if err != nil { - return nil, err - } - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/api/pets/%s", pathParam0) - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -func (c *Client) applyEditors(ctx context.Context, req *http.Request, additionalEditors []RequestEditorFn) error { - for _, r := range c.RequestEditors { - if err := r(ctx, req); err != nil { - return err - } - } - for _, r := range additionalEditors { - if err := r(ctx, req); err != nil { - return err - } - } - return nil -} - -// ClientWithResponses builds on ClientInterface to offer response payloads -type ClientWithResponses struct { - ClientInterface -} - -// NewClientWithResponses creates a new ClientWithResponses, which wraps -// Client with return type handling -func NewClientWithResponses(server string, opts ...ClientOption) (*ClientWithResponses, error) { - client, err := NewClient(server, opts...) - if err != nil { - return nil, err - } - return &ClientWithResponses{client}, nil -} - -// WithBaseURL overrides the baseURL. -func WithBaseURL(baseURL string) ClientOption { - return func(c *Client) error { - newBaseURL, err := url.Parse(baseURL) - if err != nil { - return err - } - c.Server = newBaseURL.String() - return nil - } -} - -// ClientWithResponsesInterface is the interface specification for the client with responses above. -type ClientWithResponsesInterface interface { - // GetHttpPetWithResponse request - GetHttpPetWithResponse(ctx context.Context, petId string, reqEditors ...RequestEditorFn) (*GetHttpPetResponse, error) -} - -type GetHttpPetResponse struct { - Body []byte - HTTPResponse *http.Response - JSON200 *Pet -} - -// Status returns HTTPResponse.Status -func (r GetHttpPetResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r GetHttpPetResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -// GetHttpPetWithResponse request returning *GetHttpPetResponse -func (c *ClientWithResponses) GetHttpPetWithResponse(ctx context.Context, petId string, reqEditors ...RequestEditorFn) (*GetHttpPetResponse, error) { - rsp, err := c.GetHttpPet(ctx, petId, reqEditors...) - if err != nil { - return nil, err - } - return ParseGetHttpPetResponse(rsp) -} - -// ParseGetHttpPetResponse parses an HTTP response from a GetHttpPetWithResponse call -func ParseGetHttpPetResponse(rsp *http.Response) (*GetHttpPetResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &GetHttpPetResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest Pet - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON200 = &dest - - } - - return response, nil -} - -// ServerInterface represents all server handlers. -type ServerInterface interface { - // Get pet given identifier. - // (GET /api/pets/{petId}) - GetHttpPet(w http.ResponseWriter, r *http.Request, petId string) -} - -// ServerInterfaceWrapper converts contexts to parameters. -type ServerInterfaceWrapper struct { - Handler ServerInterface - HandlerMiddlewares []MiddlewareFunc - ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) -} - -type MiddlewareFunc func(http.Handler) http.Handler - -// GetHttpPet operation middleware -func (siw *ServerInterfaceWrapper) GetHttpPet(w http.ResponseWriter, r *http.Request) { - - var err error - - // ------------- Path parameter "petId" ------------- - var petId string - - err = runtime.BindStyledParameterWithOptions("simple", "petId", mux.Vars(r)["petId"], &petId, runtime.BindStyledParameterOptions{Explode: false, Required: true, Type: "string", Format: ""}) - if err != nil { - siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "petId", Err: err}) - return - } - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.GetHttpPet(w, r, petId) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -type UnescapedCookieParamError struct { - ParamName string - Err error -} - -func (e *UnescapedCookieParamError) Error() string { - return fmt.Sprintf("error unescaping cookie parameter '%s'", e.ParamName) -} - -func (e *UnescapedCookieParamError) Unwrap() error { - return e.Err -} - -type UnmarshalingParamError struct { - ParamName string - Err error -} - -func (e *UnmarshalingParamError) Error() string { - return fmt.Sprintf("Error unmarshaling parameter %s as JSON: %s", e.ParamName, e.Err.Error()) -} - -func (e *UnmarshalingParamError) Unwrap() error { - return e.Err -} - -type RequiredParamError struct { - ParamName string -} - -func (e *RequiredParamError) Error() string { - return fmt.Sprintf("Query argument %s is required, but not found", e.ParamName) -} - -type RequiredHeaderError struct { - ParamName string - Err error -} - -func (e *RequiredHeaderError) Error() string { - return fmt.Sprintf("Header parameter %s is required, but not found", e.ParamName) -} - -func (e *RequiredHeaderError) Unwrap() error { - return e.Err -} - -type InvalidParamFormatError struct { - ParamName string - Err error -} - -func (e *InvalidParamFormatError) Error() string { - return fmt.Sprintf("Invalid format for parameter %s: %s", e.ParamName, e.Err.Error()) -} - -func (e *InvalidParamFormatError) Unwrap() error { - return e.Err -} - -type TooManyValuesForParamError struct { - ParamName string - Count int -} - -func (e *TooManyValuesForParamError) Error() string { - return fmt.Sprintf("Expected one value for %s, got %d", e.ParamName, e.Count) -} - -// Handler creates http.Handler with routing matching OpenAPI spec. -func Handler(si ServerInterface) http.Handler { - return HandlerWithOptions(si, GorillaServerOptions{}) -} - -type GorillaServerOptions struct { - BaseURL string - BaseRouter *mux.Router - Middlewares []MiddlewareFunc - ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) -} - -// HandlerFromMux creates http.Handler with routing matching OpenAPI spec based on the provided mux. -func HandlerFromMux(si ServerInterface, r *mux.Router) http.Handler { - return HandlerWithOptions(si, GorillaServerOptions{ - BaseRouter: r, - }) -} - -func HandlerFromMuxWithBaseURL(si ServerInterface, r *mux.Router, baseURL string) http.Handler { - return HandlerWithOptions(si, GorillaServerOptions{ - BaseURL: baseURL, - BaseRouter: r, - }) -} - -// HandlerWithOptions creates http.Handler with additional options -func HandlerWithOptions(si ServerInterface, options GorillaServerOptions) http.Handler { - r := options.BaseRouter - - if r == nil { - r = mux.NewRouter() - } - if options.ErrorHandlerFunc == nil { - options.ErrorHandlerFunc = func(w http.ResponseWriter, r *http.Request, err error) { - http.Error(w, err.Error(), http.StatusBadRequest) - } - } - wrapper := ServerInterfaceWrapper{ - Handler: si, - HandlerMiddlewares: options.Middlewares, - ErrorHandlerFunc: options.ErrorHandlerFunc, - } - - r.HandleFunc(options.BaseURL+"/api/pets/{petId}", wrapper.GetHttpPet).Methods("GET") - - return r -} - -// Base64 encoded, gzipped, json marshaled Swagger object -var swaggerSpec = []string{ - - "H4sIAAAAAAAC/4RTzY7TMBB+FWvgaJLSveW+gr2wHLitKtXEk2RWiW3sScVS5d3R2G0pbVe9tI5n/Pn7", - "8eyh9VPwDh0naPaQ2gEnk5ePMfooixB9wMiEebv1FuXfYmojBSbvoCnNKtc0dD5OhqEBcvywBg38FrB8", - "Yo8RFg0TpmT6d4GO5dPRxJFcD8uiIeKvmSJaaF7gcOGxfbNoeHb43K15INena/hvnqlFxYNhxQOqbWnc", - "KkrKeVatCcRmpIQWNHjBgubl0gOy8nup6oIbWdic+Pufr9gyLPo21MmxeSZ7V/VNZNH+Hfk6MGemGz7/", - "GFBJRfkuGxGQq+uLdSF083RAVlKt7vI9iMpErolLN7nOZ0uJR6k9/jZTGDE/KNX5WLISgE9OrBrpD8at", - "8jOHmZUvtDTsMKZC8HO1qlbC3wd0JhA08JC3NATDQzamNoHqgJzqfUB+sots9sVCMdAI6pOFBr4gf2UO", - "Yq+cj2ZCxpjyyyC5TjCPChvIaHDuAccZ9WG4zp7Oya+NNKfgXSqZrVerMmuO0WVCJoSR2kypfk2icX+G", - "9zFiBw18qP9Nc30Y5VpYZ5P/j3BnRrISYo4rzdNk4lvRmqPtaYdOkUXH1BHGSkCWvwEAAP//D5F1qDAE", - "AAA=", -} - -// GetSwagger returns the content of the embedded swagger specification file -// or error if failed to decode -func decodeSpec() ([]byte, error) { - zipped, err := base64.StdEncoding.DecodeString(strings.Join(swaggerSpec, "")) - if err != nil { - return nil, fmt.Errorf("error base64 decoding spec: %w", err) - } - zr, err := gzip.NewReader(bytes.NewReader(zipped)) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - var buf bytes.Buffer - _, err = buf.ReadFrom(zr) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - - return buf.Bytes(), nil -} - -var rawSpec = decodeSpecCached() - -// a naive cached of a decoded swagger spec -func decodeSpecCached() func() ([]byte, error) { - data, err := decodeSpec() - return func() ([]byte, error) { - return data, err - } -} - -// Constructs a synthetic filesystem for resolving external references when loading openapi specifications. -func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { - res := make(map[string]func() ([]byte, error)) - if len(pathToFile) > 0 { - res[pathToFile] = rawSpec - } - - return res -} - -// GetSwagger returns the Swagger specification corresponding to the generated code -// in this file. The external references of Swagger specification are resolved. -// The logic of resolving external references is tightly connected to "import-mapping" feature. -// Externally referenced files must be embedded in the corresponding golang packages. -// Urls can be supported but this task was out of the scope. -func GetSwagger() (swagger *openapi3.T, err error) { - resolvePath := PathToRawSpec("") - - loader := openapi3.NewLoader() - loader.IsExternalRefsAllowed = true - loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() - pathToFile = path.Clean(pathToFile) - getSpec, ok := resolvePath[pathToFile] - if !ok { - err1 := fmt.Errorf("path not found: %s", pathToFile) - return nil, err1 - } - return getSpec() - } - var specData []byte - specData, err = rawSpec() - if err != nil { - return - } - swagger, err = loader.LoadFromData(specData) - if err != nil { - return - } - return -} diff --git a/internal/test/outputoptions/name-normalizer/to-camel-case-with-digits/name_normalizer_test.go b/internal/test/outputoptions/name-normalizer/to-camel-case-with-digits/name_normalizer_test.go deleted file mode 100644 index 32a01436e9..0000000000 --- a/internal/test/outputoptions/name-normalizer/to-camel-case-with-digits/name_normalizer_test.go +++ /dev/null @@ -1,24 +0,0 @@ -package tocamelcasewithdigits - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestGenCodeHasCorrectNames(t *testing.T) { - pet := &Pet{} - assert.Equal(t, "", pet.Name) - assert.Equal(t, "", pet.Uuid) - - uri := "https://my-api.com/some-base-url/v1/" - client, err := NewClient(uri) - assert.Nil(t, err) - assert.NotNil(t, client.GetHttpPet) - - server := &ServerInterfaceWrapper{} - assert.NotNil(t, server.GetHttpPet) - - oneOf := OneOf2Things{} - assert.Zero(t, oneOf) -} diff --git a/internal/test/outputoptions/name-normalizer/to-camel-case-with-initialisms/config.yaml b/internal/test/outputoptions/name-normalizer/to-camel-case-with-initialisms/config.yaml deleted file mode 100644 index 63e903aeaf..0000000000 --- a/internal/test/outputoptions/name-normalizer/to-camel-case-with-initialisms/config.yaml +++ /dev/null @@ -1,11 +0,0 @@ -# yaml-language-server: $schema=../../../../../configuration-schema.json -package: tocamelcasewithinitialisms -generate: - gorilla-server: true - client: true - models: true - embedded-spec: true -output: name_normalizer.gen.go -output-options: - skip-prune: true - name-normalizer: ToCamelCaseWithInitialisms diff --git a/internal/test/outputoptions/name-normalizer/to-camel-case-with-initialisms/generate.go b/internal/test/outputoptions/name-normalizer/to-camel-case-with-initialisms/generate.go deleted file mode 100644 index 5f65491318..0000000000 --- a/internal/test/outputoptions/name-normalizer/to-camel-case-with-initialisms/generate.go +++ /dev/null @@ -1,3 +0,0 @@ -package tocamelcasewithinitialisms - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml ../spec.yaml diff --git a/internal/test/outputoptions/name-normalizer/to-camel-case-with-initialisms/name_normalizer.gen.go b/internal/test/outputoptions/name-normalizer/to-camel-case-with-initialisms/name_normalizer.gen.go deleted file mode 100644 index 6cf9d6e7fe..0000000000 --- a/internal/test/outputoptions/name-normalizer/to-camel-case-with-initialisms/name_normalizer.gen.go +++ /dev/null @@ -1,590 +0,0 @@ -// Package tocamelcasewithinitialisms provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package tocamelcasewithinitialisms - -import ( - "bytes" - "compress/gzip" - "context" - "encoding/base64" - "encoding/json" - "fmt" - "io" - "net/http" - "net/url" - "path" - "strings" - - "github.com/getkin/kin-openapi/openapi3" - "github.com/gorilla/mux" - "github.com/oapi-codegen/runtime" - openapi_types "github.com/oapi-codegen/runtime/types" -) - -// Error defines model for Error. -type Error struct { - // Code Error code - Code int32 `json:"code"` - - // Message Error message - Message string `json:"message"` -} - -// OneOf2Things Notice that the `things` is not capitalised -type OneOf2Things struct { - union json.RawMessage -} - -// OneOf2Things0 defines model for . -type OneOf2Things0 struct { - ID int `json:"id"` -} - -// OneOf2Things1 defines model for . -type OneOf2Things1 struct { - ID openapi_types.UUID `json:"id"` -} - -// Pet defines model for Pet. -type Pet struct { - // Name The name of the pet. - Name string `json:"name"` - - // UUID The pet uuid. - UUID string `json:"uuid"` -} - -// AsOneOf2Things0 returns the union data inside the OneOf2Things as a OneOf2Things0 -func (t OneOf2Things) AsOneOf2Things0() (OneOf2Things0, error) { - var body OneOf2Things0 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromOneOf2Things0 overwrites any union data inside the OneOf2Things as the provided OneOf2Things0 -func (t *OneOf2Things) FromOneOf2Things0(v OneOf2Things0) error { - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeOneOf2Things0 performs a merge with any union data inside the OneOf2Things, using the provided OneOf2Things0 -func (t *OneOf2Things) MergeOneOf2Things0(v OneOf2Things0) error { - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -// AsOneOf2Things1 returns the union data inside the OneOf2Things as a OneOf2Things1 -func (t OneOf2Things) AsOneOf2Things1() (OneOf2Things1, error) { - var body OneOf2Things1 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromOneOf2Things1 overwrites any union data inside the OneOf2Things as the provided OneOf2Things1 -func (t *OneOf2Things) FromOneOf2Things1(v OneOf2Things1) error { - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeOneOf2Things1 performs a merge with any union data inside the OneOf2Things, using the provided OneOf2Things1 -func (t *OneOf2Things) MergeOneOf2Things1(v OneOf2Things1) error { - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -func (t OneOf2Things) MarshalJSON() ([]byte, error) { - b, err := t.union.MarshalJSON() - return b, err -} - -func (t *OneOf2Things) UnmarshalJSON(b []byte) error { - err := t.union.UnmarshalJSON(b) - return err -} - -// RequestEditorFn is the function signature for the RequestEditor callback function -type RequestEditorFn func(ctx context.Context, req *http.Request) error - -// Doer performs HTTP requests. -// -// The standard http.Client implements this interface. -type HttpRequestDoer interface { - Do(req *http.Request) (*http.Response, error) -} - -// Client which conforms to the OpenAPI3 specification for this service. -type Client struct { - // The endpoint of the server conforming to this interface, with scheme, - // https://api.deepmap.com for example. This can contain a path relative - // to the server, such as https://api.deepmap.com/dev-test, and all the - // paths in the swagger spec will be appended to the server. - Server string - - // Doer for performing requests, typically a *http.Client with any - // customized settings, such as certificate chains. - Client HttpRequestDoer - - // A list of callbacks for modifying requests which are generated before sending over - // the network. - RequestEditors []RequestEditorFn -} - -// ClientOption allows setting custom parameters during construction -type ClientOption func(*Client) error - -// Creates a new Client, with reasonable defaults -func NewClient(server string, opts ...ClientOption) (*Client, error) { - // create a client with sane default values - client := Client{ - Server: server, - } - // mutate client and add all optional params - for _, o := range opts { - if err := o(&client); err != nil { - return nil, err - } - } - // ensure the server URL always has a trailing slash - if !strings.HasSuffix(client.Server, "/") { - client.Server += "/" - } - // create httpClient, if not already present - if client.Client == nil { - client.Client = &http.Client{} - } - return &client, nil -} - -// WithHTTPClient allows overriding the default Doer, which is -// automatically created using http.Client. This is useful for tests. -func WithHTTPClient(doer HttpRequestDoer) ClientOption { - return func(c *Client) error { - c.Client = doer - return nil - } -} - -// WithRequestEditorFn allows setting up a callback function, which will be -// called right before sending the request. This can be used to mutate the request. -func WithRequestEditorFn(fn RequestEditorFn) ClientOption { - return func(c *Client) error { - c.RequestEditors = append(c.RequestEditors, fn) - return nil - } -} - -// The interface specification for the client above. -type ClientInterface interface { - // GetHTTPPet request - GetHTTPPet(ctx context.Context, petID string, reqEditors ...RequestEditorFn) (*http.Response, error) -} - -func (c *Client) GetHTTPPet(ctx context.Context, petID string, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewGetHTTPPetRequest(c.Server, petID) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -// NewGetHTTPPetRequest generates requests for GetHTTPPet -func NewGetHTTPPetRequest(server string, petID string) (*http.Request, error) { - var err error - - var pathParam0 string - - pathParam0, err = runtime.StyleParamWithOptions("simple", false, "petId", petID, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) - if err != nil { - return nil, err - } - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/api/pets/%s", pathParam0) - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -func (c *Client) applyEditors(ctx context.Context, req *http.Request, additionalEditors []RequestEditorFn) error { - for _, r := range c.RequestEditors { - if err := r(ctx, req); err != nil { - return err - } - } - for _, r := range additionalEditors { - if err := r(ctx, req); err != nil { - return err - } - } - return nil -} - -// ClientWithResponses builds on ClientInterface to offer response payloads -type ClientWithResponses struct { - ClientInterface -} - -// NewClientWithResponses creates a new ClientWithResponses, which wraps -// Client with return type handling -func NewClientWithResponses(server string, opts ...ClientOption) (*ClientWithResponses, error) { - client, err := NewClient(server, opts...) - if err != nil { - return nil, err - } - return &ClientWithResponses{client}, nil -} - -// WithBaseURL overrides the baseURL. -func WithBaseURL(baseURL string) ClientOption { - return func(c *Client) error { - newBaseURL, err := url.Parse(baseURL) - if err != nil { - return err - } - c.Server = newBaseURL.String() - return nil - } -} - -// ClientWithResponsesInterface is the interface specification for the client with responses above. -type ClientWithResponsesInterface interface { - // GetHTTPPetWithResponse request - GetHTTPPetWithResponse(ctx context.Context, petID string, reqEditors ...RequestEditorFn) (*GetHTTPPetResponse, error) -} - -type GetHTTPPetResponse struct { - Body []byte - HTTPResponse *http.Response - JSON200 *Pet -} - -// Status returns HTTPResponse.Status -func (r GetHTTPPetResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r GetHTTPPetResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -// GetHTTPPetWithResponse request returning *GetHTTPPetResponse -func (c *ClientWithResponses) GetHTTPPetWithResponse(ctx context.Context, petID string, reqEditors ...RequestEditorFn) (*GetHTTPPetResponse, error) { - rsp, err := c.GetHTTPPet(ctx, petID, reqEditors...) - if err != nil { - return nil, err - } - return ParseGetHTTPPetResponse(rsp) -} - -// ParseGetHTTPPetResponse parses an HTTP response from a GetHTTPPetWithResponse call -func ParseGetHTTPPetResponse(rsp *http.Response) (*GetHTTPPetResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &GetHTTPPetResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest Pet - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON200 = &dest - - } - - return response, nil -} - -// ServerInterface represents all server handlers. -type ServerInterface interface { - // Get pet given identifier. - // (GET /api/pets/{petId}) - GetHTTPPet(w http.ResponseWriter, r *http.Request, petID string) -} - -// ServerInterfaceWrapper converts contexts to parameters. -type ServerInterfaceWrapper struct { - Handler ServerInterface - HandlerMiddlewares []MiddlewareFunc - ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) -} - -type MiddlewareFunc func(http.Handler) http.Handler - -// GetHTTPPet operation middleware -func (siw *ServerInterfaceWrapper) GetHTTPPet(w http.ResponseWriter, r *http.Request) { - - var err error - - // ------------- Path parameter "petId" ------------- - var petID string - - err = runtime.BindStyledParameterWithOptions("simple", "petId", mux.Vars(r)["petId"], &petID, runtime.BindStyledParameterOptions{Explode: false, Required: true, Type: "string", Format: ""}) - if err != nil { - siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "petId", Err: err}) - return - } - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.GetHTTPPet(w, r, petID) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -type UnescapedCookieParamError struct { - ParamName string - Err error -} - -func (e *UnescapedCookieParamError) Error() string { - return fmt.Sprintf("error unescaping cookie parameter '%s'", e.ParamName) -} - -func (e *UnescapedCookieParamError) Unwrap() error { - return e.Err -} - -type UnmarshalingParamError struct { - ParamName string - Err error -} - -func (e *UnmarshalingParamError) Error() string { - return fmt.Sprintf("Error unmarshaling parameter %s as JSON: %s", e.ParamName, e.Err.Error()) -} - -func (e *UnmarshalingParamError) Unwrap() error { - return e.Err -} - -type RequiredParamError struct { - ParamName string -} - -func (e *RequiredParamError) Error() string { - return fmt.Sprintf("Query argument %s is required, but not found", e.ParamName) -} - -type RequiredHeaderError struct { - ParamName string - Err error -} - -func (e *RequiredHeaderError) Error() string { - return fmt.Sprintf("Header parameter %s is required, but not found", e.ParamName) -} - -func (e *RequiredHeaderError) Unwrap() error { - return e.Err -} - -type InvalidParamFormatError struct { - ParamName string - Err error -} - -func (e *InvalidParamFormatError) Error() string { - return fmt.Sprintf("Invalid format for parameter %s: %s", e.ParamName, e.Err.Error()) -} - -func (e *InvalidParamFormatError) Unwrap() error { - return e.Err -} - -type TooManyValuesForParamError struct { - ParamName string - Count int -} - -func (e *TooManyValuesForParamError) Error() string { - return fmt.Sprintf("Expected one value for %s, got %d", e.ParamName, e.Count) -} - -// Handler creates http.Handler with routing matching OpenAPI spec. -func Handler(si ServerInterface) http.Handler { - return HandlerWithOptions(si, GorillaServerOptions{}) -} - -type GorillaServerOptions struct { - BaseURL string - BaseRouter *mux.Router - Middlewares []MiddlewareFunc - ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) -} - -// HandlerFromMux creates http.Handler with routing matching OpenAPI spec based on the provided mux. -func HandlerFromMux(si ServerInterface, r *mux.Router) http.Handler { - return HandlerWithOptions(si, GorillaServerOptions{ - BaseRouter: r, - }) -} - -func HandlerFromMuxWithBaseURL(si ServerInterface, r *mux.Router, baseURL string) http.Handler { - return HandlerWithOptions(si, GorillaServerOptions{ - BaseURL: baseURL, - BaseRouter: r, - }) -} - -// HandlerWithOptions creates http.Handler with additional options -func HandlerWithOptions(si ServerInterface, options GorillaServerOptions) http.Handler { - r := options.BaseRouter - - if r == nil { - r = mux.NewRouter() - } - if options.ErrorHandlerFunc == nil { - options.ErrorHandlerFunc = func(w http.ResponseWriter, r *http.Request, err error) { - http.Error(w, err.Error(), http.StatusBadRequest) - } - } - wrapper := ServerInterfaceWrapper{ - Handler: si, - HandlerMiddlewares: options.Middlewares, - ErrorHandlerFunc: options.ErrorHandlerFunc, - } - - r.HandleFunc(options.BaseURL+"/api/pets/{petId}", wrapper.GetHTTPPet).Methods("GET") - - return r -} - -// Base64 encoded, gzipped, json marshaled Swagger object -var swaggerSpec = []string{ - - "H4sIAAAAAAAC/4RTTW/bPAz+KwLf96jZWXrzvdh6WXvIrQgQzaJtFrakSXSwLvB/HyglWZZk6CWRRerR", - "8yEeoPVT8A4dJ2gOkNoBJ5OXjzH6KIsQfcDIhHm79Rbl32JqIwUm76ApzSrXNHQ+ToahAXL8sAYN/B6w", - "fGKPERYNE6Zk+n8Cncrno4kjuR6WRUPEHzNFtNC8wvHCU/t20fDs8Llb80CuT7fw3zxTi4oHw4oHVLvS", - "uFOUlPOsWhOIzUgJLWjwggXN67UHZOX3WtUVN7KwPfP339+wZVj0faizY/NM9kPVd5FF+wvybWDOTHd8", - "3gyopKJ8l40IyNXtxboQuns6ICupVh/yPYrKRG6JSze5zmdLiUepPf40UxgxPyjV+ViyEoBPTqwa6RfG", - "nfIzh5mVL7Q07DGmQvBztapWwt8HdCYQNPCQtzQEw0M2pjaB6oCc6kNAfrKLbPbFQjHQCOqThQa+IH/d", - "bF7EXjkfzYSMMeWXQXKdYJ4UNpDR4NIDjjPq43BdPJ2zX1tpTsG7VDJbr1Zl1hyjy4RMCCO1mVL9lkTj", - "4QLv/4gdNPBf/Wea6+Mo18I6m/x3hHszkpUQc1xpniYT34vWHG1Pe3SKLDqmjjBWArL8DgAA//+VcR3v", - "MAQAAA==", -} - -// GetSwagger returns the content of the embedded swagger specification file -// or error if failed to decode -func decodeSpec() ([]byte, error) { - zipped, err := base64.StdEncoding.DecodeString(strings.Join(swaggerSpec, "")) - if err != nil { - return nil, fmt.Errorf("error base64 decoding spec: %w", err) - } - zr, err := gzip.NewReader(bytes.NewReader(zipped)) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - var buf bytes.Buffer - _, err = buf.ReadFrom(zr) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - - return buf.Bytes(), nil -} - -var rawSpec = decodeSpecCached() - -// a naive cached of a decoded swagger spec -func decodeSpecCached() func() ([]byte, error) { - data, err := decodeSpec() - return func() ([]byte, error) { - return data, err - } -} - -// Constructs a synthetic filesystem for resolving external references when loading openapi specifications. -func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { - res := make(map[string]func() ([]byte, error)) - if len(pathToFile) > 0 { - res[pathToFile] = rawSpec - } - - return res -} - -// GetSwagger returns the Swagger specification corresponding to the generated code -// in this file. The external references of Swagger specification are resolved. -// The logic of resolving external references is tightly connected to "import-mapping" feature. -// Externally referenced files must be embedded in the corresponding golang packages. -// Urls can be supported but this task was out of the scope. -func GetSwagger() (swagger *openapi3.T, err error) { - resolvePath := PathToRawSpec("") - - loader := openapi3.NewLoader() - loader.IsExternalRefsAllowed = true - loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() - pathToFile = path.Clean(pathToFile) - getSpec, ok := resolvePath[pathToFile] - if !ok { - err1 := fmt.Errorf("path not found: %s", pathToFile) - return nil, err1 - } - return getSpec() - } - var specData []byte - specData, err = rawSpec() - if err != nil { - return - } - swagger, err = loader.LoadFromData(specData) - if err != nil { - return - } - return -} diff --git a/internal/test/outputoptions/name-normalizer/to-camel-case-with-initialisms/name_normalizer_test.go b/internal/test/outputoptions/name-normalizer/to-camel-case-with-initialisms/name_normalizer_test.go deleted file mode 100644 index fea7b84dc5..0000000000 --- a/internal/test/outputoptions/name-normalizer/to-camel-case-with-initialisms/name_normalizer_test.go +++ /dev/null @@ -1,24 +0,0 @@ -package tocamelcasewithinitialisms - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestGenCodeHasCorrectNames(t *testing.T) { - pet := &Pet{} - assert.Equal(t, "", pet.Name) - assert.Equal(t, "", pet.UUID) - - uri := "https://my-api.com/some-base-url/v1/" - client, err := NewClient(uri) - assert.Nil(t, err) - assert.NotNil(t, client.GetHTTPPet) - - server := &ServerInterfaceWrapper{} - assert.NotNil(t, server.GetHTTPPet) - - oneOf := OneOf2Things{} - assert.Zero(t, oneOf) -} diff --git a/internal/test/outputoptions/name-normalizer/to-camel-case/config.yaml b/internal/test/outputoptions/name-normalizer/to-camel-case/config.yaml deleted file mode 100644 index b80cdda8eb..0000000000 --- a/internal/test/outputoptions/name-normalizer/to-camel-case/config.yaml +++ /dev/null @@ -1,11 +0,0 @@ -# yaml-language-server: $schema=../../../../../configuration-schema.json -package: tocamelcase -generate: - gorilla-server: true - client: true - models: true - embedded-spec: true -output: name_normalizer.gen.go -output-options: - skip-prune: true - name-normalizer: ToCamelCase diff --git a/internal/test/outputoptions/name-normalizer/to-camel-case/generate.go b/internal/test/outputoptions/name-normalizer/to-camel-case/generate.go deleted file mode 100644 index a6c179b79d..0000000000 --- a/internal/test/outputoptions/name-normalizer/to-camel-case/generate.go +++ /dev/null @@ -1,3 +0,0 @@ -package tocamelcase - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml ../spec.yaml diff --git a/internal/test/outputoptions/name-normalizer/to-camel-case/name_normalizer.gen.go b/internal/test/outputoptions/name-normalizer/to-camel-case/name_normalizer.gen.go deleted file mode 100644 index e34d1c4663..0000000000 --- a/internal/test/outputoptions/name-normalizer/to-camel-case/name_normalizer.gen.go +++ /dev/null @@ -1,590 +0,0 @@ -// Package tocamelcase provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package tocamelcase - -import ( - "bytes" - "compress/gzip" - "context" - "encoding/base64" - "encoding/json" - "fmt" - "io" - "net/http" - "net/url" - "path" - "strings" - - "github.com/getkin/kin-openapi/openapi3" - "github.com/gorilla/mux" - "github.com/oapi-codegen/runtime" - openapi_types "github.com/oapi-codegen/runtime/types" -) - -// Error defines model for Error. -type Error struct { - // Code Error code - Code int32 `json:"code"` - - // Message Error message - Message string `json:"message"` -} - -// OneOf2things Notice that the `things` is not capitalised -type OneOf2things struct { - union json.RawMessage -} - -// OneOf2things0 defines model for . -type OneOf2things0 struct { - Id int `json:"id"` -} - -// OneOf2things1 defines model for . -type OneOf2things1 struct { - Id openapi_types.UUID `json:"id"` -} - -// Pet defines model for Pet. -type Pet struct { - // Name The name of the pet. - Name string `json:"name"` - - // Uuid The pet uuid. - Uuid string `json:"uuid"` -} - -// AsOneOf2things0 returns the union data inside the OneOf2things as a OneOf2things0 -func (t OneOf2things) AsOneOf2things0() (OneOf2things0, error) { - var body OneOf2things0 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromOneOf2things0 overwrites any union data inside the OneOf2things as the provided OneOf2things0 -func (t *OneOf2things) FromOneOf2things0(v OneOf2things0) error { - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeOneOf2things0 performs a merge with any union data inside the OneOf2things, using the provided OneOf2things0 -func (t *OneOf2things) MergeOneOf2things0(v OneOf2things0) error { - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -// AsOneOf2things1 returns the union data inside the OneOf2things as a OneOf2things1 -func (t OneOf2things) AsOneOf2things1() (OneOf2things1, error) { - var body OneOf2things1 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromOneOf2things1 overwrites any union data inside the OneOf2things as the provided OneOf2things1 -func (t *OneOf2things) FromOneOf2things1(v OneOf2things1) error { - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeOneOf2things1 performs a merge with any union data inside the OneOf2things, using the provided OneOf2things1 -func (t *OneOf2things) MergeOneOf2things1(v OneOf2things1) error { - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -func (t OneOf2things) MarshalJSON() ([]byte, error) { - b, err := t.union.MarshalJSON() - return b, err -} - -func (t *OneOf2things) UnmarshalJSON(b []byte) error { - err := t.union.UnmarshalJSON(b) - return err -} - -// RequestEditorFn is the function signature for the RequestEditor callback function -type RequestEditorFn func(ctx context.Context, req *http.Request) error - -// Doer performs HTTP requests. -// -// The standard http.Client implements this interface. -type HttpRequestDoer interface { - Do(req *http.Request) (*http.Response, error) -} - -// Client which conforms to the OpenAPI3 specification for this service. -type Client struct { - // The endpoint of the server conforming to this interface, with scheme, - // https://api.deepmap.com for example. This can contain a path relative - // to the server, such as https://api.deepmap.com/dev-test, and all the - // paths in the swagger spec will be appended to the server. - Server string - - // Doer for performing requests, typically a *http.Client with any - // customized settings, such as certificate chains. - Client HttpRequestDoer - - // A list of callbacks for modifying requests which are generated before sending over - // the network. - RequestEditors []RequestEditorFn -} - -// ClientOption allows setting custom parameters during construction -type ClientOption func(*Client) error - -// Creates a new Client, with reasonable defaults -func NewClient(server string, opts ...ClientOption) (*Client, error) { - // create a client with sane default values - client := Client{ - Server: server, - } - // mutate client and add all optional params - for _, o := range opts { - if err := o(&client); err != nil { - return nil, err - } - } - // ensure the server URL always has a trailing slash - if !strings.HasSuffix(client.Server, "/") { - client.Server += "/" - } - // create httpClient, if not already present - if client.Client == nil { - client.Client = &http.Client{} - } - return &client, nil -} - -// WithHTTPClient allows overriding the default Doer, which is -// automatically created using http.Client. This is useful for tests. -func WithHTTPClient(doer HttpRequestDoer) ClientOption { - return func(c *Client) error { - c.Client = doer - return nil - } -} - -// WithRequestEditorFn allows setting up a callback function, which will be -// called right before sending the request. This can be used to mutate the request. -func WithRequestEditorFn(fn RequestEditorFn) ClientOption { - return func(c *Client) error { - c.RequestEditors = append(c.RequestEditors, fn) - return nil - } -} - -// The interface specification for the client above. -type ClientInterface interface { - // GetHttpPet request - GetHttpPet(ctx context.Context, petId string, reqEditors ...RequestEditorFn) (*http.Response, error) -} - -func (c *Client) GetHttpPet(ctx context.Context, petId string, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewGetHttpPetRequest(c.Server, petId) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -// NewGetHttpPetRequest generates requests for GetHttpPet -func NewGetHttpPetRequest(server string, petId string) (*http.Request, error) { - var err error - - var pathParam0 string - - pathParam0, err = runtime.StyleParamWithOptions("simple", false, "petId", petId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) - if err != nil { - return nil, err - } - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/api/pets/%s", pathParam0) - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -func (c *Client) applyEditors(ctx context.Context, req *http.Request, additionalEditors []RequestEditorFn) error { - for _, r := range c.RequestEditors { - if err := r(ctx, req); err != nil { - return err - } - } - for _, r := range additionalEditors { - if err := r(ctx, req); err != nil { - return err - } - } - return nil -} - -// ClientWithResponses builds on ClientInterface to offer response payloads -type ClientWithResponses struct { - ClientInterface -} - -// NewClientWithResponses creates a new ClientWithResponses, which wraps -// Client with return type handling -func NewClientWithResponses(server string, opts ...ClientOption) (*ClientWithResponses, error) { - client, err := NewClient(server, opts...) - if err != nil { - return nil, err - } - return &ClientWithResponses{client}, nil -} - -// WithBaseURL overrides the baseURL. -func WithBaseURL(baseURL string) ClientOption { - return func(c *Client) error { - newBaseURL, err := url.Parse(baseURL) - if err != nil { - return err - } - c.Server = newBaseURL.String() - return nil - } -} - -// ClientWithResponsesInterface is the interface specification for the client with responses above. -type ClientWithResponsesInterface interface { - // GetHttpPetWithResponse request - GetHttpPetWithResponse(ctx context.Context, petId string, reqEditors ...RequestEditorFn) (*GetHttpPetResponse, error) -} - -type GetHttpPetResponse struct { - Body []byte - HTTPResponse *http.Response - JSON200 *Pet -} - -// Status returns HTTPResponse.Status -func (r GetHttpPetResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r GetHttpPetResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -// GetHttpPetWithResponse request returning *GetHttpPetResponse -func (c *ClientWithResponses) GetHttpPetWithResponse(ctx context.Context, petId string, reqEditors ...RequestEditorFn) (*GetHttpPetResponse, error) { - rsp, err := c.GetHttpPet(ctx, petId, reqEditors...) - if err != nil { - return nil, err - } - return ParseGetHttpPetResponse(rsp) -} - -// ParseGetHttpPetResponse parses an HTTP response from a GetHttpPetWithResponse call -func ParseGetHttpPetResponse(rsp *http.Response) (*GetHttpPetResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &GetHttpPetResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest Pet - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON200 = &dest - - } - - return response, nil -} - -// ServerInterface represents all server handlers. -type ServerInterface interface { - // Get pet given identifier. - // (GET /api/pets/{petId}) - GetHttpPet(w http.ResponseWriter, r *http.Request, petId string) -} - -// ServerInterfaceWrapper converts contexts to parameters. -type ServerInterfaceWrapper struct { - Handler ServerInterface - HandlerMiddlewares []MiddlewareFunc - ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) -} - -type MiddlewareFunc func(http.Handler) http.Handler - -// GetHttpPet operation middleware -func (siw *ServerInterfaceWrapper) GetHttpPet(w http.ResponseWriter, r *http.Request) { - - var err error - - // ------------- Path parameter "petId" ------------- - var petId string - - err = runtime.BindStyledParameterWithOptions("simple", "petId", mux.Vars(r)["petId"], &petId, runtime.BindStyledParameterOptions{Explode: false, Required: true, Type: "string", Format: ""}) - if err != nil { - siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "petId", Err: err}) - return - } - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.GetHttpPet(w, r, petId) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -type UnescapedCookieParamError struct { - ParamName string - Err error -} - -func (e *UnescapedCookieParamError) Error() string { - return fmt.Sprintf("error unescaping cookie parameter '%s'", e.ParamName) -} - -func (e *UnescapedCookieParamError) Unwrap() error { - return e.Err -} - -type UnmarshalingParamError struct { - ParamName string - Err error -} - -func (e *UnmarshalingParamError) Error() string { - return fmt.Sprintf("Error unmarshaling parameter %s as JSON: %s", e.ParamName, e.Err.Error()) -} - -func (e *UnmarshalingParamError) Unwrap() error { - return e.Err -} - -type RequiredParamError struct { - ParamName string -} - -func (e *RequiredParamError) Error() string { - return fmt.Sprintf("Query argument %s is required, but not found", e.ParamName) -} - -type RequiredHeaderError struct { - ParamName string - Err error -} - -func (e *RequiredHeaderError) Error() string { - return fmt.Sprintf("Header parameter %s is required, but not found", e.ParamName) -} - -func (e *RequiredHeaderError) Unwrap() error { - return e.Err -} - -type InvalidParamFormatError struct { - ParamName string - Err error -} - -func (e *InvalidParamFormatError) Error() string { - return fmt.Sprintf("Invalid format for parameter %s: %s", e.ParamName, e.Err.Error()) -} - -func (e *InvalidParamFormatError) Unwrap() error { - return e.Err -} - -type TooManyValuesForParamError struct { - ParamName string - Count int -} - -func (e *TooManyValuesForParamError) Error() string { - return fmt.Sprintf("Expected one value for %s, got %d", e.ParamName, e.Count) -} - -// Handler creates http.Handler with routing matching OpenAPI spec. -func Handler(si ServerInterface) http.Handler { - return HandlerWithOptions(si, GorillaServerOptions{}) -} - -type GorillaServerOptions struct { - BaseURL string - BaseRouter *mux.Router - Middlewares []MiddlewareFunc - ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) -} - -// HandlerFromMux creates http.Handler with routing matching OpenAPI spec based on the provided mux. -func HandlerFromMux(si ServerInterface, r *mux.Router) http.Handler { - return HandlerWithOptions(si, GorillaServerOptions{ - BaseRouter: r, - }) -} - -func HandlerFromMuxWithBaseURL(si ServerInterface, r *mux.Router, baseURL string) http.Handler { - return HandlerWithOptions(si, GorillaServerOptions{ - BaseURL: baseURL, - BaseRouter: r, - }) -} - -// HandlerWithOptions creates http.Handler with additional options -func HandlerWithOptions(si ServerInterface, options GorillaServerOptions) http.Handler { - r := options.BaseRouter - - if r == nil { - r = mux.NewRouter() - } - if options.ErrorHandlerFunc == nil { - options.ErrorHandlerFunc = func(w http.ResponseWriter, r *http.Request, err error) { - http.Error(w, err.Error(), http.StatusBadRequest) - } - } - wrapper := ServerInterfaceWrapper{ - Handler: si, - HandlerMiddlewares: options.Middlewares, - ErrorHandlerFunc: options.ErrorHandlerFunc, - } - - r.HandleFunc(options.BaseURL+"/api/pets/{petId}", wrapper.GetHttpPet).Methods("GET") - - return r -} - -// Base64 encoded, gzipped, json marshaled Swagger object -var swaggerSpec = []string{ - - "H4sIAAAAAAAC/4RTzY7TMBB+FWvgaJLSveW+gr2wHLitKtXEk2RWiW3sScVS5d3R2G0pbVe9tI5n/Pn7", - "8eyh9VPwDh0naPaQ2gEnk5ePMfooixB9wMiEebv1FuXfYmojBSbvoCnNKtc0dD5OhqEBcvywBg38FrB8", - "Yo8RFg0TpmT6d4GO5dPRxJFcD8uiIeKvmSJaaF7gcOGxfbNoeHb43K15INena/hvnqlFxYNhxQOqbWnc", - "KkrKeVatCcRmpIQWNHjBgubl0gOy8nup6oIbWdic+Pufr9gyLPo21MmxeSZ7V/VNZNH+Hfk6MGemGz7/", - "GFBJRfkuGxGQq+uLdSF083RAVlKt7vI9iMpErolLN7nOZ0uJR6k9/jZTGDE/KNX5WLISgE9OrBrpD8at", - "8jOHmZUvtDTsMKZC8HO1qlbC3wd0JhA08JC3NATDQzamNoHqgJzqfUB+sots9sVCMdAI6pOFBr4gf2UO", - "Yq+cj2ZCxpjyyyC5TjCPChvIaHDuAccZ9WG4zp7Oya+NNKfgXSqZrVerMmuO0WVCJoSR2kypfk2icX+G", - "9zFiBw18qP9Nc30Y5VpYZ5P/j3BnRrISYo4rzdNk4lvRmqPtaYdOkUXH1BHGSkCWvwEAAP//D5F1qDAE", - "AAA=", -} - -// GetSwagger returns the content of the embedded swagger specification file -// or error if failed to decode -func decodeSpec() ([]byte, error) { - zipped, err := base64.StdEncoding.DecodeString(strings.Join(swaggerSpec, "")) - if err != nil { - return nil, fmt.Errorf("error base64 decoding spec: %w", err) - } - zr, err := gzip.NewReader(bytes.NewReader(zipped)) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - var buf bytes.Buffer - _, err = buf.ReadFrom(zr) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - - return buf.Bytes(), nil -} - -var rawSpec = decodeSpecCached() - -// a naive cached of a decoded swagger spec -func decodeSpecCached() func() ([]byte, error) { - data, err := decodeSpec() - return func() ([]byte, error) { - return data, err - } -} - -// Constructs a synthetic filesystem for resolving external references when loading openapi specifications. -func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { - res := make(map[string]func() ([]byte, error)) - if len(pathToFile) > 0 { - res[pathToFile] = rawSpec - } - - return res -} - -// GetSwagger returns the Swagger specification corresponding to the generated code -// in this file. The external references of Swagger specification are resolved. -// The logic of resolving external references is tightly connected to "import-mapping" feature. -// Externally referenced files must be embedded in the corresponding golang packages. -// Urls can be supported but this task was out of the scope. -func GetSwagger() (swagger *openapi3.T, err error) { - resolvePath := PathToRawSpec("") - - loader := openapi3.NewLoader() - loader.IsExternalRefsAllowed = true - loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() - pathToFile = path.Clean(pathToFile) - getSpec, ok := resolvePath[pathToFile] - if !ok { - err1 := fmt.Errorf("path not found: %s", pathToFile) - return nil, err1 - } - return getSpec() - } - var specData []byte - specData, err = rawSpec() - if err != nil { - return - } - swagger, err = loader.LoadFromData(specData) - if err != nil { - return - } - return -} diff --git a/internal/test/outputoptions/name-normalizer/to-camel-case/name_normalizer_test.go b/internal/test/outputoptions/name-normalizer/to-camel-case/name_normalizer_test.go deleted file mode 100644 index 3e0d83fa86..0000000000 --- a/internal/test/outputoptions/name-normalizer/to-camel-case/name_normalizer_test.go +++ /dev/null @@ -1,24 +0,0 @@ -package tocamelcase - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestGenCodeHasCorrectNames(t *testing.T) { - pet := &Pet{} - assert.Equal(t, "", pet.Name) - assert.Equal(t, "", pet.Uuid) - - uri := "https://my-api.com/some-base-url/v1/" - client, err := NewClient(uri) - assert.Nil(t, err) - assert.NotNil(t, client.GetHttpPet) - - server := &ServerInterfaceWrapper{} - assert.NotNil(t, server.GetHttpPet) - - oneOf := OneOf2things{} - assert.Zero(t, oneOf) -} diff --git a/internal/test/outputoptions/name-normalizer/unset/config.yaml b/internal/test/outputoptions/name-normalizer/unset/config.yaml deleted file mode 100644 index bd2918ed51..0000000000 --- a/internal/test/outputoptions/name-normalizer/unset/config.yaml +++ /dev/null @@ -1,11 +0,0 @@ -# yaml-language-server: $schema=../../../../../configuration-schema.json -package: unset -generate: - gorilla-server: true - client: true - models: true - embedded-spec: true -output: name_normalizer.gen.go -output-options: - skip-prune: true - # When `name-normalizer` is unset diff --git a/internal/test/outputoptions/name-normalizer/unset/generate.go b/internal/test/outputoptions/name-normalizer/unset/generate.go deleted file mode 100644 index 84fac60cba..0000000000 --- a/internal/test/outputoptions/name-normalizer/unset/generate.go +++ /dev/null @@ -1,3 +0,0 @@ -package unset - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml ../spec.yaml diff --git a/internal/test/outputoptions/name-normalizer/unset/name_normalizer.gen.go b/internal/test/outputoptions/name-normalizer/unset/name_normalizer.gen.go deleted file mode 100644 index 17f65ad9ee..0000000000 --- a/internal/test/outputoptions/name-normalizer/unset/name_normalizer.gen.go +++ /dev/null @@ -1,590 +0,0 @@ -// Package unset provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package unset - -import ( - "bytes" - "compress/gzip" - "context" - "encoding/base64" - "encoding/json" - "fmt" - "io" - "net/http" - "net/url" - "path" - "strings" - - "github.com/getkin/kin-openapi/openapi3" - "github.com/gorilla/mux" - "github.com/oapi-codegen/runtime" - openapi_types "github.com/oapi-codegen/runtime/types" -) - -// Error defines model for Error. -type Error struct { - // Code Error code - Code int32 `json:"code"` - - // Message Error message - Message string `json:"message"` -} - -// OneOf2things Notice that the `things` is not capitalised -type OneOf2things struct { - union json.RawMessage -} - -// OneOf2things0 defines model for . -type OneOf2things0 struct { - Id int `json:"id"` -} - -// OneOf2things1 defines model for . -type OneOf2things1 struct { - Id openapi_types.UUID `json:"id"` -} - -// Pet defines model for Pet. -type Pet struct { - // Name The name of the pet. - Name string `json:"name"` - - // Uuid The pet uuid. - Uuid string `json:"uuid"` -} - -// AsOneOf2things0 returns the union data inside the OneOf2things as a OneOf2things0 -func (t OneOf2things) AsOneOf2things0() (OneOf2things0, error) { - var body OneOf2things0 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromOneOf2things0 overwrites any union data inside the OneOf2things as the provided OneOf2things0 -func (t *OneOf2things) FromOneOf2things0(v OneOf2things0) error { - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeOneOf2things0 performs a merge with any union data inside the OneOf2things, using the provided OneOf2things0 -func (t *OneOf2things) MergeOneOf2things0(v OneOf2things0) error { - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -// AsOneOf2things1 returns the union data inside the OneOf2things as a OneOf2things1 -func (t OneOf2things) AsOneOf2things1() (OneOf2things1, error) { - var body OneOf2things1 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromOneOf2things1 overwrites any union data inside the OneOf2things as the provided OneOf2things1 -func (t *OneOf2things) FromOneOf2things1(v OneOf2things1) error { - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeOneOf2things1 performs a merge with any union data inside the OneOf2things, using the provided OneOf2things1 -func (t *OneOf2things) MergeOneOf2things1(v OneOf2things1) error { - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -func (t OneOf2things) MarshalJSON() ([]byte, error) { - b, err := t.union.MarshalJSON() - return b, err -} - -func (t *OneOf2things) UnmarshalJSON(b []byte) error { - err := t.union.UnmarshalJSON(b) - return err -} - -// RequestEditorFn is the function signature for the RequestEditor callback function -type RequestEditorFn func(ctx context.Context, req *http.Request) error - -// Doer performs HTTP requests. -// -// The standard http.Client implements this interface. -type HttpRequestDoer interface { - Do(req *http.Request) (*http.Response, error) -} - -// Client which conforms to the OpenAPI3 specification for this service. -type Client struct { - // The endpoint of the server conforming to this interface, with scheme, - // https://api.deepmap.com for example. This can contain a path relative - // to the server, such as https://api.deepmap.com/dev-test, and all the - // paths in the swagger spec will be appended to the server. - Server string - - // Doer for performing requests, typically a *http.Client with any - // customized settings, such as certificate chains. - Client HttpRequestDoer - - // A list of callbacks for modifying requests which are generated before sending over - // the network. - RequestEditors []RequestEditorFn -} - -// ClientOption allows setting custom parameters during construction -type ClientOption func(*Client) error - -// Creates a new Client, with reasonable defaults -func NewClient(server string, opts ...ClientOption) (*Client, error) { - // create a client with sane default values - client := Client{ - Server: server, - } - // mutate client and add all optional params - for _, o := range opts { - if err := o(&client); err != nil { - return nil, err - } - } - // ensure the server URL always has a trailing slash - if !strings.HasSuffix(client.Server, "/") { - client.Server += "/" - } - // create httpClient, if not already present - if client.Client == nil { - client.Client = &http.Client{} - } - return &client, nil -} - -// WithHTTPClient allows overriding the default Doer, which is -// automatically created using http.Client. This is useful for tests. -func WithHTTPClient(doer HttpRequestDoer) ClientOption { - return func(c *Client) error { - c.Client = doer - return nil - } -} - -// WithRequestEditorFn allows setting up a callback function, which will be -// called right before sending the request. This can be used to mutate the request. -func WithRequestEditorFn(fn RequestEditorFn) ClientOption { - return func(c *Client) error { - c.RequestEditors = append(c.RequestEditors, fn) - return nil - } -} - -// The interface specification for the client above. -type ClientInterface interface { - // GetHttpPet request - GetHttpPet(ctx context.Context, petId string, reqEditors ...RequestEditorFn) (*http.Response, error) -} - -func (c *Client) GetHttpPet(ctx context.Context, petId string, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewGetHttpPetRequest(c.Server, petId) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -// NewGetHttpPetRequest generates requests for GetHttpPet -func NewGetHttpPetRequest(server string, petId string) (*http.Request, error) { - var err error - - var pathParam0 string - - pathParam0, err = runtime.StyleParamWithOptions("simple", false, "petId", petId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) - if err != nil { - return nil, err - } - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/api/pets/%s", pathParam0) - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -func (c *Client) applyEditors(ctx context.Context, req *http.Request, additionalEditors []RequestEditorFn) error { - for _, r := range c.RequestEditors { - if err := r(ctx, req); err != nil { - return err - } - } - for _, r := range additionalEditors { - if err := r(ctx, req); err != nil { - return err - } - } - return nil -} - -// ClientWithResponses builds on ClientInterface to offer response payloads -type ClientWithResponses struct { - ClientInterface -} - -// NewClientWithResponses creates a new ClientWithResponses, which wraps -// Client with return type handling -func NewClientWithResponses(server string, opts ...ClientOption) (*ClientWithResponses, error) { - client, err := NewClient(server, opts...) - if err != nil { - return nil, err - } - return &ClientWithResponses{client}, nil -} - -// WithBaseURL overrides the baseURL. -func WithBaseURL(baseURL string) ClientOption { - return func(c *Client) error { - newBaseURL, err := url.Parse(baseURL) - if err != nil { - return err - } - c.Server = newBaseURL.String() - return nil - } -} - -// ClientWithResponsesInterface is the interface specification for the client with responses above. -type ClientWithResponsesInterface interface { - // GetHttpPetWithResponse request - GetHttpPetWithResponse(ctx context.Context, petId string, reqEditors ...RequestEditorFn) (*GetHttpPetResponse, error) -} - -type GetHttpPetResponse struct { - Body []byte - HTTPResponse *http.Response - JSON200 *Pet -} - -// Status returns HTTPResponse.Status -func (r GetHttpPetResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r GetHttpPetResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -// GetHttpPetWithResponse request returning *GetHttpPetResponse -func (c *ClientWithResponses) GetHttpPetWithResponse(ctx context.Context, petId string, reqEditors ...RequestEditorFn) (*GetHttpPetResponse, error) { - rsp, err := c.GetHttpPet(ctx, petId, reqEditors...) - if err != nil { - return nil, err - } - return ParseGetHttpPetResponse(rsp) -} - -// ParseGetHttpPetResponse parses an HTTP response from a GetHttpPetWithResponse call -func ParseGetHttpPetResponse(rsp *http.Response) (*GetHttpPetResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &GetHttpPetResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest Pet - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON200 = &dest - - } - - return response, nil -} - -// ServerInterface represents all server handlers. -type ServerInterface interface { - // Get pet given identifier. - // (GET /api/pets/{petId}) - GetHttpPet(w http.ResponseWriter, r *http.Request, petId string) -} - -// ServerInterfaceWrapper converts contexts to parameters. -type ServerInterfaceWrapper struct { - Handler ServerInterface - HandlerMiddlewares []MiddlewareFunc - ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) -} - -type MiddlewareFunc func(http.Handler) http.Handler - -// GetHttpPet operation middleware -func (siw *ServerInterfaceWrapper) GetHttpPet(w http.ResponseWriter, r *http.Request) { - - var err error - - // ------------- Path parameter "petId" ------------- - var petId string - - err = runtime.BindStyledParameterWithOptions("simple", "petId", mux.Vars(r)["petId"], &petId, runtime.BindStyledParameterOptions{Explode: false, Required: true, Type: "string", Format: ""}) - if err != nil { - siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "petId", Err: err}) - return - } - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.GetHttpPet(w, r, petId) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -type UnescapedCookieParamError struct { - ParamName string - Err error -} - -func (e *UnescapedCookieParamError) Error() string { - return fmt.Sprintf("error unescaping cookie parameter '%s'", e.ParamName) -} - -func (e *UnescapedCookieParamError) Unwrap() error { - return e.Err -} - -type UnmarshalingParamError struct { - ParamName string - Err error -} - -func (e *UnmarshalingParamError) Error() string { - return fmt.Sprintf("Error unmarshaling parameter %s as JSON: %s", e.ParamName, e.Err.Error()) -} - -func (e *UnmarshalingParamError) Unwrap() error { - return e.Err -} - -type RequiredParamError struct { - ParamName string -} - -func (e *RequiredParamError) Error() string { - return fmt.Sprintf("Query argument %s is required, but not found", e.ParamName) -} - -type RequiredHeaderError struct { - ParamName string - Err error -} - -func (e *RequiredHeaderError) Error() string { - return fmt.Sprintf("Header parameter %s is required, but not found", e.ParamName) -} - -func (e *RequiredHeaderError) Unwrap() error { - return e.Err -} - -type InvalidParamFormatError struct { - ParamName string - Err error -} - -func (e *InvalidParamFormatError) Error() string { - return fmt.Sprintf("Invalid format for parameter %s: %s", e.ParamName, e.Err.Error()) -} - -func (e *InvalidParamFormatError) Unwrap() error { - return e.Err -} - -type TooManyValuesForParamError struct { - ParamName string - Count int -} - -func (e *TooManyValuesForParamError) Error() string { - return fmt.Sprintf("Expected one value for %s, got %d", e.ParamName, e.Count) -} - -// Handler creates http.Handler with routing matching OpenAPI spec. -func Handler(si ServerInterface) http.Handler { - return HandlerWithOptions(si, GorillaServerOptions{}) -} - -type GorillaServerOptions struct { - BaseURL string - BaseRouter *mux.Router - Middlewares []MiddlewareFunc - ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) -} - -// HandlerFromMux creates http.Handler with routing matching OpenAPI spec based on the provided mux. -func HandlerFromMux(si ServerInterface, r *mux.Router) http.Handler { - return HandlerWithOptions(si, GorillaServerOptions{ - BaseRouter: r, - }) -} - -func HandlerFromMuxWithBaseURL(si ServerInterface, r *mux.Router, baseURL string) http.Handler { - return HandlerWithOptions(si, GorillaServerOptions{ - BaseURL: baseURL, - BaseRouter: r, - }) -} - -// HandlerWithOptions creates http.Handler with additional options -func HandlerWithOptions(si ServerInterface, options GorillaServerOptions) http.Handler { - r := options.BaseRouter - - if r == nil { - r = mux.NewRouter() - } - if options.ErrorHandlerFunc == nil { - options.ErrorHandlerFunc = func(w http.ResponseWriter, r *http.Request, err error) { - http.Error(w, err.Error(), http.StatusBadRequest) - } - } - wrapper := ServerInterfaceWrapper{ - Handler: si, - HandlerMiddlewares: options.Middlewares, - ErrorHandlerFunc: options.ErrorHandlerFunc, - } - - r.HandleFunc(options.BaseURL+"/api/pets/{petId}", wrapper.GetHttpPet).Methods("GET") - - return r -} - -// Base64 encoded, gzipped, json marshaled Swagger object -var swaggerSpec = []string{ - - "H4sIAAAAAAAC/4RTzY7TMBB+FWvgaJLSveW+gr2wHLitKtXEk2RWiW3sScVS5d3R2G0pbVe9tI5n/Pn7", - "8eyh9VPwDh0naPaQ2gEnk5ePMfooixB9wMiEebv1FuXfYmojBSbvoCnNKtc0dD5OhqEBcvywBg38FrB8", - "Yo8RFg0TpmT6d4GO5dPRxJFcD8uiIeKvmSJaaF7gcOGxfbNoeHb43K15INena/hvnqlFxYNhxQOqbWnc", - "KkrKeVatCcRmpIQWNHjBgubl0gOy8nup6oIbWdic+Pufr9gyLPo21MmxeSZ7V/VNZNH+Hfk6MGemGz7/", - "GFBJRfkuGxGQq+uLdSF083RAVlKt7vI9iMpErolLN7nOZ0uJR6k9/jZTGDE/KNX5WLISgE9OrBrpD8at", - "8jOHmZUvtDTsMKZC8HO1qlbC3wd0JhA08JC3NATDQzamNoHqgJzqfUB+sots9sVCMdAI6pOFBr4gf2UO", - "Yq+cj2ZCxpjyyyC5TjCPChvIaHDuAccZ9WG4zp7Oya+NNKfgXSqZrVerMmuO0WVCJoSR2kypfk2icX+G", - "9zFiBw18qP9Nc30Y5VpYZ5P/j3BnRrISYo4rzdNk4lvRmqPtaYdOkUXH1BHGSkCWvwEAAP//D5F1qDAE", - "AAA=", -} - -// GetSwagger returns the content of the embedded swagger specification file -// or error if failed to decode -func decodeSpec() ([]byte, error) { - zipped, err := base64.StdEncoding.DecodeString(strings.Join(swaggerSpec, "")) - if err != nil { - return nil, fmt.Errorf("error base64 decoding spec: %w", err) - } - zr, err := gzip.NewReader(bytes.NewReader(zipped)) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - var buf bytes.Buffer - _, err = buf.ReadFrom(zr) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - - return buf.Bytes(), nil -} - -var rawSpec = decodeSpecCached() - -// a naive cached of a decoded swagger spec -func decodeSpecCached() func() ([]byte, error) { - data, err := decodeSpec() - return func() ([]byte, error) { - return data, err - } -} - -// Constructs a synthetic filesystem for resolving external references when loading openapi specifications. -func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { - res := make(map[string]func() ([]byte, error)) - if len(pathToFile) > 0 { - res[pathToFile] = rawSpec - } - - return res -} - -// GetSwagger returns the Swagger specification corresponding to the generated code -// in this file. The external references of Swagger specification are resolved. -// The logic of resolving external references is tightly connected to "import-mapping" feature. -// Externally referenced files must be embedded in the corresponding golang packages. -// Urls can be supported but this task was out of the scope. -func GetSwagger() (swagger *openapi3.T, err error) { - resolvePath := PathToRawSpec("") - - loader := openapi3.NewLoader() - loader.IsExternalRefsAllowed = true - loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() - pathToFile = path.Clean(pathToFile) - getSpec, ok := resolvePath[pathToFile] - if !ok { - err1 := fmt.Errorf("path not found: %s", pathToFile) - return nil, err1 - } - return getSpec() - } - var specData []byte - specData, err = rawSpec() - if err != nil { - return - } - swagger, err = loader.LoadFromData(specData) - if err != nil { - return - } - return -} diff --git a/internal/test/outputoptions/name-normalizer/unset/name_normalizer_test.go b/internal/test/outputoptions/name-normalizer/unset/name_normalizer_test.go deleted file mode 100644 index 9702a59c40..0000000000 --- a/internal/test/outputoptions/name-normalizer/unset/name_normalizer_test.go +++ /dev/null @@ -1,24 +0,0 @@ -package unset - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestGenCodeHasCorrectNames(t *testing.T) { - pet := &Pet{} - assert.Equal(t, "", pet.Name) - assert.Equal(t, "", pet.Uuid) - - uri := "https://my-api.com/some-base-url/v1/" - client, err := NewClient(uri) - assert.Nil(t, err) - assert.NotNil(t, client.GetHttpPet) - - server := &ServerInterfaceWrapper{} - assert.NotNil(t, server.GetHttpPet) - - oneOf := OneOf2things{} - assert.Zero(t, oneOf) -} diff --git a/internal/test/outputoptions/yaml-tags/config.yaml b/internal/test/outputoptions/yaml-tags/config.yaml deleted file mode 100644 index 6f1e3eef12..0000000000 --- a/internal/test/outputoptions/yaml-tags/config.yaml +++ /dev/null @@ -1,8 +0,0 @@ -# yaml-language-server: $schema=../../../../configuration-schema.json -package: yamltags -generate: - models: true -output-options: - skip-prune: true - yaml-tags: true -output: yamltags.go diff --git a/internal/test/outputoptions/yaml-tags/generate.go b/internal/test/outputoptions/yaml-tags/generate.go deleted file mode 100644 index 1da2444608..0000000000 --- a/internal/test/outputoptions/yaml-tags/generate.go +++ /dev/null @@ -1,3 +0,0 @@ -package yamltags - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml spec.yaml diff --git a/internal/test/outputoptions/yaml-tags/spec.yaml b/internal/test/outputoptions/yaml-tags/spec.yaml deleted file mode 100644 index f30596224f..0000000000 --- a/internal/test/outputoptions/yaml-tags/spec.yaml +++ /dev/null @@ -1,24 +0,0 @@ -openapi: "3.0.1" -info: - version: 1.0.0 - title: Cookie parameters -paths: - /cookies: - get: - operationId: cookieParams - parameters: - - name: authId - description: Cookie parameter - in: cookie - required: false - schema: - type: string - - name: serverId - description: Another cookie parameter - in: cookie - required: false - schema: - type: string - responses: - 204: - description: no content diff --git a/internal/test/outputoptions/yaml-tags/yamltags.go b/internal/test/outputoptions/yaml-tags/yamltags.go deleted file mode 100644 index 6422e7391e..0000000000 --- a/internal/test/outputoptions/yaml-tags/yamltags.go +++ /dev/null @@ -1,13 +0,0 @@ -// Package yamltags provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package yamltags - -// CookieParamsParams defines parameters for CookieParams. -type CookieParamsParams struct { - // AuthId Cookie parameter - AuthId *string `form:"authId,omitempty" json:"authId,omitempty" yaml:"authId,omitempty"` - - // ServerId Another cookie parameter - ServerId *string `form:"serverId,omitempty" json:"serverId,omitempty" yaml:"serverId,omitempty"` -} diff --git a/internal/test/parameters/config.yaml b/internal/test/parameters/config.yaml deleted file mode 100644 index 64850f5de5..0000000000 --- a/internal/test/parameters/config.yaml +++ /dev/null @@ -1,8 +0,0 @@ -# yaml-language-server: $schema=../../../configuration-schema.json -package: parameters -generate: - echo-server: true - client: true - models: true - embedded-spec: true -output: parameters.gen.go diff --git a/internal/test/issues/issue-52/config.yaml b/internal/test/parameters/content/config.yaml similarity index 68% rename from internal/test/issues/issue-52/config.yaml rename to internal/test/parameters/content/config.yaml index 1277b9c971..2579d99d6a 100644 --- a/internal/test/issues/issue-52/config.yaml +++ b/internal/test/parameters/content/config.yaml @@ -1,8 +1,7 @@ # yaml-language-server: $schema=../../../../configuration-schema.json -package: issue52 +package: content generate: echo-server: true client: true models: true - embedded-spec: true -output: issue.gen.go +output: content.gen.go diff --git a/internal/test/parameters/content/content.gen.go b/internal/test/parameters/content/content.gen.go new file mode 100644 index 0000000000..32d68390c9 --- /dev/null +++ b/internal/test/parameters/content/content.gen.go @@ -0,0 +1,852 @@ +// Package content provides primitives to interact with the openapi HTTP API. +// +// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. +package content + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "strings" + + "github.com/labstack/echo/v4" +) + +// ComplexObject defines model for ComplexObject. +type ComplexObject struct { + Id int `json:"Id"` + IsAdmin bool `json:"IsAdmin"` + Object Object `json:"Object"` +} + +// Object defines model for Object. +type Object struct { + FirstName string `json:"firstName"` + Role string `json:"role"` +} + +// GetCookieJsonParams defines parameters for GetCookieJson. +type GetCookieJsonParams struct { + Obj *ComplexObject `form:"obj,omitempty" json:"obj,omitempty"` +} + +// GetHeaderJsonParams defines parameters for GetHeaderJson. +type GetHeaderJsonParams struct { + XObject *ComplexObject `json:"X-Object,omitempty"` +} + +// GetQueryJsonParams defines parameters for GetQueryJson. +type GetQueryJsonParams struct { + Obj *ComplexObject `form:"obj,omitempty" json:"obj,omitempty"` +} + +// RequestEditorFn is the function signature for the RequestEditor callback function +type RequestEditorFn func(ctx context.Context, req *http.Request) error + +// Doer performs HTTP requests. +// +// The standard http.Client implements this interface. +type HttpRequestDoer interface { + Do(req *http.Request) (*http.Response, error) +} + +// Client which conforms to the OpenAPI3 specification for this service. +type Client struct { + // The endpoint of the server conforming to this interface, with scheme, + // https://api.deepmap.com for example. This can contain a path relative + // to the server, such as https://api.deepmap.com/dev-test, and all the + // paths in the swagger spec will be appended to the server. + Server string + + // Doer for performing requests, typically a *http.Client with any + // customized settings, such as certificate chains. + Client HttpRequestDoer + + // A list of callbacks for modifying requests which are generated before sending over + // the network. + RequestEditors []RequestEditorFn +} + +// ClientOption allows setting custom parameters during construction +type ClientOption func(*Client) error + +// Creates a new Client, with reasonable defaults +func NewClient(server string, opts ...ClientOption) (*Client, error) { + // create a client with sane default values + client := Client{ + Server: server, + } + // mutate client and add all optional params + for _, o := range opts { + if err := o(&client); err != nil { + return nil, err + } + } + // ensure the server URL always has a trailing slash + if !strings.HasSuffix(client.Server, "/") { + client.Server += "/" + } + // create httpClient, if not already present + if client.Client == nil { + client.Client = &http.Client{} + } + return &client, nil +} + +// WithHTTPClient allows overriding the default Doer, which is +// automatically created using http.Client. This is useful for tests. +func WithHTTPClient(doer HttpRequestDoer) ClientOption { + return func(c *Client) error { + c.Client = doer + return nil + } +} + +// WithRequestEditorFn allows setting up a callback function, which will be +// called right before sending the request. This can be used to mutate the request. +func WithRequestEditorFn(fn RequestEditorFn) ClientOption { + return func(c *Client) error { + c.RequestEditors = append(c.RequestEditors, fn) + return nil + } +} + +// The interface specification for the client above. +type ClientInterface interface { + // GetCookieJson request + GetCookieJson(ctx context.Context, params *GetCookieJsonParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetHeaderJson request + GetHeaderJson(ctx context.Context, params *GetHeaderJsonParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetPathJson request + GetPathJson(ctx context.Context, param ComplexObject, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetPathText request + GetPathText(ctx context.Context, param string, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetQueryJson request + GetQueryJson(ctx context.Context, params *GetQueryJsonParams, reqEditors ...RequestEditorFn) (*http.Response, error) +} + +func (c *Client) GetCookieJson(ctx context.Context, params *GetCookieJsonParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetCookieJsonRequest(c.Server, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetHeaderJson(ctx context.Context, params *GetHeaderJsonParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetHeaderJsonRequest(c.Server, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetPathJson(ctx context.Context, param ComplexObject, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetPathJsonRequest(c.Server, param) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetPathText(ctx context.Context, param string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetPathTextRequest(c.Server, param) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetQueryJson(ctx context.Context, params *GetQueryJsonParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetQueryJsonRequest(c.Server, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +// NewGetCookieJsonRequest generates requests for GetCookieJson +func NewGetCookieJsonRequest(server string, params *GetCookieJsonParams) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/cookieJson") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + if params != nil { + + if params.Obj != nil { + var cookieParam0 string + + var cookieParamBuf0 []byte + cookieParamBuf0, err = json.Marshal(*params.Obj) + if err != nil { + return nil, err + } + cookieParam0 = url.QueryEscape(string(cookieParamBuf0)) + + cookie0 := &http.Cookie{ + Name: "obj", + Value: cookieParam0, + } + req.AddCookie(cookie0) + } + } + return req, nil +} + +// NewGetHeaderJsonRequest generates requests for GetHeaderJson +func NewGetHeaderJsonRequest(server string, params *GetHeaderJsonParams) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/headerJson") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + if params != nil { + + if params.XObject != nil { + var headerParam0 string + + var headerParamBuf0 []byte + headerParamBuf0, err = json.Marshal(*params.XObject) + if err != nil { + return nil, err + } + headerParam0 = string(headerParamBuf0) + + req.Header.Set("X-Object", headerParam0) + } + + } + + return req, nil +} + +// NewGetPathJsonRequest generates requests for GetPathJson +func NewGetPathJsonRequest(server string, param ComplexObject) (*http.Request, error) { + var err error + + var pathParam0 string + + var pathParamBuf0 []byte + pathParamBuf0, err = json.Marshal(param) + if err != nil { + return nil, err + } + pathParam0 = string(pathParamBuf0) + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/pathJson/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetPathTextRequest generates requests for GetPathText +func NewGetPathTextRequest(server string, param string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0 = param + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/pathText/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetQueryJsonRequest generates requests for GetQueryJson +func NewGetQueryJsonRequest(server string, params *GetQueryJsonParams) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/queryJson") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + queryValues := queryURL.Query() + + if params.Obj != nil { + + if queryParamBuf, err := json.Marshal(*params.Obj); err != nil { + return nil, err + } else { + queryValues.Add("obj", string(queryParamBuf)) + } + + } + + queryURL.RawQuery = queryValues.Encode() + } + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +func (c *Client) applyEditors(ctx context.Context, req *http.Request, additionalEditors []RequestEditorFn) error { + for _, r := range c.RequestEditors { + if err := r(ctx, req); err != nil { + return err + } + } + for _, r := range additionalEditors { + if err := r(ctx, req); err != nil { + return err + } + } + return nil +} + +// ClientWithResponses builds on ClientInterface to offer response payloads +type ClientWithResponses struct { + ClientInterface +} + +// NewClientWithResponses creates a new ClientWithResponses, which wraps +// Client with return type handling +func NewClientWithResponses(server string, opts ...ClientOption) (*ClientWithResponses, error) { + client, err := NewClient(server, opts...) + if err != nil { + return nil, err + } + return &ClientWithResponses{client}, nil +} + +// WithBaseURL overrides the baseURL. +func WithBaseURL(baseURL string) ClientOption { + return func(c *Client) error { + newBaseURL, err := url.Parse(baseURL) + if err != nil { + return err + } + c.Server = newBaseURL.String() + return nil + } +} + +// ClientWithResponsesInterface is the interface specification for the client with responses above. +type ClientWithResponsesInterface interface { + // GetCookieJsonWithResponse request + GetCookieJsonWithResponse(ctx context.Context, params *GetCookieJsonParams, reqEditors ...RequestEditorFn) (*GetCookieJsonResponse, error) + + // GetHeaderJsonWithResponse request + GetHeaderJsonWithResponse(ctx context.Context, params *GetHeaderJsonParams, reqEditors ...RequestEditorFn) (*GetHeaderJsonResponse, error) + + // GetPathJsonWithResponse request + GetPathJsonWithResponse(ctx context.Context, param ComplexObject, reqEditors ...RequestEditorFn) (*GetPathJsonResponse, error) + + // GetPathTextWithResponse request + GetPathTextWithResponse(ctx context.Context, param string, reqEditors ...RequestEditorFn) (*GetPathTextResponse, error) + + // GetQueryJsonWithResponse request + GetQueryJsonWithResponse(ctx context.Context, params *GetQueryJsonParams, reqEditors ...RequestEditorFn) (*GetQueryJsonResponse, error) +} + +type GetCookieJsonResponse struct { + Body []byte + HTTPResponse *http.Response +} + +// Status returns HTTPResponse.Status +func (r GetCookieJsonResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetCookieJsonResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetHeaderJsonResponse struct { + Body []byte + HTTPResponse *http.Response +} + +// Status returns HTTPResponse.Status +func (r GetHeaderJsonResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetHeaderJsonResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetPathJsonResponse struct { + Body []byte + HTTPResponse *http.Response +} + +// Status returns HTTPResponse.Status +func (r GetPathJsonResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetPathJsonResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetPathTextResponse struct { + Body []byte + HTTPResponse *http.Response +} + +// Status returns HTTPResponse.Status +func (r GetPathTextResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetPathTextResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetQueryJsonResponse struct { + Body []byte + HTTPResponse *http.Response +} + +// Status returns HTTPResponse.Status +func (r GetQueryJsonResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetQueryJsonResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// GetCookieJsonWithResponse request returning *GetCookieJsonResponse +func (c *ClientWithResponses) GetCookieJsonWithResponse(ctx context.Context, params *GetCookieJsonParams, reqEditors ...RequestEditorFn) (*GetCookieJsonResponse, error) { + rsp, err := c.GetCookieJson(ctx, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetCookieJsonResponse(rsp) +} + +// GetHeaderJsonWithResponse request returning *GetHeaderJsonResponse +func (c *ClientWithResponses) GetHeaderJsonWithResponse(ctx context.Context, params *GetHeaderJsonParams, reqEditors ...RequestEditorFn) (*GetHeaderJsonResponse, error) { + rsp, err := c.GetHeaderJson(ctx, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetHeaderJsonResponse(rsp) +} + +// GetPathJsonWithResponse request returning *GetPathJsonResponse +func (c *ClientWithResponses) GetPathJsonWithResponse(ctx context.Context, param ComplexObject, reqEditors ...RequestEditorFn) (*GetPathJsonResponse, error) { + rsp, err := c.GetPathJson(ctx, param, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetPathJsonResponse(rsp) +} + +// GetPathTextWithResponse request returning *GetPathTextResponse +func (c *ClientWithResponses) GetPathTextWithResponse(ctx context.Context, param string, reqEditors ...RequestEditorFn) (*GetPathTextResponse, error) { + rsp, err := c.GetPathText(ctx, param, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetPathTextResponse(rsp) +} + +// GetQueryJsonWithResponse request returning *GetQueryJsonResponse +func (c *ClientWithResponses) GetQueryJsonWithResponse(ctx context.Context, params *GetQueryJsonParams, reqEditors ...RequestEditorFn) (*GetQueryJsonResponse, error) { + rsp, err := c.GetQueryJson(ctx, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetQueryJsonResponse(rsp) +} + +// ParseGetCookieJsonResponse parses an HTTP response from a GetCookieJsonWithResponse call +func ParseGetCookieJsonResponse(rsp *http.Response) (*GetCookieJsonResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetCookieJsonResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + return response, nil +} + +// ParseGetHeaderJsonResponse parses an HTTP response from a GetHeaderJsonWithResponse call +func ParseGetHeaderJsonResponse(rsp *http.Response) (*GetHeaderJsonResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetHeaderJsonResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + return response, nil +} + +// ParseGetPathJsonResponse parses an HTTP response from a GetPathJsonWithResponse call +func ParseGetPathJsonResponse(rsp *http.Response) (*GetPathJsonResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetPathJsonResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + return response, nil +} + +// ParseGetPathTextResponse parses an HTTP response from a GetPathTextWithResponse call +func ParseGetPathTextResponse(rsp *http.Response) (*GetPathTextResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetPathTextResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + return response, nil +} + +// ParseGetQueryJsonResponse parses an HTTP response from a GetQueryJsonWithResponse call +func ParseGetQueryJsonResponse(rsp *http.Response) (*GetQueryJsonResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetQueryJsonResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + return response, nil +} + +// ServerInterface represents all server handlers. +type ServerInterface interface { + + // (GET /cookieJson) + GetCookieJson(ctx echo.Context, params GetCookieJsonParams) error + + // (GET /headerJson) + GetHeaderJson(ctx echo.Context, params GetHeaderJsonParams) error + + // (GET /pathJson/{param}) + GetPathJson(ctx echo.Context, param ComplexObject) error + + // (GET /pathText/{param}) + GetPathText(ctx echo.Context, param string) error + + // (GET /queryJson) + GetQueryJson(ctx echo.Context, params GetQueryJsonParams) error +} + +// ServerInterfaceWrapper converts echo contexts to parameters. +type ServerInterfaceWrapper struct { + Handler ServerInterface +} + +// GetCookieJson converts echo context to params. +func (w *ServerInterfaceWrapper) GetCookieJson(ctx echo.Context) error { + var err error + + // Parameter object where we will unmarshal all parameters from the context + var params GetCookieJsonParams + + if cookie, err := ctx.Cookie("obj"); err == nil { + + var value ComplexObject + var decoded string + decoded, err := url.QueryUnescape(cookie.Value) + if err != nil { + return echo.NewHTTPError(http.StatusBadRequest, "Error unescaping cookie parameter 'obj'") + } + err = json.Unmarshal([]byte(decoded), &value) + if err != nil { + return echo.NewHTTPError(http.StatusBadRequest, "Error unmarshaling parameter 'obj' as JSON") + } + params.Obj = &value + + } + + // Invoke the callback with all the unmarshaled arguments + err = w.Handler.GetCookieJson(ctx, params) + return err +} + +// GetHeaderJson converts echo context to params. +func (w *ServerInterfaceWrapper) GetHeaderJson(ctx echo.Context) error { + var err error + + // Parameter object where we will unmarshal all parameters from the context + var params GetHeaderJsonParams + + headers := ctx.Request().Header + // ------------- Optional header parameter "X-Object" ------------- + if valueList, found := headers[http.CanonicalHeaderKey("X-Object")]; found { + var XObject ComplexObject + n := len(valueList) + if n != 1 { + return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Expected one value for X-Object, got %d", n)) + } + + err = json.Unmarshal([]byte(valueList[0]), &XObject) + if err != nil { + return echo.NewHTTPError(http.StatusBadRequest, "Error unmarshaling parameter 'X-Object' as JSON") + } + + params.XObject = &XObject + } + + // Invoke the callback with all the unmarshaled arguments + err = w.Handler.GetHeaderJson(ctx, params) + return err +} + +// GetPathJson converts echo context to params. +func (w *ServerInterfaceWrapper) GetPathJson(ctx echo.Context) error { + var err error + // ------------- Path parameter "param" ------------- + var param ComplexObject + + err = json.Unmarshal([]byte(ctx.Param("param")), ¶m) + if err != nil { + return echo.NewHTTPError(http.StatusBadRequest, "Error unmarshaling parameter 'param' as JSON") + } + + // Invoke the callback with all the unmarshaled arguments + err = w.Handler.GetPathJson(ctx, param) + return err +} + +// GetPathText converts echo context to params. +func (w *ServerInterfaceWrapper) GetPathText(ctx echo.Context) error { + var err error + // ------------- Path parameter "param" ------------- + var param string + + param = ctx.Param("param") + + // Invoke the callback with all the unmarshaled arguments + err = w.Handler.GetPathText(ctx, param) + return err +} + +// GetQueryJson converts echo context to params. +func (w *ServerInterfaceWrapper) GetQueryJson(ctx echo.Context) error { + var err error + + // Parameter object where we will unmarshal all parameters from the context + var params GetQueryJsonParams + // ------------- Optional query parameter "obj" ------------- + + if paramValue := ctx.QueryParam("obj"); paramValue != "" { + + var value ComplexObject + err = json.Unmarshal([]byte(paramValue), &value) + if err != nil { + return echo.NewHTTPError(http.StatusBadRequest, "Error unmarshaling parameter 'obj' as JSON") + } + params.Obj = &value + + } + + // Invoke the callback with all the unmarshaled arguments + err = w.Handler.GetQueryJson(ctx, params) + return err +} + +// This is a simple interface which specifies echo.Route addition functions which +// are present on both echo.Echo and echo.Group, since we want to allow using +// either of them for path registration +type EchoRouter interface { + CONNECT(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route + DELETE(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route + GET(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route + HEAD(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route + OPTIONS(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route + PATCH(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route + POST(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route + PUT(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route + TRACE(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route +} + +// RegisterHandlers adds each server route to the EchoRouter. +func RegisterHandlers(router EchoRouter, si ServerInterface) { + RegisterHandlersWithBaseURL(router, si, "") +} + +// Registers handlers, and prepends BaseURL to the paths, so that the paths +// can be served under a prefix. +func RegisterHandlersWithBaseURL(router EchoRouter, si ServerInterface, baseURL string) { + + wrapper := ServerInterfaceWrapper{ + Handler: si, + } + + router.GET(baseURL+"/cookieJson", wrapper.GetCookieJson) + router.GET(baseURL+"/headerJson", wrapper.GetHeaderJson) + router.GET(baseURL+"/pathJson/:param", wrapper.GetPathJson) + router.GET(baseURL+"/pathText/:param", wrapper.GetPathText) + router.GET(baseURL+"/queryJson", wrapper.GetQueryJson) + +} diff --git a/internal/test/parameters/content/content_test.go b/internal/test/parameters/content/content_test.go new file mode 100644 index 0000000000..ac600812c6 --- /dev/null +++ b/internal/test/parameters/content/content_test.go @@ -0,0 +1,202 @@ +package content + +import ( + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "net/url" + "testing" + + "github.com/labstack/echo/v4" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +type testServer struct { + complexObject *ComplexObject + passThrough *string +} + +func (s *testServer) reset() { + s.complexObject = nil + s.passThrough = nil +} + +func (s *testServer) GetPathJson(ctx echo.Context, param ComplexObject) error { + s.complexObject = ¶m + return nil +} + +func (s *testServer) GetPathText(ctx echo.Context, param string) error { + s.passThrough = ¶m + return nil +} + +func (s *testServer) GetQueryJson(ctx echo.Context, params GetQueryJsonParams) error { + if params.Obj != nil { + s.complexObject = params.Obj + } + return nil +} + +func (s *testServer) GetHeaderJson(ctx echo.Context, params GetHeaderJsonParams) error { + if params.XObject != nil { + s.complexObject = params.XObject + } + return nil +} + +func (s *testServer) GetCookieJson(ctx echo.Context, params GetCookieJsonParams) error { + if params.Obj != nil { + s.complexObject = params.Obj + } + return nil +} + +func setup(t *testing.T) (*testServer, *echo.Echo, string) { + t.Helper() + ts := &testServer{} + e := echo.New() + RegisterHandlers(e, ts) + return ts, e, "http://example.com" +} + +func TestServerContentParams(t *testing.T) { + ts, e, _ := setup(t) + + expectedObject := Object{FirstName: "Alex", Role: "admin"} + expectedComplex := ComplexObject{ + Object: expectedObject, + Id: 12345, + IsAdmin: true, + } + marshaledComplex, err := json.Marshal(expectedComplex) + require.NoError(t, err) + + t.Run("path/json", func(t *testing.T) { + req := httptest.NewRequest(http.MethodGet, + fmt.Sprintf("/pathJson/%s", string(marshaledComplex)), nil) + rec := httptest.NewRecorder() + e.ServeHTTP(rec, req) + assert.Equal(t, http.StatusOK, rec.Code) + require.NotNil(t, ts.complexObject) + assert.EqualValues(t, expectedComplex, *ts.complexObject) + ts.reset() + }) + + t.Run("path/text", func(t *testing.T) { + req := httptest.NewRequest(http.MethodGet, "/pathText/some%20string", nil) + rec := httptest.NewRecorder() + e.ServeHTTP(rec, req) + assert.Equal(t, http.StatusOK, rec.Code) + require.NotNil(t, ts.passThrough) + assert.EqualValues(t, "some string", *ts.passThrough) + ts.reset() + }) + + t.Run("query/json", func(t *testing.T) { + req := httptest.NewRequest(http.MethodGet, + fmt.Sprintf("/queryJson?obj=%s", string(marshaledComplex)), nil) + rec := httptest.NewRecorder() + e.ServeHTTP(rec, req) + assert.Equal(t, http.StatusOK, rec.Code) + require.NotNil(t, ts.complexObject) + assert.EqualValues(t, expectedComplex, *ts.complexObject) + ts.reset() + }) + + t.Run("header/json", func(t *testing.T) { + req := httptest.NewRequest(http.MethodGet, "/headerJson", nil) + req.Header.Set("X-Object", string(marshaledComplex)) + rec := httptest.NewRecorder() + e.ServeHTTP(rec, req) + assert.Equal(t, http.StatusOK, rec.Code) + require.NotNil(t, ts.complexObject) + assert.EqualValues(t, expectedComplex, *ts.complexObject) + ts.reset() + }) + + t.Run("cookie/json", func(t *testing.T) { + // Cookie values cannot contain raw JSON (quotes are invalid). + // The runtime URL-encodes JSON cookie values, so we must do the same for the server-side test. + encoded := url.QueryEscape(string(marshaledComplex)) + req := httptest.NewRequest(http.MethodGet, "/cookieJson", nil) + req.AddCookie(&http.Cookie{Name: "obj", Value: encoded}) + rec := httptest.NewRecorder() + e.ServeHTTP(rec, req) + assert.Equal(t, http.StatusOK, rec.Code) + require.NotNil(t, ts.complexObject) + assert.EqualValues(t, expectedComplex, *ts.complexObject) + ts.reset() + }) +} + +func TestClientContentParams(t *testing.T) { + ts, e, server := setup(t) + + expectedObject := Object{FirstName: "Alex", Role: "admin"} + expectedComplex := ComplexObject{ + Object: expectedObject, + Id: 12345, + IsAdmin: true, + } + + t.Run("path/json", func(t *testing.T) { + req, err := NewGetPathJsonRequest(server, expectedComplex) + require.NoError(t, err) + rec := httptest.NewRecorder() + e.ServeHTTP(rec, req) + assert.Equal(t, http.StatusOK, rec.Code) + require.NotNil(t, ts.complexObject) + assert.EqualValues(t, expectedComplex, *ts.complexObject) + ts.reset() + }) + + t.Run("path/text", func(t *testing.T) { + req, err := NewGetPathTextRequest(server, "some string") + require.NoError(t, err) + rec := httptest.NewRecorder() + e.ServeHTTP(rec, req) + assert.Equal(t, http.StatusOK, rec.Code) + require.NotNil(t, ts.passThrough) + assert.Equal(t, "some string", *ts.passThrough) + ts.reset() + }) + + t.Run("query/json", func(t *testing.T) { + params := GetQueryJsonParams{Obj: &expectedComplex} + req, err := NewGetQueryJsonRequest(server, ¶ms) + require.NoError(t, err) + rec := httptest.NewRecorder() + e.ServeHTTP(rec, req) + assert.Equal(t, http.StatusOK, rec.Code) + require.NotNil(t, ts.complexObject) + assert.EqualValues(t, expectedComplex, *ts.complexObject) + ts.reset() + }) + + t.Run("header/json", func(t *testing.T) { + params := GetHeaderJsonParams{XObject: &expectedComplex} + req, err := NewGetHeaderJsonRequest(server, ¶ms) + require.NoError(t, err) + rec := httptest.NewRecorder() + e.ServeHTTP(rec, req) + assert.Equal(t, http.StatusOK, rec.Code) + require.NotNil(t, ts.complexObject) + assert.EqualValues(t, expectedComplex, *ts.complexObject) + ts.reset() + }) + + t.Run("cookie/json", func(t *testing.T) { + params := GetCookieJsonParams{Obj: &expectedComplex} + req, err := NewGetCookieJsonRequest(server, ¶ms) + require.NoError(t, err) + rec := httptest.NewRecorder() + e.ServeHTTP(rec, req) + assert.Equal(t, http.StatusOK, rec.Code) + require.NotNil(t, ts.complexObject) + assert.EqualValues(t, expectedComplex, *ts.complexObject) + ts.reset() + }) +} diff --git a/internal/test/extensions/x-order/generate.go b/internal/test/parameters/content/doc.go similarity index 87% rename from internal/test/extensions/x-order/generate.go rename to internal/test/parameters/content/doc.go index 8970f968ac..a64994995d 100644 --- a/internal/test/extensions/x-order/generate.go +++ b/internal/test/parameters/content/doc.go @@ -1,3 +1,3 @@ -package xorder +package content //go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml spec.yaml diff --git a/internal/test/parameters/content/spec.yaml b/internal/test/parameters/content/spec.yaml new file mode 100644 index 0000000000..1c8d484f22 --- /dev/null +++ b/internal/test/parameters/content/spec.yaml @@ -0,0 +1,100 @@ +openapi: "3.0.1" +info: + version: 1.0.0 + title: Content-Based Parameters +paths: + /pathJson/{param}: + get: + operationId: getPathJson + parameters: + - name: param + in: path + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/ComplexObject" + responses: + "200": + description: OK + /pathText/{param}: + get: + operationId: getPathText + parameters: + - name: param + in: path + required: true + content: + text/plain: + schema: + type: string + responses: + "200": + description: OK + /queryJson: + get: + operationId: getQueryJson + parameters: + - name: obj + in: query + required: false + content: + application/json: + schema: + $ref: "#/components/schemas/ComplexObject" + responses: + "200": + description: OK + /headerJson: + get: + operationId: getHeaderJson + parameters: + - name: X-Object + in: header + required: false + content: + application/json: + schema: + $ref: "#/components/schemas/ComplexObject" + responses: + "200": + description: OK + /cookieJson: + get: + operationId: getCookieJson + parameters: + - name: obj + in: cookie + required: false + content: + application/json: + schema: + $ref: "#/components/schemas/ComplexObject" + responses: + "200": + description: OK +components: + schemas: + Object: + type: object + properties: + role: + type: string + firstName: + type: string + required: + - role + - firstName + ComplexObject: + type: object + properties: + Object: + $ref: "#/components/schemas/Object" + Id: + type: integer + IsAdmin: + type: boolean + required: + - Object + - Id + - IsAdmin diff --git a/internal/test/parameters/cookie/form/config.yaml b/internal/test/parameters/cookie/form/config.yaml new file mode 100644 index 0000000000..4bcc072eff --- /dev/null +++ b/internal/test/parameters/cookie/form/config.yaml @@ -0,0 +1,7 @@ +# yaml-language-server: $schema=../../../../../../configuration-schema.json +package: cookieform +generate: + echo-server: true + client: true + models: true +output: cookie_form.gen.go diff --git a/internal/test/issues/issue-grab_import_names/issue.gen.go b/internal/test/parameters/cookie/form/cookie_form.gen.go similarity index 50% rename from internal/test/issues/issue-grab_import_names/issue.gen.go rename to internal/test/parameters/cookie/form/cookie_form.gen.go index 99bfcd9548..71bc55cf88 100644 --- a/internal/test/issues/issue-grab_import_names/issue.gen.go +++ b/internal/test/parameters/cookie/form/cookie_form.gen.go @@ -1,33 +1,45 @@ -// Package grabimportnames provides primitives to interact with the openapi HTTP API. +// Package cookieform provides primitives to interact with the openapi HTTP API. // // Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package grabimportnames +package cookieform import ( - "bytes" - "compress/gzip" "context" - "encoding/base64" - "encoding/json" "fmt" "io" "net/http" "net/url" - "path" "strings" - "github.com/getkin/kin-openapi/openapi3" "github.com/labstack/echo/v4" "github.com/oapi-codegen/runtime" ) -// GetFooParams defines parameters for GetFoo. -type GetFooParams struct { - // Foo base64. bytes. chi. context. echo. errors. fmt. gzip. http. io. json. openapi3. - Foo *string `json:"Foo,omitempty"` +// Object defines model for Object. +type Object struct { + FirstName string `json:"firstName"` + Role string `json:"role"` +} + +// GetCookieParams defines parameters for GetCookie. +type GetCookieParams struct { + // P unexploded primitive + P *int32 `form:"p,omitempty" json:"p,omitempty"` + + // Ep exploded primitive + Ep *int32 `form:"ep,omitempty" json:"ep,omitempty"` + + // A unexploded array + A *[]int32 `form:"a,omitempty" json:"a,omitempty"` - // Bar openapi_types. path. runtime. strings. time.Duration time.Time url. xml. yaml. - Bar *string `json:"Bar,omitempty"` + // Ea exploded array + Ea *[]int32 `form:"ea,omitempty" json:"ea,omitempty"` + + // O unexploded object + O *Object `form:"o,omitempty" json:"o,omitempty"` + + // Eo exploded object + Eo *Object `form:"eo,omitempty" json:"eo,omitempty"` } // RequestEditorFn is the function signature for the RequestEditor callback function @@ -103,12 +115,12 @@ func WithRequestEditorFn(fn RequestEditorFn) ClientOption { // The interface specification for the client above. type ClientInterface interface { - // GetFoo request - GetFoo(ctx context.Context, params *GetFooParams, reqEditors ...RequestEditorFn) (*http.Response, error) + // GetCookie request + GetCookie(ctx context.Context, params *GetCookieParams, reqEditors ...RequestEditorFn) (*http.Response, error) } -func (c *Client) GetFoo(ctx context.Context, params *GetFooParams, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewGetFooRequest(c.Server, params) +func (c *Client) GetCookie(ctx context.Context, params *GetCookieParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetCookieRequest(c.Server, params) if err != nil { return nil, err } @@ -119,8 +131,8 @@ func (c *Client) GetFoo(ctx context.Context, params *GetFooParams, reqEditors .. return c.Client.Do(req) } -// NewGetFooRequest generates requests for GetFoo -func NewGetFooRequest(server string, params *GetFooParams) (*http.Request, error) { +// NewGetCookieRequest generates requests for GetCookie +func NewGetCookieRequest(server string, params *GetCookieParams) (*http.Request, error) { var err error serverURL, err := url.Parse(server) @@ -128,7 +140,7 @@ func NewGetFooRequest(server string, params *GetFooParams) (*http.Request, error return nil, err } - operationPath := fmt.Sprintf("/foo") + operationPath := fmt.Sprintf("/cookie") if operationPath[0] == '/' { operationPath = "." + operationPath } @@ -145,30 +157,96 @@ func NewGetFooRequest(server string, params *GetFooParams) (*http.Request, error if params != nil { - if params.Foo != nil { - var headerParam0 string + if params.P != nil { + var cookieParam0 string - headerParam0, err = runtime.StyleParamWithOptions("simple", false, "Foo", *params.Foo, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) + cookieParam0, err = runtime.StyleParamWithOptions("simple", false, "p", *params.P, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationCookie, Type: "integer", Format: "int32"}) if err != nil { return nil, err } - req.Header.Set("Foo", headerParam0) + cookie0 := &http.Cookie{ + Name: "p", + Value: cookieParam0, + } + req.AddCookie(cookie0) } - if params.Bar != nil { - var headerParam1 string + if params.Ep != nil { + var cookieParam1 string - headerParam1, err = runtime.StyleParamWithOptions("simple", false, "Bar", *params.Bar, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) + cookieParam1, err = runtime.StyleParamWithOptions("simple", true, "ep", *params.Ep, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationCookie, Type: "integer", Format: "int32"}) if err != nil { return nil, err } - req.Header.Set("Bar", headerParam1) + cookie1 := &http.Cookie{ + Name: "ep", + Value: cookieParam1, + } + req.AddCookie(cookie1) } - } + if params.A != nil { + var cookieParam2 string + + cookieParam2, err = runtime.StyleParamWithOptions("simple", false, "a", *params.A, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationCookie, Type: "array", Format: ""}) + if err != nil { + return nil, err + } + + cookie2 := &http.Cookie{ + Name: "a", + Value: cookieParam2, + } + req.AddCookie(cookie2) + } + + if params.Ea != nil { + var cookieParam3 string + + cookieParam3, err = runtime.StyleParamWithOptions("simple", true, "ea", *params.Ea, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationCookie, Type: "array", Format: ""}) + if err != nil { + return nil, err + } + + cookie3 := &http.Cookie{ + Name: "ea", + Value: cookieParam3, + } + req.AddCookie(cookie3) + } + + if params.O != nil { + var cookieParam4 string + cookieParam4, err = runtime.StyleParamWithOptions("simple", false, "o", *params.O, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationCookie, Type: "object", Format: ""}) + if err != nil { + return nil, err + } + + cookie4 := &http.Cookie{ + Name: "o", + Value: cookieParam4, + } + req.AddCookie(cookie4) + } + + if params.Eo != nil { + var cookieParam5 string + + cookieParam5, err = runtime.StyleParamWithOptions("simple", true, "eo", *params.Eo, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationCookie, Type: "object", Format: ""}) + if err != nil { + return nil, err + } + + cookie5 := &http.Cookie{ + Name: "eo", + Value: cookieParam5, + } + req.AddCookie(cookie5) + } + } return req, nil } @@ -215,18 +293,17 @@ func WithBaseURL(baseURL string) ClientOption { // ClientWithResponsesInterface is the interface specification for the client with responses above. type ClientWithResponsesInterface interface { - // GetFooWithResponse request - GetFooWithResponse(ctx context.Context, params *GetFooParams, reqEditors ...RequestEditorFn) (*GetFooResponse, error) + // GetCookieWithResponse request + GetCookieWithResponse(ctx context.Context, params *GetCookieParams, reqEditors ...RequestEditorFn) (*GetCookieResponse, error) } -type GetFooResponse struct { +type GetCookieResponse struct { Body []byte HTTPResponse *http.Response - JSON200 *string } // Status returns HTTPResponse.Status -func (r GetFooResponse) Status() string { +func (r GetCookieResponse) Status() string { if r.HTTPResponse != nil { return r.HTTPResponse.Status } @@ -234,53 +311,43 @@ func (r GetFooResponse) Status() string { } // StatusCode returns HTTPResponse.StatusCode -func (r GetFooResponse) StatusCode() int { +func (r GetCookieResponse) StatusCode() int { if r.HTTPResponse != nil { return r.HTTPResponse.StatusCode } return 0 } -// GetFooWithResponse request returning *GetFooResponse -func (c *ClientWithResponses) GetFooWithResponse(ctx context.Context, params *GetFooParams, reqEditors ...RequestEditorFn) (*GetFooResponse, error) { - rsp, err := c.GetFoo(ctx, params, reqEditors...) +// GetCookieWithResponse request returning *GetCookieResponse +func (c *ClientWithResponses) GetCookieWithResponse(ctx context.Context, params *GetCookieParams, reqEditors ...RequestEditorFn) (*GetCookieResponse, error) { + rsp, err := c.GetCookie(ctx, params, reqEditors...) if err != nil { return nil, err } - return ParseGetFooResponse(rsp) + return ParseGetCookieResponse(rsp) } -// ParseGetFooResponse parses an HTTP response from a GetFooWithResponse call -func ParseGetFooResponse(rsp *http.Response) (*GetFooResponse, error) { +// ParseGetCookieResponse parses an HTTP response from a GetCookieWithResponse call +func ParseGetCookieResponse(rsp *http.Response) (*GetCookieResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &GetFooResponse{ + response := &GetCookieResponse{ Body: bodyBytes, HTTPResponse: rsp, } - switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest string - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON200 = &dest - - } - return response, nil } // ServerInterface represents all server handlers. type ServerInterface interface { - // (GET /foo) - GetFoo(ctx echo.Context, params GetFooParams) error + // (GET /cookie) + GetCookie(ctx echo.Context, params GetCookieParams) error } // ServerInterfaceWrapper converts echo contexts to parameters. @@ -288,47 +355,81 @@ type ServerInterfaceWrapper struct { Handler ServerInterface } -// GetFoo converts echo context to params. -func (w *ServerInterfaceWrapper) GetFoo(ctx echo.Context) error { +// GetCookie converts echo context to params. +func (w *ServerInterfaceWrapper) GetCookie(ctx echo.Context) error { var err error // Parameter object where we will unmarshal all parameters from the context - var params GetFooParams - - headers := ctx.Request().Header - // ------------- Optional header parameter "Foo" ------------- - if valueList, found := headers[http.CanonicalHeaderKey("Foo")]; found { - var Foo string - n := len(valueList) - if n != 1 { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Expected one value for Foo, got %d", n)) + var params GetCookieParams + + if cookie, err := ctx.Cookie("p"); err == nil { + + var value int32 + err = runtime.BindStyledParameterWithOptions("simple", "p", cookie.Value, &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationCookie, Explode: false, Required: false, Type: "integer", Format: "int32"}) + if err != nil { + return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter p: %s", err)) } + params.P = &value - err = runtime.BindStyledParameterWithOptions("simple", "Foo", valueList[0], &Foo, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "string", Format: ""}) + } + + if cookie, err := ctx.Cookie("ep"); err == nil { + + var value int32 + err = runtime.BindStyledParameterWithOptions("simple", "ep", cookie.Value, &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationCookie, Explode: true, Required: false, Type: "integer", Format: "int32"}) + if err != nil { + return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter ep: %s", err)) + } + params.Ep = &value + + } + + if cookie, err := ctx.Cookie("a"); err == nil { + + var value []int32 + err = runtime.BindStyledParameterWithOptions("simple", "a", cookie.Value, &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationCookie, Explode: false, Required: false, Type: "array", Format: ""}) + if err != nil { + return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter a: %s", err)) + } + params.A = &value + + } + + if cookie, err := ctx.Cookie("ea"); err == nil { + + var value []int32 + err = runtime.BindStyledParameterWithOptions("simple", "ea", cookie.Value, &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationCookie, Explode: true, Required: false, Type: "array", Format: ""}) if err != nil { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter Foo: %s", err)) + return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter ea: %s", err)) } + params.Ea = &value - params.Foo = &Foo } - // ------------- Optional header parameter "Bar" ------------- - if valueList, found := headers[http.CanonicalHeaderKey("Bar")]; found { - var Bar string - n := len(valueList) - if n != 1 { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Expected one value for Bar, got %d", n)) + + if cookie, err := ctx.Cookie("o"); err == nil { + + var value Object + err = runtime.BindStyledParameterWithOptions("simple", "o", cookie.Value, &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationCookie, Explode: false, Required: false, Type: "object", Format: ""}) + if err != nil { + return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter o: %s", err)) } + params.O = &value + + } + + if cookie, err := ctx.Cookie("eo"); err == nil { - err = runtime.BindStyledParameterWithOptions("simple", "Bar", valueList[0], &Bar, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "string", Format: ""}) + var value Object + err = runtime.BindStyledParameterWithOptions("simple", "eo", cookie.Value, &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationCookie, Explode: true, Required: false, Type: "object", Format: ""}) if err != nil { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter Bar: %s", err)) + return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter eo: %s", err)) } + params.Eo = &value - params.Bar = &Bar } // Invoke the callback with all the unmarshaled arguments - err = w.Handler.GetFoo(ctx, params) + err = w.Handler.GetCookie(ctx, params) return err } @@ -360,89 +461,6 @@ func RegisterHandlersWithBaseURL(router EchoRouter, si ServerInterface, baseURL Handler: si, } - router.GET(baseURL+"/foo", wrapper.GetFoo) - -} - -// Base64 encoded, gzipped, json marshaled Swagger object -var swaggerSpec = []string{ - - "H4sIAAAAAAAC/3yRzWrrQAyFX0VoPSgmudyFl6W0dN9dKWXiKPEUzw+SUpIGv3uZcVahqTdCwvrm6JwL", - "hrTP2F/Qgk2MPRIROvxi0ZAT9thRRx3ODnPh5EvAHjfU0RodFm+j1t3VPjfGga2WHesgodgCWIC5sPg6", - "edlhj89sTzk3hPjIxqLYv91ubr3y/38E27OxEgxjIBhyMj4ZAQ9jJmCRLEqwj0Zw+A6FYDQrBCETfGpO", - "BFfdm6oiVOzIfseCDpOP9eJFiQ4jR9+cOJc6VpOQDjjP7lbXlfhRf1SCagOBHJOFyATLnhK09vG4nL10", - "ryEyHGUiOMWJ4OzjdFfWg5c/Zb07FNaSk3ILYd11tTSDUsvBlzKFoT2/ql7U2X3e7H4Jbm7fTwAAAP//", - "VfuleiYCAAA=", -} - -// GetSwagger returns the content of the embedded swagger specification file -// or error if failed to decode -func decodeSpec() ([]byte, error) { - zipped, err := base64.StdEncoding.DecodeString(strings.Join(swaggerSpec, "")) - if err != nil { - return nil, fmt.Errorf("error base64 decoding spec: %w", err) - } - zr, err := gzip.NewReader(bytes.NewReader(zipped)) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - var buf bytes.Buffer - _, err = buf.ReadFrom(zr) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - - return buf.Bytes(), nil -} - -var rawSpec = decodeSpecCached() - -// a naive cached of a decoded swagger spec -func decodeSpecCached() func() ([]byte, error) { - data, err := decodeSpec() - return func() ([]byte, error) { - return data, err - } -} - -// Constructs a synthetic filesystem for resolving external references when loading openapi specifications. -func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { - res := make(map[string]func() ([]byte, error)) - if len(pathToFile) > 0 { - res[pathToFile] = rawSpec - } - - return res -} + router.GET(baseURL+"/cookie", wrapper.GetCookie) -// GetSwagger returns the Swagger specification corresponding to the generated code -// in this file. The external references of Swagger specification are resolved. -// The logic of resolving external references is tightly connected to "import-mapping" feature. -// Externally referenced files must be embedded in the corresponding golang packages. -// Urls can be supported but this task was out of the scope. -func GetSwagger() (swagger *openapi3.T, err error) { - resolvePath := PathToRawSpec("") - - loader := openapi3.NewLoader() - loader.IsExternalRefsAllowed = true - loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() - pathToFile = path.Clean(pathToFile) - getSpec, ok := resolvePath[pathToFile] - if !ok { - err1 := fmt.Errorf("path not found: %s", pathToFile) - return nil, err1 - } - return getSpec() - } - var specData []byte - specData, err = rawSpec() - if err != nil { - return - } - swagger, err = loader.LoadFromData(specData) - if err != nil { - return - } - return } diff --git a/internal/test/parameters/cookie/form/cookie_form_test.go b/internal/test/parameters/cookie/form/cookie_form_test.go new file mode 100644 index 0000000000..b8d1ea449e --- /dev/null +++ b/internal/test/parameters/cookie/form/cookie_form_test.go @@ -0,0 +1,144 @@ +package cookieform + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/labstack/echo/v4" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +type testServer struct { + params GetCookieParams +} + +func (s *testServer) reset() { + s.params = GetCookieParams{} +} + +func (s *testServer) GetCookie(ctx echo.Context, params GetCookieParams) error { + s.params = params + return nil +} + +func setup(t *testing.T) (*testServer, *echo.Echo, string) { + t.Helper() + ts := &testServer{} + e := echo.New() + RegisterHandlers(e, ts) + server := "http://example.com" + return ts, e, server +} + +func doRequestWithCookies(t *testing.T, e *echo.Echo, cookies ...*http.Cookie) *httptest.ResponseRecorder { + t.Helper() + req := httptest.NewRequest(http.MethodGet, "/cookie", nil) + for _, c := range cookies { + req.AddCookie(c) + } + rec := httptest.NewRecorder() + e.ServeHTTP(rec, req) + return rec +} + +// TestServerCookieParams tests server-side deserialization of cookie parameters. +func TestServerCookieParams(t *testing.T) { + ts, e, _ := setup(t) + + expectedObject := Object{FirstName: "Alex", Role: "admin"} + expectedArray := []int32{3, 4, 5} + var expectedPrimitive int32 = 5 + + t.Run("unexploded/primitive", func(t *testing.T) { + rec := doRequestWithCookies(t, e, &http.Cookie{Name: "p", Value: "5"}) + assert.Equal(t, http.StatusOK, rec.Code) + require.NotNil(t, ts.params.P) + assert.EqualValues(t, expectedPrimitive, *ts.params.P) + ts.reset() + }) + + t.Run("exploded/primitive", func(t *testing.T) { + rec := doRequestWithCookies(t, e, &http.Cookie{Name: "ep", Value: "5"}) + assert.Equal(t, http.StatusOK, rec.Code) + require.NotNil(t, ts.params.Ep) + assert.EqualValues(t, expectedPrimitive, *ts.params.Ep) + ts.reset() + }) + + t.Run("unexploded/array", func(t *testing.T) { + rec := doRequestWithCookies(t, e, &http.Cookie{Name: "a", Value: "3,4,5"}) + assert.Equal(t, http.StatusOK, rec.Code) + require.NotNil(t, ts.params.A) + assert.EqualValues(t, expectedArray, *ts.params.A) + ts.reset() + }) + + t.Run("exploded/array", func(t *testing.T) { + rec := doRequestWithCookies(t, e, &http.Cookie{Name: "ea", Value: "3,4,5"}) + assert.Equal(t, http.StatusOK, rec.Code) + require.NotNil(t, ts.params.Ea) + assert.EqualValues(t, expectedArray, *ts.params.Ea) + ts.reset() + }) + + t.Run("unexploded/object", func(t *testing.T) { + rec := doRequestWithCookies(t, e, &http.Cookie{Name: "o", Value: "role,admin,firstName,Alex"}) + assert.Equal(t, http.StatusOK, rec.Code) + require.NotNil(t, ts.params.O) + assert.EqualValues(t, expectedObject, *ts.params.O) + ts.reset() + }) + + t.Run("exploded/object", func(t *testing.T) { + rec := doRequestWithCookies(t, e, &http.Cookie{Name: "eo", Value: "role=admin,firstName=Alex"}) + assert.Equal(t, http.StatusOK, rec.Code) + require.NotNil(t, ts.params.Eo) + assert.EqualValues(t, expectedObject, *ts.params.Eo) + ts.reset() + }) +} + +// TestClientCookieParams tests client serialization -> server deserialization round-trip. +func TestClientCookieParams(t *testing.T) { + ts, e, server := setup(t) + + expectedObject := Object{FirstName: "Alex", Role: "admin"} + expectedArray := []int32{3, 4, 5} + var expectedPrimitive int32 = 5 + + params := &GetCookieParams{ + P: &expectedPrimitive, + Ep: &expectedPrimitive, + A: &expectedArray, + Ea: &expectedArray, + O: &expectedObject, + Eo: &expectedObject, + } + + req, err := NewGetCookieRequest(server, params) + require.NoError(t, err) + + rec := httptest.NewRecorder() + e.ServeHTTP(rec, req) + assert.Equal(t, http.StatusOK, rec.Code) + + require.NotNil(t, ts.params.P) + assert.EqualValues(t, expectedPrimitive, *ts.params.P) + + require.NotNil(t, ts.params.Ep) + assert.EqualValues(t, expectedPrimitive, *ts.params.Ep) + + require.NotNil(t, ts.params.A) + assert.EqualValues(t, expectedArray, *ts.params.A) + + require.NotNil(t, ts.params.Ea) + assert.EqualValues(t, expectedArray, *ts.params.Ea) + + require.NotNil(t, ts.params.O) + assert.EqualValues(t, expectedObject, *ts.params.O) + + require.NotNil(t, ts.params.Eo) + assert.EqualValues(t, expectedObject, *ts.params.Eo) +} diff --git a/internal/test/parameters/cookie/form/doc.go b/internal/test/parameters/cookie/form/doc.go new file mode 100644 index 0000000000..187419b28f --- /dev/null +++ b/internal/test/parameters/cookie/form/doc.go @@ -0,0 +1,3 @@ +package cookieform + +//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml spec.yaml diff --git a/internal/test/parameters/cookie/form/spec.yaml b/internal/test/parameters/cookie/form/spec.yaml new file mode 100644 index 0000000000..9943489a3c --- /dev/null +++ b/internal/test/parameters/cookie/form/spec.yaml @@ -0,0 +1,74 @@ +openapi: "3.0.1" +info: + version: 1.0.0 + title: Cookie Parameters - Form Style +paths: + /cookie: + get: + operationId: getCookie + parameters: + - name: p + description: unexploded primitive + in: cookie + required: false + explode: false + schema: + type: integer + format: int32 + - name: ep + description: exploded primitive + in: cookie + required: false + explode: true + schema: + type: integer + format: int32 + - name: a + description: unexploded array + in: cookie + required: false + explode: false + schema: + type: array + items: + type: integer + format: int32 + - name: ea + description: exploded array + in: cookie + required: false + explode: true + schema: + type: array + items: + type: integer + format: int32 + - name: o + description: unexploded object + in: cookie + required: false + explode: false + schema: + $ref: "#/components/schemas/Object" + - name: eo + description: exploded object + in: cookie + required: false + explode: true + schema: + $ref: "#/components/schemas/Object" + responses: + "200": + description: OK +components: + schemas: + Object: + type: object + properties: + role: + type: string + firstName: + type: string + required: + - role + - firstName diff --git a/internal/test/parameters/doc.go b/internal/test/parameters/doc.go deleted file mode 100644 index 30d5b502e5..0000000000 --- a/internal/test/parameters/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -package parameters - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml parameters.yaml diff --git a/internal/test/issues/issue-312/config.yaml b/internal/test/parameters/encoding/config.yaml similarity index 68% rename from internal/test/issues/issue-312/config.yaml rename to internal/test/parameters/encoding/config.yaml index 39cb190515..4d967600fa 100644 --- a/internal/test/issues/issue-312/config.yaml +++ b/internal/test/parameters/encoding/config.yaml @@ -1,8 +1,7 @@ # yaml-language-server: $schema=../../../../configuration-schema.json -package: issue312 +package: encoding generate: echo-server: true client: true models: true - embedded-spec: true -output: issue.gen.go +output: encoding.gen.go diff --git a/internal/test/externalref/packageB/doc.go b/internal/test/parameters/encoding/doc.go similarity index 86% rename from internal/test/externalref/packageB/doc.go rename to internal/test/parameters/encoding/doc.go index 0dc18f8255..d3adbbc779 100644 --- a/internal/test/externalref/packageB/doc.go +++ b/internal/test/parameters/encoding/doc.go @@ -1,3 +1,3 @@ -package packageb +package encoding //go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml spec.yaml diff --git a/internal/test/issues/issue-312/issue.gen.go b/internal/test/parameters/encoding/encoding.gen.go similarity index 79% rename from internal/test/issues/issue-312/issue.gen.go rename to internal/test/parameters/encoding/encoding.gen.go index 1686dac248..3f857f6d84 100644 --- a/internal/test/issues/issue-312/issue.gen.go +++ b/internal/test/parameters/encoding/encoding.gen.go @@ -1,44 +1,29 @@ -// Package issue312 provides primitives to interact with the openapi HTTP API. +// Package encoding provides primitives to interact with the openapi HTTP API. // // Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package issue312 +package encoding import ( "bytes" - "compress/gzip" "context" - "encoding/base64" "encoding/json" "fmt" "io" "net/http" "net/url" - "path" "strings" - "github.com/getkin/kin-openapi/openapi3" "github.com/labstack/echo/v4" "github.com/oapi-codegen/runtime" ) -// Error defines model for Error. -type Error struct { - // Code Error code - Code int32 `json:"code"` - - // Message Error message - Message string `json:"message"` -} - // Pet defines model for Pet. type Pet struct { - // Name The name of the pet. Name string `json:"name"` } // PetNames defines model for PetNames. type PetNames struct { - // Names The names of the pets. Names []string `json:"names"` } @@ -315,7 +300,6 @@ type ValidatePetsResponse struct { Body []byte HTTPResponse *http.Response JSON200 *[]Pet - JSONDefault *Error } // Status returns HTTPResponse.Status @@ -407,13 +391,6 @@ func ParseValidatePetsResponse(rsp *http.Response) (*ValidatePetsResponse, error } response.JSON200 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: - var dest Error - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSONDefault = &dest - } return response, nil @@ -421,10 +398,10 @@ func ParseValidatePetsResponse(rsp *http.Response) (*ValidatePetsResponse, error // ServerInterface represents all server handlers. type ServerInterface interface { - // Get pet given identifier. + // Path parameter with potential reserved characters // (GET /pets/{petId}) GetPet(ctx echo.Context, petId string) error - // Validate pets + // Path with colon (not a parameter) // (POST /pets:validate) ValidatePets(ctx echo.Context) error } @@ -491,89 +468,3 @@ func RegisterHandlersWithBaseURL(router EchoRouter, si ServerInterface, baseURL router.POST(baseURL+"/pets:validate", wrapper.ValidatePets) } - -// Base64 encoded, gzipped, json marshaled Swagger object -var swaggerSpec = []string{ - - "H4sIAAAAAAAC/6xUPW/bMBD9K8S1o2A58aaxRVF4KTIUXQIPrHSSmZof5Z2MGgb/e3Gk7NqxjAzNFIX3", - "eO/de0cfofU2eIeOCZojULtFq/Pnlxh9lI8QfcDIBvNx6zuUvx1SG01g4x00BaxyrYLeR6sZGjCOV49Q", - "AR8Cln9xwAipAotEerjb6FQ+XyWOxg2QUgURf48mYgfNM0yEJ/gmVfCEfCvaaTvD9X2LSirK94q3qALy", - "4k3K3GpzRvmfL9gyFOJv2ha+W3a6T08X/CQCDKPN+FdKzqQ6Rn2YVUYz0gRnXO9vFXzeYvuLVFGrkFod", - "jBtETtBRW2SMJIYY3knDNdGIavXwqBiJoYI9RiqdHhbLxVIU+oBOBwMNrPJRBUHzNk9Ty3z1MSCvuyQH", - "Q4lKyLUoWnfQwFdkiVDunSU0z0cwQiO9oJrihNwJLk3gOGI1LfGMgWkjYAreUQnkcbksO+0YXRajQ9iZ", - "NsupX0hmO170+xixhwY+1P9eTT09mVpUZ6+vPd7rnekk2pwXjdbqeChzyqkazB6dMh06Nr3BuMi47FWT", - "72rOqxs88W2CPyZE3h2oXnl5qj6VoviExJ98d3jPqcvWp+t1lCTSf7p9fgdv2n7zMu7HQJBrvR53/G4u", - "lN/KGdrR4Z+ALWOncMJcLsF1fCml9DcAAP//Z6kfG5EFAAA=", -} - -// GetSwagger returns the content of the embedded swagger specification file -// or error if failed to decode -func decodeSpec() ([]byte, error) { - zipped, err := base64.StdEncoding.DecodeString(strings.Join(swaggerSpec, "")) - if err != nil { - return nil, fmt.Errorf("error base64 decoding spec: %w", err) - } - zr, err := gzip.NewReader(bytes.NewReader(zipped)) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - var buf bytes.Buffer - _, err = buf.ReadFrom(zr) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - - return buf.Bytes(), nil -} - -var rawSpec = decodeSpecCached() - -// a naive cached of a decoded swagger spec -func decodeSpecCached() func() ([]byte, error) { - data, err := decodeSpec() - return func() ([]byte, error) { - return data, err - } -} - -// Constructs a synthetic filesystem for resolving external references when loading openapi specifications. -func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { - res := make(map[string]func() ([]byte, error)) - if len(pathToFile) > 0 { - res[pathToFile] = rawSpec - } - - return res -} - -// GetSwagger returns the Swagger specification corresponding to the generated code -// in this file. The external references of Swagger specification are resolved. -// The logic of resolving external references is tightly connected to "import-mapping" feature. -// Externally referenced files must be embedded in the corresponding golang packages. -// Urls can be supported but this task was out of the scope. -func GetSwagger() (swagger *openapi3.T, err error) { - resolvePath := PathToRawSpec("") - - loader := openapi3.NewLoader() - loader.IsExternalRefsAllowed = true - loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() - pathToFile = path.Clean(pathToFile) - getSpec, ok := resolvePath[pathToFile] - if !ok { - err1 := fmt.Errorf("path not found: %s", pathToFile) - return nil, err1 - } - return getSpec() - } - var specData []byte - specData, err = rawSpec() - if err != nil { - return - } - swagger, err = loader.LoadFromData(specData) - if err != nil { - return - } - return -} diff --git a/internal/test/parameters/encoding/encoding_test.go b/internal/test/parameters/encoding/encoding_test.go new file mode 100644 index 0000000000..529f52ac27 --- /dev/null +++ b/internal/test/parameters/encoding/encoding_test.go @@ -0,0 +1,108 @@ +package encoding + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "testing" + + "github.com/labstack/echo/v4" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" +) + +// HTTPRequestDoerMock mocks the HttpRequestDoer interface. +type HTTPRequestDoerMock struct { + mock.Mock +} + +func (m *HTTPRequestDoerMock) Do(req *http.Request) (*http.Response, error) { + args := m.Called(req) + if args.Get(0) == nil { + return nil, args.Error(1) + } + return args.Get(0).(*http.Response), args.Error(1) +} + +// mockServer implements the ServerInterface for testing. +type mockServer struct { + getPet func(ctx echo.Context, petId string) error + validatePets func(ctx echo.Context) error +} + +func (m *mockServer) GetPet(ctx echo.Context, petId string) error { + if m.getPet != nil { + return m.getPet(ctx, petId) + } + return ctx.NoContent(http.StatusNotImplemented) +} + +func (m *mockServer) ValidatePets(ctx echo.Context) error { + if m.validatePets != nil { + return m.validatePets(ctx) + } + return ctx.NoContent(http.StatusNotImplemented) +} + +func TestClient_PathWithColon(t *testing.T) { + doer := &HTTPRequestDoerMock{} + client, _ := NewClientWithResponses("http://host", WithHTTPClient(doer)) + + doer.On("Do", mock.Anything).Return(nil, errors.New("expected")).Run(func(args mock.Arguments) { + req := args.Get(0).(*http.Request) + assert.Equal(t, "http://host/pets:validate", req.URL.String()) + }) + + _, _ = client.ValidatePetsWithResponse(context.Background(), ValidatePetsJSONRequestBody{ + Names: []string{"fido"}, + }) + doer.AssertExpectations(t) +} + +func TestClient_PathParamWithID(t *testing.T) { + doer := &HTTPRequestDoerMock{} + client, _ := NewClientWithResponses("http://host", WithHTTPClient(doer)) + + doer.On("Do", mock.Anything).Return(nil, errors.New("expected")).Run(func(args mock.Arguments) { + req := args.Get(0).(*http.Request) + assert.Equal(t, "/pets/id", req.URL.Path) + }) + + _, _ = client.GetPetWithResponse(context.Background(), "id") + doer.AssertExpectations(t) +} + +func TestClient_PathParamWithReservedChar(t *testing.T) { + doer := &HTTPRequestDoerMock{} + client, _ := NewClientWithResponses("http://host", WithHTTPClient(doer)) + + doer.On("Do", mock.Anything).Return(nil, errors.New("expected")).Run(func(args mock.Arguments) { + req := args.Get(0).(*http.Request) + assert.Equal(t, "http://host/pets/id1%2Fid2", req.URL.String()) + }) + + _, _ = client.GetPetWithResponse(context.Background(), "id1/id2") + doer.AssertExpectations(t) +} + +func TestServer_UnescapesPathParam(t *testing.T) { + e := echo.New() + m := &mockServer{} + RegisterHandlers(e, m) + + receivedPetID := "" + m.getPet = func(ctx echo.Context, petId string) error { + receivedPetID = petId + return ctx.NoContent(http.StatusOK) + } + + // Use the generated client to build the request, then serve via recorder. + req, err := NewGetPetRequest("http://example.com", "id1/id2") + require.NoError(t, err) + rec := httptest.NewRecorder() + e.ServeHTTP(rec, req) + assert.Equal(t, http.StatusOK, rec.Code) + assert.Equal(t, "id1/id2", receivedPetID) +} diff --git a/internal/test/issues/issue-312/spec.yaml b/internal/test/parameters/encoding/spec.yaml similarity index 52% rename from internal/test/issues/issue-312/spec.yaml rename to internal/test/parameters/encoding/spec.yaml index f7f20270f0..d881969fd9 100644 --- a/internal/test/issues/issue-312/spec.yaml +++ b/internal/test/parameters/encoding/spec.yaml @@ -1,38 +1,31 @@ openapi: "3.0.0" info: version: 1.0.0 - title: Issue 312 test - description: Checks proper escaping of parameters + title: Parameter Encoding + description: Tests proper escaping of path parameters and special characters in paths paths: /pets:validate: post: - summary: Validate pets - description: Validate pets + summary: Path with colon (not a parameter) operationId: validatePets requestBody: required: true content: application/json: schema: - $ref: '#/components/schemas/PetNames' + $ref: "#/components/schemas/PetNames" responses: - '200': + "200": description: valid pets content: application/json: schema: type: array items: - $ref: '#/components/schemas/Pet' - default: - description: unexpected error - content: - application/json: - schema: - $ref: '#/components/schemas/Error' + $ref: "#/components/schemas/Pet" /pets/{petId}: get: - summary: Get pet given identifier. + summary: Path parameter with potential reserved characters operationId: getPet parameters: - name: petId @@ -41,12 +34,12 @@ paths: schema: type: string responses: - '200': + "200": description: valid pet content: application/json: schema: - $ref: '#/components/schemas/Pet' + $ref: "#/components/schemas/Pet" components: schemas: Pet: @@ -56,8 +49,6 @@ components: properties: name: type: string - description: The name of the pet. - PetNames: type: object required: @@ -65,19 +56,5 @@ components: properties: names: type: array - description: The names of the pets. items: type: string - - Error: - required: - - code - - message - properties: - code: - type: integer - format: int32 - description: Error code - message: - type: string - description: Error message diff --git a/internal/test/parameters/header/simple/config.yaml b/internal/test/parameters/header/simple/config.yaml new file mode 100644 index 0000000000..8a74624b42 --- /dev/null +++ b/internal/test/parameters/header/simple/config.yaml @@ -0,0 +1,7 @@ +# yaml-language-server: $schema=../../../../../../configuration-schema.json +package: headersimple +generate: + echo-server: true + client: true + models: true +output: header_simple.gen.go diff --git a/internal/test/parameters/header/simple/doc.go b/internal/test/parameters/header/simple/doc.go new file mode 100644 index 0000000000..0cc1b3431f --- /dev/null +++ b/internal/test/parameters/header/simple/doc.go @@ -0,0 +1,3 @@ +package headersimple + +//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml spec.yaml diff --git a/internal/test/parameters/header/simple/header_simple.gen.go b/internal/test/parameters/header/simple/header_simple.gen.go new file mode 100644 index 0000000000..df76a2fd37 --- /dev/null +++ b/internal/test/parameters/header/simple/header_simple.gen.go @@ -0,0 +1,459 @@ +// Package headersimple provides primitives to interact with the openapi HTTP API. +// +// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. +package headersimple + +import ( + "context" + "fmt" + "io" + "net/http" + "net/url" + "strings" + + "github.com/labstack/echo/v4" + "github.com/oapi-codegen/runtime" +) + +// Object defines model for Object. +type Object struct { + FirstName string `json:"firstName"` + Role string `json:"role"` +} + +// GetHeaderParams defines parameters for GetHeader. +type GetHeaderParams struct { + XPrimitive *int32 `json:"X-Primitive,omitempty"` + XPrimitiveExploded *int32 `json:"X-Primitive-Exploded,omitempty"` + XArray *[]int32 `json:"X-Array,omitempty"` + XArrayExploded *[]int32 `json:"X-Array-Exploded,omitempty"` + XObject *Object `json:"X-Object,omitempty"` + XObjectExploded *Object `json:"X-Object-Exploded,omitempty"` +} + +// RequestEditorFn is the function signature for the RequestEditor callback function +type RequestEditorFn func(ctx context.Context, req *http.Request) error + +// Doer performs HTTP requests. +// +// The standard http.Client implements this interface. +type HttpRequestDoer interface { + Do(req *http.Request) (*http.Response, error) +} + +// Client which conforms to the OpenAPI3 specification for this service. +type Client struct { + // The endpoint of the server conforming to this interface, with scheme, + // https://api.deepmap.com for example. This can contain a path relative + // to the server, such as https://api.deepmap.com/dev-test, and all the + // paths in the swagger spec will be appended to the server. + Server string + + // Doer for performing requests, typically a *http.Client with any + // customized settings, such as certificate chains. + Client HttpRequestDoer + + // A list of callbacks for modifying requests which are generated before sending over + // the network. + RequestEditors []RequestEditorFn +} + +// ClientOption allows setting custom parameters during construction +type ClientOption func(*Client) error + +// Creates a new Client, with reasonable defaults +func NewClient(server string, opts ...ClientOption) (*Client, error) { + // create a client with sane default values + client := Client{ + Server: server, + } + // mutate client and add all optional params + for _, o := range opts { + if err := o(&client); err != nil { + return nil, err + } + } + // ensure the server URL always has a trailing slash + if !strings.HasSuffix(client.Server, "/") { + client.Server += "/" + } + // create httpClient, if not already present + if client.Client == nil { + client.Client = &http.Client{} + } + return &client, nil +} + +// WithHTTPClient allows overriding the default Doer, which is +// automatically created using http.Client. This is useful for tests. +func WithHTTPClient(doer HttpRequestDoer) ClientOption { + return func(c *Client) error { + c.Client = doer + return nil + } +} + +// WithRequestEditorFn allows setting up a callback function, which will be +// called right before sending the request. This can be used to mutate the request. +func WithRequestEditorFn(fn RequestEditorFn) ClientOption { + return func(c *Client) error { + c.RequestEditors = append(c.RequestEditors, fn) + return nil + } +} + +// The interface specification for the client above. +type ClientInterface interface { + // GetHeader request + GetHeader(ctx context.Context, params *GetHeaderParams, reqEditors ...RequestEditorFn) (*http.Response, error) +} + +func (c *Client) GetHeader(ctx context.Context, params *GetHeaderParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetHeaderRequest(c.Server, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +// NewGetHeaderRequest generates requests for GetHeader +func NewGetHeaderRequest(server string, params *GetHeaderParams) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/header") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + if params != nil { + + if params.XPrimitive != nil { + var headerParam0 string + + headerParam0, err = runtime.StyleParamWithOptions("simple", false, "X-Primitive", *params.XPrimitive, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "integer", Format: "int32"}) + if err != nil { + return nil, err + } + + req.Header.Set("X-Primitive", headerParam0) + } + + if params.XPrimitiveExploded != nil { + var headerParam1 string + + headerParam1, err = runtime.StyleParamWithOptions("simple", true, "X-Primitive-Exploded", *params.XPrimitiveExploded, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "integer", Format: "int32"}) + if err != nil { + return nil, err + } + + req.Header.Set("X-Primitive-Exploded", headerParam1) + } + + if params.XArray != nil { + var headerParam2 string + + headerParam2, err = runtime.StyleParamWithOptions("simple", false, "X-Array", *params.XArray, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "array", Format: ""}) + if err != nil { + return nil, err + } + + req.Header.Set("X-Array", headerParam2) + } + + if params.XArrayExploded != nil { + var headerParam3 string + + headerParam3, err = runtime.StyleParamWithOptions("simple", true, "X-Array-Exploded", *params.XArrayExploded, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "array", Format: ""}) + if err != nil { + return nil, err + } + + req.Header.Set("X-Array-Exploded", headerParam3) + } + + if params.XObject != nil { + var headerParam4 string + + headerParam4, err = runtime.StyleParamWithOptions("simple", false, "X-Object", *params.XObject, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "object", Format: ""}) + if err != nil { + return nil, err + } + + req.Header.Set("X-Object", headerParam4) + } + + if params.XObjectExploded != nil { + var headerParam5 string + + headerParam5, err = runtime.StyleParamWithOptions("simple", true, "X-Object-Exploded", *params.XObjectExploded, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "object", Format: ""}) + if err != nil { + return nil, err + } + + req.Header.Set("X-Object-Exploded", headerParam5) + } + + } + + return req, nil +} + +func (c *Client) applyEditors(ctx context.Context, req *http.Request, additionalEditors []RequestEditorFn) error { + for _, r := range c.RequestEditors { + if err := r(ctx, req); err != nil { + return err + } + } + for _, r := range additionalEditors { + if err := r(ctx, req); err != nil { + return err + } + } + return nil +} + +// ClientWithResponses builds on ClientInterface to offer response payloads +type ClientWithResponses struct { + ClientInterface +} + +// NewClientWithResponses creates a new ClientWithResponses, which wraps +// Client with return type handling +func NewClientWithResponses(server string, opts ...ClientOption) (*ClientWithResponses, error) { + client, err := NewClient(server, opts...) + if err != nil { + return nil, err + } + return &ClientWithResponses{client}, nil +} + +// WithBaseURL overrides the baseURL. +func WithBaseURL(baseURL string) ClientOption { + return func(c *Client) error { + newBaseURL, err := url.Parse(baseURL) + if err != nil { + return err + } + c.Server = newBaseURL.String() + return nil + } +} + +// ClientWithResponsesInterface is the interface specification for the client with responses above. +type ClientWithResponsesInterface interface { + // GetHeaderWithResponse request + GetHeaderWithResponse(ctx context.Context, params *GetHeaderParams, reqEditors ...RequestEditorFn) (*GetHeaderResponse, error) +} + +type GetHeaderResponse struct { + Body []byte + HTTPResponse *http.Response +} + +// Status returns HTTPResponse.Status +func (r GetHeaderResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetHeaderResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// GetHeaderWithResponse request returning *GetHeaderResponse +func (c *ClientWithResponses) GetHeaderWithResponse(ctx context.Context, params *GetHeaderParams, reqEditors ...RequestEditorFn) (*GetHeaderResponse, error) { + rsp, err := c.GetHeader(ctx, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetHeaderResponse(rsp) +} + +// ParseGetHeaderResponse parses an HTTP response from a GetHeaderWithResponse call +func ParseGetHeaderResponse(rsp *http.Response) (*GetHeaderResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetHeaderResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + return response, nil +} + +// ServerInterface represents all server handlers. +type ServerInterface interface { + + // (GET /header) + GetHeader(ctx echo.Context, params GetHeaderParams) error +} + +// ServerInterfaceWrapper converts echo contexts to parameters. +type ServerInterfaceWrapper struct { + Handler ServerInterface +} + +// GetHeader converts echo context to params. +func (w *ServerInterfaceWrapper) GetHeader(ctx echo.Context) error { + var err error + + // Parameter object where we will unmarshal all parameters from the context + var params GetHeaderParams + + headers := ctx.Request().Header + // ------------- Optional header parameter "X-Primitive" ------------- + if valueList, found := headers[http.CanonicalHeaderKey("X-Primitive")]; found { + var XPrimitive int32 + n := len(valueList) + if n != 1 { + return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Expected one value for X-Primitive, got %d", n)) + } + + err = runtime.BindStyledParameterWithOptions("simple", "X-Primitive", valueList[0], &XPrimitive, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int32"}) + if err != nil { + return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter X-Primitive: %s", err)) + } + + params.XPrimitive = &XPrimitive + } + // ------------- Optional header parameter "X-Primitive-Exploded" ------------- + if valueList, found := headers[http.CanonicalHeaderKey("X-Primitive-Exploded")]; found { + var XPrimitiveExploded int32 + n := len(valueList) + if n != 1 { + return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Expected one value for X-Primitive-Exploded, got %d", n)) + } + + err = runtime.BindStyledParameterWithOptions("simple", "X-Primitive-Exploded", valueList[0], &XPrimitiveExploded, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: true, Required: false, Type: "integer", Format: "int32"}) + if err != nil { + return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter X-Primitive-Exploded: %s", err)) + } + + params.XPrimitiveExploded = &XPrimitiveExploded + } + // ------------- Optional header parameter "X-Array" ------------- + if valueList, found := headers[http.CanonicalHeaderKey("X-Array")]; found { + var XArray []int32 + n := len(valueList) + if n != 1 { + return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Expected one value for X-Array, got %d", n)) + } + + err = runtime.BindStyledParameterWithOptions("simple", "X-Array", valueList[0], &XArray, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "array", Format: ""}) + if err != nil { + return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter X-Array: %s", err)) + } + + params.XArray = &XArray + } + // ------------- Optional header parameter "X-Array-Exploded" ------------- + if valueList, found := headers[http.CanonicalHeaderKey("X-Array-Exploded")]; found { + var XArrayExploded []int32 + n := len(valueList) + if n != 1 { + return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Expected one value for X-Array-Exploded, got %d", n)) + } + + err = runtime.BindStyledParameterWithOptions("simple", "X-Array-Exploded", valueList[0], &XArrayExploded, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: true, Required: false, Type: "array", Format: ""}) + if err != nil { + return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter X-Array-Exploded: %s", err)) + } + + params.XArrayExploded = &XArrayExploded + } + // ------------- Optional header parameter "X-Object" ------------- + if valueList, found := headers[http.CanonicalHeaderKey("X-Object")]; found { + var XObject Object + n := len(valueList) + if n != 1 { + return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Expected one value for X-Object, got %d", n)) + } + + err = runtime.BindStyledParameterWithOptions("simple", "X-Object", valueList[0], &XObject, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "object", Format: ""}) + if err != nil { + return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter X-Object: %s", err)) + } + + params.XObject = &XObject + } + // ------------- Optional header parameter "X-Object-Exploded" ------------- + if valueList, found := headers[http.CanonicalHeaderKey("X-Object-Exploded")]; found { + var XObjectExploded Object + n := len(valueList) + if n != 1 { + return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Expected one value for X-Object-Exploded, got %d", n)) + } + + err = runtime.BindStyledParameterWithOptions("simple", "X-Object-Exploded", valueList[0], &XObjectExploded, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: true, Required: false, Type: "object", Format: ""}) + if err != nil { + return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter X-Object-Exploded: %s", err)) + } + + params.XObjectExploded = &XObjectExploded + } + + // Invoke the callback with all the unmarshaled arguments + err = w.Handler.GetHeader(ctx, params) + return err +} + +// This is a simple interface which specifies echo.Route addition functions which +// are present on both echo.Echo and echo.Group, since we want to allow using +// either of them for path registration +type EchoRouter interface { + CONNECT(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route + DELETE(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route + GET(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route + HEAD(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route + OPTIONS(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route + PATCH(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route + POST(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route + PUT(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route + TRACE(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route +} + +// RegisterHandlers adds each server route to the EchoRouter. +func RegisterHandlers(router EchoRouter, si ServerInterface) { + RegisterHandlersWithBaseURL(router, si, "") +} + +// Registers handlers, and prepends BaseURL to the paths, so that the paths +// can be served under a prefix. +func RegisterHandlersWithBaseURL(router EchoRouter, si ServerInterface, baseURL string) { + + wrapper := ServerInterfaceWrapper{ + Handler: si, + } + + router.GET(baseURL+"/header", wrapper.GetHeader) + +} diff --git a/internal/test/parameters/header/simple/header_simple_test.go b/internal/test/parameters/header/simple/header_simple_test.go new file mode 100644 index 0000000000..4cfcd46240 --- /dev/null +++ b/internal/test/parameters/header/simple/header_simple_test.go @@ -0,0 +1,156 @@ +package headersimple + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/labstack/echo/v4" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +type testServer struct { + params GetHeaderParams +} + +func (s *testServer) reset() { + s.params = GetHeaderParams{} +} + +func (s *testServer) GetHeader(ctx echo.Context, params GetHeaderParams) error { + s.params = params + return nil +} + +func setup(t *testing.T) (*testServer, *echo.Echo, string) { + t.Helper() + ts := &testServer{} + e := echo.New() + RegisterHandlers(e, ts) + server := "http://example.com" + return ts, e, server +} + +func doHeaderRequest(t *testing.T, e *echo.Echo, headers map[string]string) *httptest.ResponseRecorder { + t.Helper() + req := httptest.NewRequest(http.MethodGet, "/header", nil) + for k, v := range headers { + req.Header.Set(k, v) + } + rec := httptest.NewRecorder() + e.ServeHTTP(rec, req) + return rec +} + +// TestServerSimpleHeaderParams tests server-side deserialization of simple-style header parameters. +func TestServerSimpleHeaderParams(t *testing.T) { + ts, e, _ := setup(t) + + expectedObject := Object{FirstName: "Alex", Role: "admin"} + expectedArray := []int32{3, 4, 5} + var expectedPrimitive int32 = 5 + + t.Run("primitive", func(t *testing.T) { + rec := doHeaderRequest(t, e, map[string]string{ + "X-Primitive": "5", + }) + assert.Equal(t, http.StatusOK, rec.Code) + require.NotNil(t, ts.params.XPrimitive) + assert.EqualValues(t, expectedPrimitive, *ts.params.XPrimitive) + ts.reset() + }) + + t.Run("primitiveExploded", func(t *testing.T) { + rec := doHeaderRequest(t, e, map[string]string{ + "X-Primitive-Exploded": "5", + }) + assert.Equal(t, http.StatusOK, rec.Code) + require.NotNil(t, ts.params.XPrimitiveExploded) + assert.EqualValues(t, expectedPrimitive, *ts.params.XPrimitiveExploded) + ts.reset() + }) + + t.Run("array", func(t *testing.T) { + rec := doHeaderRequest(t, e, map[string]string{ + "X-Array": "3,4,5", + }) + assert.Equal(t, http.StatusOK, rec.Code) + require.NotNil(t, ts.params.XArray) + assert.EqualValues(t, expectedArray, *ts.params.XArray) + ts.reset() + }) + + t.Run("arrayExploded", func(t *testing.T) { + rec := doHeaderRequest(t, e, map[string]string{ + "X-Array-Exploded": "3,4,5", + }) + assert.Equal(t, http.StatusOK, rec.Code) + require.NotNil(t, ts.params.XArrayExploded) + assert.EqualValues(t, expectedArray, *ts.params.XArrayExploded) + ts.reset() + }) + + t.Run("object", func(t *testing.T) { + rec := doHeaderRequest(t, e, map[string]string{ + "X-Object": "role,admin,firstName,Alex", + }) + assert.Equal(t, http.StatusOK, rec.Code) + require.NotNil(t, ts.params.XObject) + assert.EqualValues(t, expectedObject, *ts.params.XObject) + ts.reset() + }) + + t.Run("objectExploded", func(t *testing.T) { + rec := doHeaderRequest(t, e, map[string]string{ + "X-Object-Exploded": "role=admin,firstName=Alex", + }) + assert.Equal(t, http.StatusOK, rec.Code) + require.NotNil(t, ts.params.XObjectExploded) + assert.EqualValues(t, expectedObject, *ts.params.XObjectExploded) + ts.reset() + }) +} + +// TestClientSimpleHeaderParams tests client serialization → server deserialization round-trip. +func TestClientSimpleHeaderParams(t *testing.T) { + ts, e, server := setup(t) + + expectedObject := Object{FirstName: "Alex", Role: "admin"} + expectedArray := []int32{3, 4, 5} + var expectedPrimitive int32 = 5 + + params := &GetHeaderParams{ + XPrimitive: &expectedPrimitive, + XPrimitiveExploded: &expectedPrimitive, + XArray: &expectedArray, + XArrayExploded: &expectedArray, + XObject: &expectedObject, + XObjectExploded: &expectedObject, + } + + req, err := NewGetHeaderRequest(server, params) + require.NoError(t, err) + + rec := httptest.NewRecorder() + e.ServeHTTP(rec, req) + assert.Equal(t, http.StatusOK, rec.Code) + + require.NotNil(t, ts.params.XPrimitive) + assert.EqualValues(t, expectedPrimitive, *ts.params.XPrimitive) + + require.NotNil(t, ts.params.XPrimitiveExploded) + assert.EqualValues(t, expectedPrimitive, *ts.params.XPrimitiveExploded) + + require.NotNil(t, ts.params.XArray) + assert.EqualValues(t, expectedArray, *ts.params.XArray) + + require.NotNil(t, ts.params.XArrayExploded) + assert.EqualValues(t, expectedArray, *ts.params.XArrayExploded) + + require.NotNil(t, ts.params.XObject) + assert.EqualValues(t, expectedObject, *ts.params.XObject) + + require.NotNil(t, ts.params.XObjectExploded) + assert.EqualValues(t, expectedObject, *ts.params.XObjectExploded) +} diff --git a/internal/test/parameters/header/simple/spec.yaml b/internal/test/parameters/header/simple/spec.yaml new file mode 100644 index 0000000000..34f384c9e5 --- /dev/null +++ b/internal/test/parameters/header/simple/spec.yaml @@ -0,0 +1,74 @@ +openapi: "3.0.1" +info: + version: 1.0.0 + title: Header Parameters - Simple Style +paths: + /header: + get: + operationId: getHeader + parameters: + - name: X-Primitive + in: header + required: false + style: simple + explode: false + schema: + type: integer + format: int32 + - name: X-Primitive-Exploded + in: header + required: false + style: simple + explode: true + schema: + type: integer + format: int32 + - name: X-Array + in: header + required: false + style: simple + explode: false + schema: + type: array + items: + type: integer + format: int32 + - name: X-Array-Exploded + in: header + required: false + style: simple + explode: true + schema: + type: array + items: + type: integer + format: int32 + - name: X-Object + in: header + required: false + style: simple + explode: false + schema: + $ref: "#/components/schemas/Object" + - name: X-Object-Exploded + in: header + required: false + style: simple + explode: true + schema: + $ref: "#/components/schemas/Object" + responses: + "200": + description: OK +components: + schemas: + Object: + type: object + properties: + role: + type: string + firstName: + type: string + required: + - role + - firstName diff --git a/internal/test/parameters/parameters.gen.go b/internal/test/parameters/parameters.gen.go deleted file mode 100644 index 5821715fc2..0000000000 --- a/internal/test/parameters/parameters.gen.go +++ /dev/null @@ -1,3517 +0,0 @@ -// Package parameters provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package parameters - -import ( - "bytes" - "compress/gzip" - "context" - "encoding/base64" - "encoding/json" - "fmt" - "io" - "net/http" - "net/url" - "path" - "strings" - - "github.com/getkin/kin-openapi/openapi3" - "github.com/labstack/echo/v4" - "github.com/oapi-codegen/runtime" -) - -// Defines values for EnumParamsParamsEnumPathParam. -const ( - N100 EnumParamsParamsEnumPathParam = 100 - N200 EnumParamsParamsEnumPathParam = 200 -) - -// Valid indicates whether the value is a known member of the EnumParamsParamsEnumPathParam enum. -func (e EnumParamsParamsEnumPathParam) Valid() bool { - switch e { - case N100: - return true - case N200: - return true - default: - return false - } -} - -// ComplexObject defines model for ComplexObject. -type ComplexObject struct { - Id int `json:"Id"` - IsAdmin bool `json:"IsAdmin"` - Object Object `json:"Object"` -} - -// Object defines model for Object. -type Object struct { - FirstName string `json:"firstName"` - Role string `json:"role"` -} - -// GetCookieParams defines parameters for GetCookie. -type GetCookieParams struct { - // P primitive - P *int32 `form:"p,omitempty" json:"p,omitempty"` - - // Ep primitive - Ep *int32 `form:"ep,omitempty" json:"ep,omitempty"` - - // Ea exploded array - Ea *[]int32 `form:"ea,omitempty" json:"ea,omitempty"` - - // A array - A *[]int32 `form:"a,omitempty" json:"a,omitempty"` - - // Eo exploded object - Eo *Object `form:"eo,omitempty" json:"eo,omitempty"` - - // O object - O *Object `form:"o,omitempty" json:"o,omitempty"` - - // Co complex object - Co *ComplexObject `form:"co,omitempty" json:"co,omitempty"` - - // N1s name starting with number - N1s *string `form:"1s,omitempty" json:"1s,omitempty"` -} - -// EnumParamsParams defines parameters for EnumParams. -type EnumParamsParams struct { - // EnumPathParam Parameter with enum values - EnumPathParam *EnumParamsParamsEnumPathParam `form:"enumPathParam,omitempty" json:"enumPathParam,omitempty"` -} - -// EnumParamsParamsEnumPathParam defines parameters for EnumParams. -type EnumParamsParamsEnumPathParam int32 - -// GetHeaderParams defines parameters for GetHeader. -type GetHeaderParams struct { - // XPrimitive primitive - XPrimitive *int32 `json:"X-Primitive,omitempty"` - - // XPrimitiveExploded primitive - XPrimitiveExploded *int32 `json:"X-Primitive-Exploded,omitempty"` - - // XArrayExploded exploded array - XArrayExploded *[]int32 `json:"X-Array-Exploded,omitempty"` - - // XArray array - XArray *[]int32 `json:"X-Array,omitempty"` - - // XObjectExploded exploded object - XObjectExploded *Object `json:"X-Object-Exploded,omitempty"` - - // XObject object - XObject *Object `json:"X-Object,omitempty"` - - // XComplexObject complex object - XComplexObject *ComplexObject `json:"X-Complex-Object,omitempty"` - - // N1StartingWithNumber name starting with number - N1StartingWithNumber *string `json:"1-Starting-With-Number,omitempty"` -} - -// GetDeepObjectParams defines parameters for GetDeepObject. -type GetDeepObjectParams struct { - // DeepObj deep object - DeepObj ComplexObject `json:"deepObj"` -} - -// GetQueryFormParams defines parameters for GetQueryForm. -type GetQueryFormParams struct { - // Ea exploded array - Ea *[]int32 `form:"ea,omitempty" json:"ea,omitempty"` - - // A array - A *[]int32 `form:"a,omitempty" json:"a,omitempty"` - - // Eo exploded object - Eo *Object `form:"eo,omitempty" json:"eo,omitempty"` - - // O object - O *Object `form:"o,omitempty" json:"o,omitempty"` - - // Ep exploded primitive - Ep *int32 `form:"ep,omitempty" json:"ep,omitempty"` - - // P primitive - P *int32 `form:"p,omitempty" json:"p,omitempty"` - - // Ps primitive string - Ps *string `form:"ps,omitempty" json:"ps,omitempty"` - - // Co complex object - Co *ComplexObject `form:"co,omitempty" json:"co,omitempty"` - - // N1s name starting with number - N1s *string `form:"1s,omitempty" json:"1s,omitempty"` -} - -// RequestEditorFn is the function signature for the RequestEditor callback function -type RequestEditorFn func(ctx context.Context, req *http.Request) error - -// Doer performs HTTP requests. -// -// The standard http.Client implements this interface. -type HttpRequestDoer interface { - Do(req *http.Request) (*http.Response, error) -} - -// Client which conforms to the OpenAPI3 specification for this service. -type Client struct { - // The endpoint of the server conforming to this interface, with scheme, - // https://api.deepmap.com for example. This can contain a path relative - // to the server, such as https://api.deepmap.com/dev-test, and all the - // paths in the swagger spec will be appended to the server. - Server string - - // Doer for performing requests, typically a *http.Client with any - // customized settings, such as certificate chains. - Client HttpRequestDoer - - // A list of callbacks for modifying requests which are generated before sending over - // the network. - RequestEditors []RequestEditorFn -} - -// ClientOption allows setting custom parameters during construction -type ClientOption func(*Client) error - -// Creates a new Client, with reasonable defaults -func NewClient(server string, opts ...ClientOption) (*Client, error) { - // create a client with sane default values - client := Client{ - Server: server, - } - // mutate client and add all optional params - for _, o := range opts { - if err := o(&client); err != nil { - return nil, err - } - } - // ensure the server URL always has a trailing slash - if !strings.HasSuffix(client.Server, "/") { - client.Server += "/" - } - // create httpClient, if not already present - if client.Client == nil { - client.Client = &http.Client{} - } - return &client, nil -} - -// WithHTTPClient allows overriding the default Doer, which is -// automatically created using http.Client. This is useful for tests. -func WithHTTPClient(doer HttpRequestDoer) ClientOption { - return func(c *Client) error { - c.Client = doer - return nil - } -} - -// WithRequestEditorFn allows setting up a callback function, which will be -// called right before sending the request. This can be used to mutate the request. -func WithRequestEditorFn(fn RequestEditorFn) ClientOption { - return func(c *Client) error { - c.RequestEditors = append(c.RequestEditors, fn) - return nil - } -} - -// The interface specification for the client above. -type ClientInterface interface { - // GetContentObject request - GetContentObject(ctx context.Context, param ComplexObject, reqEditors ...RequestEditorFn) (*http.Response, error) - - // GetCookie request - GetCookie(ctx context.Context, params *GetCookieParams, reqEditors ...RequestEditorFn) (*http.Response, error) - - // EnumParams request - EnumParams(ctx context.Context, params *EnumParamsParams, reqEditors ...RequestEditorFn) (*http.Response, error) - - // GetHeader request - GetHeader(ctx context.Context, params *GetHeaderParams, reqEditors ...RequestEditorFn) (*http.Response, error) - - // GetLabelExplodeArray request - GetLabelExplodeArray(ctx context.Context, param []int32, reqEditors ...RequestEditorFn) (*http.Response, error) - - // GetLabelExplodeObject request - GetLabelExplodeObject(ctx context.Context, param Object, reqEditors ...RequestEditorFn) (*http.Response, error) - - // GetLabelNoExplodeArray request - GetLabelNoExplodeArray(ctx context.Context, param []int32, reqEditors ...RequestEditorFn) (*http.Response, error) - - // GetLabelNoExplodeObject request - GetLabelNoExplodeObject(ctx context.Context, param Object, reqEditors ...RequestEditorFn) (*http.Response, error) - - // GetMatrixExplodeArray request - GetMatrixExplodeArray(ctx context.Context, id []int32, reqEditors ...RequestEditorFn) (*http.Response, error) - - // GetMatrixExplodeObject request - GetMatrixExplodeObject(ctx context.Context, id Object, reqEditors ...RequestEditorFn) (*http.Response, error) - - // GetMatrixNoExplodeArray request - GetMatrixNoExplodeArray(ctx context.Context, id []int32, reqEditors ...RequestEditorFn) (*http.Response, error) - - // GetMatrixNoExplodeObject request - GetMatrixNoExplodeObject(ctx context.Context, id Object, reqEditors ...RequestEditorFn) (*http.Response, error) - - // GetPassThrough request - GetPassThrough(ctx context.Context, param string, reqEditors ...RequestEditorFn) (*http.Response, error) - - // GetDeepObject request - GetDeepObject(ctx context.Context, params *GetDeepObjectParams, reqEditors ...RequestEditorFn) (*http.Response, error) - - // GetQueryForm request - GetQueryForm(ctx context.Context, params *GetQueryFormParams, reqEditors ...RequestEditorFn) (*http.Response, error) - - // GetSimpleExplodeArray request - GetSimpleExplodeArray(ctx context.Context, param []int32, reqEditors ...RequestEditorFn) (*http.Response, error) - - // GetSimpleExplodeObject request - GetSimpleExplodeObject(ctx context.Context, param Object, reqEditors ...RequestEditorFn) (*http.Response, error) - - // GetSimpleNoExplodeArray request - GetSimpleNoExplodeArray(ctx context.Context, param []int32, reqEditors ...RequestEditorFn) (*http.Response, error) - - // GetSimpleNoExplodeObject request - GetSimpleNoExplodeObject(ctx context.Context, param Object, reqEditors ...RequestEditorFn) (*http.Response, error) - - // GetSimplePrimitive request - GetSimplePrimitive(ctx context.Context, param int32, reqEditors ...RequestEditorFn) (*http.Response, error) - - // GetStartingWithNumber request - GetStartingWithNumber(ctx context.Context, n1param string, reqEditors ...RequestEditorFn) (*http.Response, error) -} - -func (c *Client) GetContentObject(ctx context.Context, param ComplexObject, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewGetContentObjectRequest(c.Server, param) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) GetCookie(ctx context.Context, params *GetCookieParams, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewGetCookieRequest(c.Server, params) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) EnumParams(ctx context.Context, params *EnumParamsParams, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewEnumParamsRequest(c.Server, params) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) GetHeader(ctx context.Context, params *GetHeaderParams, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewGetHeaderRequest(c.Server, params) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) GetLabelExplodeArray(ctx context.Context, param []int32, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewGetLabelExplodeArrayRequest(c.Server, param) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) GetLabelExplodeObject(ctx context.Context, param Object, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewGetLabelExplodeObjectRequest(c.Server, param) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) GetLabelNoExplodeArray(ctx context.Context, param []int32, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewGetLabelNoExplodeArrayRequest(c.Server, param) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) GetLabelNoExplodeObject(ctx context.Context, param Object, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewGetLabelNoExplodeObjectRequest(c.Server, param) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) GetMatrixExplodeArray(ctx context.Context, id []int32, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewGetMatrixExplodeArrayRequest(c.Server, id) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) GetMatrixExplodeObject(ctx context.Context, id Object, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewGetMatrixExplodeObjectRequest(c.Server, id) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) GetMatrixNoExplodeArray(ctx context.Context, id []int32, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewGetMatrixNoExplodeArrayRequest(c.Server, id) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) GetMatrixNoExplodeObject(ctx context.Context, id Object, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewGetMatrixNoExplodeObjectRequest(c.Server, id) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) GetPassThrough(ctx context.Context, param string, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewGetPassThroughRequest(c.Server, param) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) GetDeepObject(ctx context.Context, params *GetDeepObjectParams, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewGetDeepObjectRequest(c.Server, params) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) GetQueryForm(ctx context.Context, params *GetQueryFormParams, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewGetQueryFormRequest(c.Server, params) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) GetSimpleExplodeArray(ctx context.Context, param []int32, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewGetSimpleExplodeArrayRequest(c.Server, param) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) GetSimpleExplodeObject(ctx context.Context, param Object, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewGetSimpleExplodeObjectRequest(c.Server, param) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) GetSimpleNoExplodeArray(ctx context.Context, param []int32, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewGetSimpleNoExplodeArrayRequest(c.Server, param) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) GetSimpleNoExplodeObject(ctx context.Context, param Object, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewGetSimpleNoExplodeObjectRequest(c.Server, param) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) GetSimplePrimitive(ctx context.Context, param int32, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewGetSimplePrimitiveRequest(c.Server, param) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) GetStartingWithNumber(ctx context.Context, n1param string, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewGetStartingWithNumberRequest(c.Server, n1param) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -// NewGetContentObjectRequest generates requests for GetContentObject -func NewGetContentObjectRequest(server string, param ComplexObject) (*http.Request, error) { - var err error - - var pathParam0 string - - var pathParamBuf0 []byte - pathParamBuf0, err = json.Marshal(param) - if err != nil { - return nil, err - } - pathParam0 = string(pathParamBuf0) - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/contentObject/%s", pathParam0) - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -// NewGetCookieRequest generates requests for GetCookie -func NewGetCookieRequest(server string, params *GetCookieParams) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/cookie") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - if params != nil { - - if params.P != nil { - var cookieParam0 string - - cookieParam0, err = runtime.StyleParamWithOptions("simple", false, "p", *params.P, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationCookie, Type: "integer", Format: "int32"}) - if err != nil { - return nil, err - } - - cookie0 := &http.Cookie{ - Name: "p", - Value: cookieParam0, - } - req.AddCookie(cookie0) - } - - if params.Ep != nil { - var cookieParam1 string - - cookieParam1, err = runtime.StyleParamWithOptions("simple", true, "ep", *params.Ep, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationCookie, Type: "integer", Format: "int32"}) - if err != nil { - return nil, err - } - - cookie1 := &http.Cookie{ - Name: "ep", - Value: cookieParam1, - } - req.AddCookie(cookie1) - } - - if params.Ea != nil { - var cookieParam2 string - - cookieParam2, err = runtime.StyleParamWithOptions("simple", true, "ea", *params.Ea, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationCookie, Type: "array", Format: ""}) - if err != nil { - return nil, err - } - - cookie2 := &http.Cookie{ - Name: "ea", - Value: cookieParam2, - } - req.AddCookie(cookie2) - } - - if params.A != nil { - var cookieParam3 string - - cookieParam3, err = runtime.StyleParamWithOptions("simple", false, "a", *params.A, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationCookie, Type: "array", Format: ""}) - if err != nil { - return nil, err - } - - cookie3 := &http.Cookie{ - Name: "a", - Value: cookieParam3, - } - req.AddCookie(cookie3) - } - - if params.Eo != nil { - var cookieParam4 string - - cookieParam4, err = runtime.StyleParamWithOptions("simple", true, "eo", *params.Eo, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationCookie, Type: "", Format: ""}) - if err != nil { - return nil, err - } - - cookie4 := &http.Cookie{ - Name: "eo", - Value: cookieParam4, - } - req.AddCookie(cookie4) - } - - if params.O != nil { - var cookieParam5 string - - cookieParam5, err = runtime.StyleParamWithOptions("simple", false, "o", *params.O, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationCookie, Type: "", Format: ""}) - if err != nil { - return nil, err - } - - cookie5 := &http.Cookie{ - Name: "o", - Value: cookieParam5, - } - req.AddCookie(cookie5) - } - - if params.Co != nil { - var cookieParam6 string - - var cookieParamBuf6 []byte - cookieParamBuf6, err = json.Marshal(*params.Co) - if err != nil { - return nil, err - } - cookieParam6 = url.QueryEscape(string(cookieParamBuf6)) - - cookie6 := &http.Cookie{ - Name: "co", - Value: cookieParam6, - } - req.AddCookie(cookie6) - } - - if params.N1s != nil { - var cookieParam7 string - - cookieParam7, err = runtime.StyleParamWithOptions("simple", true, "1s", *params.N1s, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationCookie, Type: "string", Format: ""}) - if err != nil { - return nil, err - } - - cookie7 := &http.Cookie{ - Name: "1s", - Value: cookieParam7, - } - req.AddCookie(cookie7) - } - } - return req, nil -} - -// NewEnumParamsRequest generates requests for EnumParams -func NewEnumParamsRequest(server string, params *EnumParamsParams) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/enums") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - if params != nil { - queryValues := queryURL.Query() - - if params.EnumPathParam != nil { - - if queryFrag, err := runtime.StyleParamWithOptions("form", true, "enumPathParam", *params.EnumPathParam, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: "int32"}); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { - return nil, err - } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } - } - } - - } - - queryURL.RawQuery = queryValues.Encode() - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -// NewGetHeaderRequest generates requests for GetHeader -func NewGetHeaderRequest(server string, params *GetHeaderParams) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/header") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - if params != nil { - - if params.XPrimitive != nil { - var headerParam0 string - - headerParam0, err = runtime.StyleParamWithOptions("simple", false, "X-Primitive", *params.XPrimitive, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "integer", Format: "int32"}) - if err != nil { - return nil, err - } - - req.Header.Set("X-Primitive", headerParam0) - } - - if params.XPrimitiveExploded != nil { - var headerParam1 string - - headerParam1, err = runtime.StyleParamWithOptions("simple", true, "X-Primitive-Exploded", *params.XPrimitiveExploded, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "integer", Format: "int32"}) - if err != nil { - return nil, err - } - - req.Header.Set("X-Primitive-Exploded", headerParam1) - } - - if params.XArrayExploded != nil { - var headerParam2 string - - headerParam2, err = runtime.StyleParamWithOptions("simple", true, "X-Array-Exploded", *params.XArrayExploded, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "array", Format: ""}) - if err != nil { - return nil, err - } - - req.Header.Set("X-Array-Exploded", headerParam2) - } - - if params.XArray != nil { - var headerParam3 string - - headerParam3, err = runtime.StyleParamWithOptions("simple", false, "X-Array", *params.XArray, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "array", Format: ""}) - if err != nil { - return nil, err - } - - req.Header.Set("X-Array", headerParam3) - } - - if params.XObjectExploded != nil { - var headerParam4 string - - headerParam4, err = runtime.StyleParamWithOptions("simple", true, "X-Object-Exploded", *params.XObjectExploded, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "", Format: ""}) - if err != nil { - return nil, err - } - - req.Header.Set("X-Object-Exploded", headerParam4) - } - - if params.XObject != nil { - var headerParam5 string - - headerParam5, err = runtime.StyleParamWithOptions("simple", false, "X-Object", *params.XObject, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "", Format: ""}) - if err != nil { - return nil, err - } - - req.Header.Set("X-Object", headerParam5) - } - - if params.XComplexObject != nil { - var headerParam6 string - - var headerParamBuf6 []byte - headerParamBuf6, err = json.Marshal(*params.XComplexObject) - if err != nil { - return nil, err - } - headerParam6 = string(headerParamBuf6) - - req.Header.Set("X-Complex-Object", headerParam6) - } - - if params.N1StartingWithNumber != nil { - var headerParam7 string - - headerParam7, err = runtime.StyleParamWithOptions("simple", false, "1-Starting-With-Number", *params.N1StartingWithNumber, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) - if err != nil { - return nil, err - } - - req.Header.Set("1-Starting-With-Number", headerParam7) - } - - } - - return req, nil -} - -// NewGetLabelExplodeArrayRequest generates requests for GetLabelExplodeArray -func NewGetLabelExplodeArrayRequest(server string, param []int32) (*http.Request, error) { - var err error - - var pathParam0 string - - pathParam0, err = runtime.StyleParamWithOptions("label", true, "param", param, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "array", Format: ""}) - if err != nil { - return nil, err - } - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/labelExplodeArray/%s", pathParam0) - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -// NewGetLabelExplodeObjectRequest generates requests for GetLabelExplodeObject -func NewGetLabelExplodeObjectRequest(server string, param Object) (*http.Request, error) { - var err error - - var pathParam0 string - - pathParam0, err = runtime.StyleParamWithOptions("label", true, "param", param, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "", Format: ""}) - if err != nil { - return nil, err - } - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/labelExplodeObject/%s", pathParam0) - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -// NewGetLabelNoExplodeArrayRequest generates requests for GetLabelNoExplodeArray -func NewGetLabelNoExplodeArrayRequest(server string, param []int32) (*http.Request, error) { - var err error - - var pathParam0 string - - pathParam0, err = runtime.StyleParamWithOptions("label", false, "param", param, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "array", Format: ""}) - if err != nil { - return nil, err - } - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/labelNoExplodeArray/%s", pathParam0) - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -// NewGetLabelNoExplodeObjectRequest generates requests for GetLabelNoExplodeObject -func NewGetLabelNoExplodeObjectRequest(server string, param Object) (*http.Request, error) { - var err error - - var pathParam0 string - - pathParam0, err = runtime.StyleParamWithOptions("label", false, "param", param, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "", Format: ""}) - if err != nil { - return nil, err - } - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/labelNoExplodeObject/%s", pathParam0) - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -// NewGetMatrixExplodeArrayRequest generates requests for GetMatrixExplodeArray -func NewGetMatrixExplodeArrayRequest(server string, id []int32) (*http.Request, error) { - var err error - - var pathParam0 string - - pathParam0, err = runtime.StyleParamWithOptions("matrix", true, "id", id, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "array", Format: ""}) - if err != nil { - return nil, err - } - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/matrixExplodeArray/%s", pathParam0) - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -// NewGetMatrixExplodeObjectRequest generates requests for GetMatrixExplodeObject -func NewGetMatrixExplodeObjectRequest(server string, id Object) (*http.Request, error) { - var err error - - var pathParam0 string - - pathParam0, err = runtime.StyleParamWithOptions("matrix", true, "id", id, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "", Format: ""}) - if err != nil { - return nil, err - } - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/matrixExplodeObject/%s", pathParam0) - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -// NewGetMatrixNoExplodeArrayRequest generates requests for GetMatrixNoExplodeArray -func NewGetMatrixNoExplodeArrayRequest(server string, id []int32) (*http.Request, error) { - var err error - - var pathParam0 string - - pathParam0, err = runtime.StyleParamWithOptions("matrix", false, "id", id, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "array", Format: ""}) - if err != nil { - return nil, err - } - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/matrixNoExplodeArray/%s", pathParam0) - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -// NewGetMatrixNoExplodeObjectRequest generates requests for GetMatrixNoExplodeObject -func NewGetMatrixNoExplodeObjectRequest(server string, id Object) (*http.Request, error) { - var err error - - var pathParam0 string - - pathParam0, err = runtime.StyleParamWithOptions("matrix", false, "id", id, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "", Format: ""}) - if err != nil { - return nil, err - } - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/matrixNoExplodeObject/%s", pathParam0) - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -// NewGetPassThroughRequest generates requests for GetPassThrough -func NewGetPassThroughRequest(server string, param string) (*http.Request, error) { - var err error - - var pathParam0 string - - pathParam0 = param - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/passThrough/%s", pathParam0) - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -// NewGetDeepObjectRequest generates requests for GetDeepObject -func NewGetDeepObjectRequest(server string, params *GetDeepObjectParams) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/queryDeepObject") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - if params != nil { - queryValues := queryURL.Query() - - if queryFrag, err := runtime.StyleParamWithOptions("deepObject", true, "deepObj", params.DeepObj, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "", Format: ""}); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { - return nil, err - } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } - } - } - - queryURL.RawQuery = queryValues.Encode() - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -// NewGetQueryFormRequest generates requests for GetQueryForm -func NewGetQueryFormRequest(server string, params *GetQueryFormParams) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/queryForm") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - if params != nil { - queryValues := queryURL.Query() - - if params.Ea != nil { - - if queryFrag, err := runtime.StyleParamWithOptions("form", true, "ea", *params.Ea, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "array", Format: ""}); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { - return nil, err - } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } - } - } - - } - - if params.A != nil { - - if queryFrag, err := runtime.StyleParamWithOptions("form", false, "a", *params.A, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "array", Format: ""}); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { - return nil, err - } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } - } - } - - } - - if params.Eo != nil { - - if queryFrag, err := runtime.StyleParamWithOptions("form", true, "eo", *params.Eo, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "", Format: ""}); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { - return nil, err - } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } - } - } - - } - - if params.O != nil { - - if queryFrag, err := runtime.StyleParamWithOptions("form", false, "o", *params.O, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "", Format: ""}); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { - return nil, err - } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } - } - } - - } - - if params.Ep != nil { - - if queryFrag, err := runtime.StyleParamWithOptions("form", true, "ep", *params.Ep, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: "int32"}); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { - return nil, err - } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } - } - } - - } - - if params.P != nil { - - if queryFrag, err := runtime.StyleParamWithOptions("form", false, "p", *params.P, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: "int32"}); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { - return nil, err - } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } - } - } - - } - - if params.Ps != nil { - - if queryFrag, err := runtime.StyleParamWithOptions("form", true, "ps", *params.Ps, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { - return nil, err - } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } - } - } - - } - - if params.Co != nil { - - if queryParamBuf, err := json.Marshal(*params.Co); err != nil { - return nil, err - } else { - queryValues.Add("co", string(queryParamBuf)) - } - - } - - if params.N1s != nil { - - if queryFrag, err := runtime.StyleParamWithOptions("form", true, "1s", *params.N1s, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { - return nil, err - } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } - } - } - - } - - queryURL.RawQuery = queryValues.Encode() - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -// NewGetSimpleExplodeArrayRequest generates requests for GetSimpleExplodeArray -func NewGetSimpleExplodeArrayRequest(server string, param []int32) (*http.Request, error) { - var err error - - var pathParam0 string - - pathParam0, err = runtime.StyleParamWithOptions("simple", true, "param", param, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "array", Format: ""}) - if err != nil { - return nil, err - } - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/simpleExplodeArray/%s", pathParam0) - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -// NewGetSimpleExplodeObjectRequest generates requests for GetSimpleExplodeObject -func NewGetSimpleExplodeObjectRequest(server string, param Object) (*http.Request, error) { - var err error - - var pathParam0 string - - pathParam0, err = runtime.StyleParamWithOptions("simple", true, "param", param, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "", Format: ""}) - if err != nil { - return nil, err - } - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/simpleExplodeObject/%s", pathParam0) - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -// NewGetSimpleNoExplodeArrayRequest generates requests for GetSimpleNoExplodeArray -func NewGetSimpleNoExplodeArrayRequest(server string, param []int32) (*http.Request, error) { - var err error - - var pathParam0 string - - pathParam0, err = runtime.StyleParamWithOptions("simple", false, "param", param, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "array", Format: ""}) - if err != nil { - return nil, err - } - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/simpleNoExplodeArray/%s", pathParam0) - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -// NewGetSimpleNoExplodeObjectRequest generates requests for GetSimpleNoExplodeObject -func NewGetSimpleNoExplodeObjectRequest(server string, param Object) (*http.Request, error) { - var err error - - var pathParam0 string - - pathParam0, err = runtime.StyleParamWithOptions("simple", false, "param", param, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "", Format: ""}) - if err != nil { - return nil, err - } - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/simpleNoExplodeObject/%s", pathParam0) - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -// NewGetSimplePrimitiveRequest generates requests for GetSimplePrimitive -func NewGetSimplePrimitiveRequest(server string, param int32) (*http.Request, error) { - var err error - - var pathParam0 string - - pathParam0, err = runtime.StyleParamWithOptions("simple", false, "param", param, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "integer", Format: "int32"}) - if err != nil { - return nil, err - } - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/simplePrimitive/%s", pathParam0) - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -// NewGetStartingWithNumberRequest generates requests for GetStartingWithNumber -func NewGetStartingWithNumberRequest(server string, n1param string) (*http.Request, error) { - var err error - - var pathParam0 string - - pathParam0 = n1param - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/startingWithNumber/%s", pathParam0) - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -func (c *Client) applyEditors(ctx context.Context, req *http.Request, additionalEditors []RequestEditorFn) error { - for _, r := range c.RequestEditors { - if err := r(ctx, req); err != nil { - return err - } - } - for _, r := range additionalEditors { - if err := r(ctx, req); err != nil { - return err - } - } - return nil -} - -// ClientWithResponses builds on ClientInterface to offer response payloads -type ClientWithResponses struct { - ClientInterface -} - -// NewClientWithResponses creates a new ClientWithResponses, which wraps -// Client with return type handling -func NewClientWithResponses(server string, opts ...ClientOption) (*ClientWithResponses, error) { - client, err := NewClient(server, opts...) - if err != nil { - return nil, err - } - return &ClientWithResponses{client}, nil -} - -// WithBaseURL overrides the baseURL. -func WithBaseURL(baseURL string) ClientOption { - return func(c *Client) error { - newBaseURL, err := url.Parse(baseURL) - if err != nil { - return err - } - c.Server = newBaseURL.String() - return nil - } -} - -// ClientWithResponsesInterface is the interface specification for the client with responses above. -type ClientWithResponsesInterface interface { - // GetContentObjectWithResponse request - GetContentObjectWithResponse(ctx context.Context, param ComplexObject, reqEditors ...RequestEditorFn) (*GetContentObjectResponse, error) - - // GetCookieWithResponse request - GetCookieWithResponse(ctx context.Context, params *GetCookieParams, reqEditors ...RequestEditorFn) (*GetCookieResponse, error) - - // EnumParamsWithResponse request - EnumParamsWithResponse(ctx context.Context, params *EnumParamsParams, reqEditors ...RequestEditorFn) (*EnumParamsResponse, error) - - // GetHeaderWithResponse request - GetHeaderWithResponse(ctx context.Context, params *GetHeaderParams, reqEditors ...RequestEditorFn) (*GetHeaderResponse, error) - - // GetLabelExplodeArrayWithResponse request - GetLabelExplodeArrayWithResponse(ctx context.Context, param []int32, reqEditors ...RequestEditorFn) (*GetLabelExplodeArrayResponse, error) - - // GetLabelExplodeObjectWithResponse request - GetLabelExplodeObjectWithResponse(ctx context.Context, param Object, reqEditors ...RequestEditorFn) (*GetLabelExplodeObjectResponse, error) - - // GetLabelNoExplodeArrayWithResponse request - GetLabelNoExplodeArrayWithResponse(ctx context.Context, param []int32, reqEditors ...RequestEditorFn) (*GetLabelNoExplodeArrayResponse, error) - - // GetLabelNoExplodeObjectWithResponse request - GetLabelNoExplodeObjectWithResponse(ctx context.Context, param Object, reqEditors ...RequestEditorFn) (*GetLabelNoExplodeObjectResponse, error) - - // GetMatrixExplodeArrayWithResponse request - GetMatrixExplodeArrayWithResponse(ctx context.Context, id []int32, reqEditors ...RequestEditorFn) (*GetMatrixExplodeArrayResponse, error) - - // GetMatrixExplodeObjectWithResponse request - GetMatrixExplodeObjectWithResponse(ctx context.Context, id Object, reqEditors ...RequestEditorFn) (*GetMatrixExplodeObjectResponse, error) - - // GetMatrixNoExplodeArrayWithResponse request - GetMatrixNoExplodeArrayWithResponse(ctx context.Context, id []int32, reqEditors ...RequestEditorFn) (*GetMatrixNoExplodeArrayResponse, error) - - // GetMatrixNoExplodeObjectWithResponse request - GetMatrixNoExplodeObjectWithResponse(ctx context.Context, id Object, reqEditors ...RequestEditorFn) (*GetMatrixNoExplodeObjectResponse, error) - - // GetPassThroughWithResponse request - GetPassThroughWithResponse(ctx context.Context, param string, reqEditors ...RequestEditorFn) (*GetPassThroughResponse, error) - - // GetDeepObjectWithResponse request - GetDeepObjectWithResponse(ctx context.Context, params *GetDeepObjectParams, reqEditors ...RequestEditorFn) (*GetDeepObjectResponse, error) - - // GetQueryFormWithResponse request - GetQueryFormWithResponse(ctx context.Context, params *GetQueryFormParams, reqEditors ...RequestEditorFn) (*GetQueryFormResponse, error) - - // GetSimpleExplodeArrayWithResponse request - GetSimpleExplodeArrayWithResponse(ctx context.Context, param []int32, reqEditors ...RequestEditorFn) (*GetSimpleExplodeArrayResponse, error) - - // GetSimpleExplodeObjectWithResponse request - GetSimpleExplodeObjectWithResponse(ctx context.Context, param Object, reqEditors ...RequestEditorFn) (*GetSimpleExplodeObjectResponse, error) - - // GetSimpleNoExplodeArrayWithResponse request - GetSimpleNoExplodeArrayWithResponse(ctx context.Context, param []int32, reqEditors ...RequestEditorFn) (*GetSimpleNoExplodeArrayResponse, error) - - // GetSimpleNoExplodeObjectWithResponse request - GetSimpleNoExplodeObjectWithResponse(ctx context.Context, param Object, reqEditors ...RequestEditorFn) (*GetSimpleNoExplodeObjectResponse, error) - - // GetSimplePrimitiveWithResponse request - GetSimplePrimitiveWithResponse(ctx context.Context, param int32, reqEditors ...RequestEditorFn) (*GetSimplePrimitiveResponse, error) - - // GetStartingWithNumberWithResponse request - GetStartingWithNumberWithResponse(ctx context.Context, n1param string, reqEditors ...RequestEditorFn) (*GetStartingWithNumberResponse, error) -} - -type GetContentObjectResponse struct { - Body []byte - HTTPResponse *http.Response -} - -// Status returns HTTPResponse.Status -func (r GetContentObjectResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r GetContentObjectResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type GetCookieResponse struct { - Body []byte - HTTPResponse *http.Response -} - -// Status returns HTTPResponse.Status -func (r GetCookieResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r GetCookieResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type EnumParamsResponse struct { - Body []byte - HTTPResponse *http.Response -} - -// Status returns HTTPResponse.Status -func (r EnumParamsResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r EnumParamsResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type GetHeaderResponse struct { - Body []byte - HTTPResponse *http.Response -} - -// Status returns HTTPResponse.Status -func (r GetHeaderResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r GetHeaderResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type GetLabelExplodeArrayResponse struct { - Body []byte - HTTPResponse *http.Response -} - -// Status returns HTTPResponse.Status -func (r GetLabelExplodeArrayResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r GetLabelExplodeArrayResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type GetLabelExplodeObjectResponse struct { - Body []byte - HTTPResponse *http.Response -} - -// Status returns HTTPResponse.Status -func (r GetLabelExplodeObjectResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r GetLabelExplodeObjectResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type GetLabelNoExplodeArrayResponse struct { - Body []byte - HTTPResponse *http.Response -} - -// Status returns HTTPResponse.Status -func (r GetLabelNoExplodeArrayResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r GetLabelNoExplodeArrayResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type GetLabelNoExplodeObjectResponse struct { - Body []byte - HTTPResponse *http.Response -} - -// Status returns HTTPResponse.Status -func (r GetLabelNoExplodeObjectResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r GetLabelNoExplodeObjectResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type GetMatrixExplodeArrayResponse struct { - Body []byte - HTTPResponse *http.Response -} - -// Status returns HTTPResponse.Status -func (r GetMatrixExplodeArrayResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r GetMatrixExplodeArrayResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type GetMatrixExplodeObjectResponse struct { - Body []byte - HTTPResponse *http.Response -} - -// Status returns HTTPResponse.Status -func (r GetMatrixExplodeObjectResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r GetMatrixExplodeObjectResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type GetMatrixNoExplodeArrayResponse struct { - Body []byte - HTTPResponse *http.Response -} - -// Status returns HTTPResponse.Status -func (r GetMatrixNoExplodeArrayResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r GetMatrixNoExplodeArrayResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type GetMatrixNoExplodeObjectResponse struct { - Body []byte - HTTPResponse *http.Response -} - -// Status returns HTTPResponse.Status -func (r GetMatrixNoExplodeObjectResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r GetMatrixNoExplodeObjectResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type GetPassThroughResponse struct { - Body []byte - HTTPResponse *http.Response -} - -// Status returns HTTPResponse.Status -func (r GetPassThroughResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r GetPassThroughResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type GetDeepObjectResponse struct { - Body []byte - HTTPResponse *http.Response -} - -// Status returns HTTPResponse.Status -func (r GetDeepObjectResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r GetDeepObjectResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type GetQueryFormResponse struct { - Body []byte - HTTPResponse *http.Response -} - -// Status returns HTTPResponse.Status -func (r GetQueryFormResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r GetQueryFormResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type GetSimpleExplodeArrayResponse struct { - Body []byte - HTTPResponse *http.Response -} - -// Status returns HTTPResponse.Status -func (r GetSimpleExplodeArrayResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r GetSimpleExplodeArrayResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type GetSimpleExplodeObjectResponse struct { - Body []byte - HTTPResponse *http.Response -} - -// Status returns HTTPResponse.Status -func (r GetSimpleExplodeObjectResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r GetSimpleExplodeObjectResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type GetSimpleNoExplodeArrayResponse struct { - Body []byte - HTTPResponse *http.Response -} - -// Status returns HTTPResponse.Status -func (r GetSimpleNoExplodeArrayResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r GetSimpleNoExplodeArrayResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type GetSimpleNoExplodeObjectResponse struct { - Body []byte - HTTPResponse *http.Response -} - -// Status returns HTTPResponse.Status -func (r GetSimpleNoExplodeObjectResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r GetSimpleNoExplodeObjectResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type GetSimplePrimitiveResponse struct { - Body []byte - HTTPResponse *http.Response -} - -// Status returns HTTPResponse.Status -func (r GetSimplePrimitiveResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r GetSimplePrimitiveResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type GetStartingWithNumberResponse struct { - Body []byte - HTTPResponse *http.Response -} - -// Status returns HTTPResponse.Status -func (r GetStartingWithNumberResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r GetStartingWithNumberResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -// GetContentObjectWithResponse request returning *GetContentObjectResponse -func (c *ClientWithResponses) GetContentObjectWithResponse(ctx context.Context, param ComplexObject, reqEditors ...RequestEditorFn) (*GetContentObjectResponse, error) { - rsp, err := c.GetContentObject(ctx, param, reqEditors...) - if err != nil { - return nil, err - } - return ParseGetContentObjectResponse(rsp) -} - -// GetCookieWithResponse request returning *GetCookieResponse -func (c *ClientWithResponses) GetCookieWithResponse(ctx context.Context, params *GetCookieParams, reqEditors ...RequestEditorFn) (*GetCookieResponse, error) { - rsp, err := c.GetCookie(ctx, params, reqEditors...) - if err != nil { - return nil, err - } - return ParseGetCookieResponse(rsp) -} - -// EnumParamsWithResponse request returning *EnumParamsResponse -func (c *ClientWithResponses) EnumParamsWithResponse(ctx context.Context, params *EnumParamsParams, reqEditors ...RequestEditorFn) (*EnumParamsResponse, error) { - rsp, err := c.EnumParams(ctx, params, reqEditors...) - if err != nil { - return nil, err - } - return ParseEnumParamsResponse(rsp) -} - -// GetHeaderWithResponse request returning *GetHeaderResponse -func (c *ClientWithResponses) GetHeaderWithResponse(ctx context.Context, params *GetHeaderParams, reqEditors ...RequestEditorFn) (*GetHeaderResponse, error) { - rsp, err := c.GetHeader(ctx, params, reqEditors...) - if err != nil { - return nil, err - } - return ParseGetHeaderResponse(rsp) -} - -// GetLabelExplodeArrayWithResponse request returning *GetLabelExplodeArrayResponse -func (c *ClientWithResponses) GetLabelExplodeArrayWithResponse(ctx context.Context, param []int32, reqEditors ...RequestEditorFn) (*GetLabelExplodeArrayResponse, error) { - rsp, err := c.GetLabelExplodeArray(ctx, param, reqEditors...) - if err != nil { - return nil, err - } - return ParseGetLabelExplodeArrayResponse(rsp) -} - -// GetLabelExplodeObjectWithResponse request returning *GetLabelExplodeObjectResponse -func (c *ClientWithResponses) GetLabelExplodeObjectWithResponse(ctx context.Context, param Object, reqEditors ...RequestEditorFn) (*GetLabelExplodeObjectResponse, error) { - rsp, err := c.GetLabelExplodeObject(ctx, param, reqEditors...) - if err != nil { - return nil, err - } - return ParseGetLabelExplodeObjectResponse(rsp) -} - -// GetLabelNoExplodeArrayWithResponse request returning *GetLabelNoExplodeArrayResponse -func (c *ClientWithResponses) GetLabelNoExplodeArrayWithResponse(ctx context.Context, param []int32, reqEditors ...RequestEditorFn) (*GetLabelNoExplodeArrayResponse, error) { - rsp, err := c.GetLabelNoExplodeArray(ctx, param, reqEditors...) - if err != nil { - return nil, err - } - return ParseGetLabelNoExplodeArrayResponse(rsp) -} - -// GetLabelNoExplodeObjectWithResponse request returning *GetLabelNoExplodeObjectResponse -func (c *ClientWithResponses) GetLabelNoExplodeObjectWithResponse(ctx context.Context, param Object, reqEditors ...RequestEditorFn) (*GetLabelNoExplodeObjectResponse, error) { - rsp, err := c.GetLabelNoExplodeObject(ctx, param, reqEditors...) - if err != nil { - return nil, err - } - return ParseGetLabelNoExplodeObjectResponse(rsp) -} - -// GetMatrixExplodeArrayWithResponse request returning *GetMatrixExplodeArrayResponse -func (c *ClientWithResponses) GetMatrixExplodeArrayWithResponse(ctx context.Context, id []int32, reqEditors ...RequestEditorFn) (*GetMatrixExplodeArrayResponse, error) { - rsp, err := c.GetMatrixExplodeArray(ctx, id, reqEditors...) - if err != nil { - return nil, err - } - return ParseGetMatrixExplodeArrayResponse(rsp) -} - -// GetMatrixExplodeObjectWithResponse request returning *GetMatrixExplodeObjectResponse -func (c *ClientWithResponses) GetMatrixExplodeObjectWithResponse(ctx context.Context, id Object, reqEditors ...RequestEditorFn) (*GetMatrixExplodeObjectResponse, error) { - rsp, err := c.GetMatrixExplodeObject(ctx, id, reqEditors...) - if err != nil { - return nil, err - } - return ParseGetMatrixExplodeObjectResponse(rsp) -} - -// GetMatrixNoExplodeArrayWithResponse request returning *GetMatrixNoExplodeArrayResponse -func (c *ClientWithResponses) GetMatrixNoExplodeArrayWithResponse(ctx context.Context, id []int32, reqEditors ...RequestEditorFn) (*GetMatrixNoExplodeArrayResponse, error) { - rsp, err := c.GetMatrixNoExplodeArray(ctx, id, reqEditors...) - if err != nil { - return nil, err - } - return ParseGetMatrixNoExplodeArrayResponse(rsp) -} - -// GetMatrixNoExplodeObjectWithResponse request returning *GetMatrixNoExplodeObjectResponse -func (c *ClientWithResponses) GetMatrixNoExplodeObjectWithResponse(ctx context.Context, id Object, reqEditors ...RequestEditorFn) (*GetMatrixNoExplodeObjectResponse, error) { - rsp, err := c.GetMatrixNoExplodeObject(ctx, id, reqEditors...) - if err != nil { - return nil, err - } - return ParseGetMatrixNoExplodeObjectResponse(rsp) -} - -// GetPassThroughWithResponse request returning *GetPassThroughResponse -func (c *ClientWithResponses) GetPassThroughWithResponse(ctx context.Context, param string, reqEditors ...RequestEditorFn) (*GetPassThroughResponse, error) { - rsp, err := c.GetPassThrough(ctx, param, reqEditors...) - if err != nil { - return nil, err - } - return ParseGetPassThroughResponse(rsp) -} - -// GetDeepObjectWithResponse request returning *GetDeepObjectResponse -func (c *ClientWithResponses) GetDeepObjectWithResponse(ctx context.Context, params *GetDeepObjectParams, reqEditors ...RequestEditorFn) (*GetDeepObjectResponse, error) { - rsp, err := c.GetDeepObject(ctx, params, reqEditors...) - if err != nil { - return nil, err - } - return ParseGetDeepObjectResponse(rsp) -} - -// GetQueryFormWithResponse request returning *GetQueryFormResponse -func (c *ClientWithResponses) GetQueryFormWithResponse(ctx context.Context, params *GetQueryFormParams, reqEditors ...RequestEditorFn) (*GetQueryFormResponse, error) { - rsp, err := c.GetQueryForm(ctx, params, reqEditors...) - if err != nil { - return nil, err - } - return ParseGetQueryFormResponse(rsp) -} - -// GetSimpleExplodeArrayWithResponse request returning *GetSimpleExplodeArrayResponse -func (c *ClientWithResponses) GetSimpleExplodeArrayWithResponse(ctx context.Context, param []int32, reqEditors ...RequestEditorFn) (*GetSimpleExplodeArrayResponse, error) { - rsp, err := c.GetSimpleExplodeArray(ctx, param, reqEditors...) - if err != nil { - return nil, err - } - return ParseGetSimpleExplodeArrayResponse(rsp) -} - -// GetSimpleExplodeObjectWithResponse request returning *GetSimpleExplodeObjectResponse -func (c *ClientWithResponses) GetSimpleExplodeObjectWithResponse(ctx context.Context, param Object, reqEditors ...RequestEditorFn) (*GetSimpleExplodeObjectResponse, error) { - rsp, err := c.GetSimpleExplodeObject(ctx, param, reqEditors...) - if err != nil { - return nil, err - } - return ParseGetSimpleExplodeObjectResponse(rsp) -} - -// GetSimpleNoExplodeArrayWithResponse request returning *GetSimpleNoExplodeArrayResponse -func (c *ClientWithResponses) GetSimpleNoExplodeArrayWithResponse(ctx context.Context, param []int32, reqEditors ...RequestEditorFn) (*GetSimpleNoExplodeArrayResponse, error) { - rsp, err := c.GetSimpleNoExplodeArray(ctx, param, reqEditors...) - if err != nil { - return nil, err - } - return ParseGetSimpleNoExplodeArrayResponse(rsp) -} - -// GetSimpleNoExplodeObjectWithResponse request returning *GetSimpleNoExplodeObjectResponse -func (c *ClientWithResponses) GetSimpleNoExplodeObjectWithResponse(ctx context.Context, param Object, reqEditors ...RequestEditorFn) (*GetSimpleNoExplodeObjectResponse, error) { - rsp, err := c.GetSimpleNoExplodeObject(ctx, param, reqEditors...) - if err != nil { - return nil, err - } - return ParseGetSimpleNoExplodeObjectResponse(rsp) -} - -// GetSimplePrimitiveWithResponse request returning *GetSimplePrimitiveResponse -func (c *ClientWithResponses) GetSimplePrimitiveWithResponse(ctx context.Context, param int32, reqEditors ...RequestEditorFn) (*GetSimplePrimitiveResponse, error) { - rsp, err := c.GetSimplePrimitive(ctx, param, reqEditors...) - if err != nil { - return nil, err - } - return ParseGetSimplePrimitiveResponse(rsp) -} - -// GetStartingWithNumberWithResponse request returning *GetStartingWithNumberResponse -func (c *ClientWithResponses) GetStartingWithNumberWithResponse(ctx context.Context, n1param string, reqEditors ...RequestEditorFn) (*GetStartingWithNumberResponse, error) { - rsp, err := c.GetStartingWithNumber(ctx, n1param, reqEditors...) - if err != nil { - return nil, err - } - return ParseGetStartingWithNumberResponse(rsp) -} - -// ParseGetContentObjectResponse parses an HTTP response from a GetContentObjectWithResponse call -func ParseGetContentObjectResponse(rsp *http.Response) (*GetContentObjectResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &GetContentObjectResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - return response, nil -} - -// ParseGetCookieResponse parses an HTTP response from a GetCookieWithResponse call -func ParseGetCookieResponse(rsp *http.Response) (*GetCookieResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &GetCookieResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - return response, nil -} - -// ParseEnumParamsResponse parses an HTTP response from a EnumParamsWithResponse call -func ParseEnumParamsResponse(rsp *http.Response) (*EnumParamsResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &EnumParamsResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - return response, nil -} - -// ParseGetHeaderResponse parses an HTTP response from a GetHeaderWithResponse call -func ParseGetHeaderResponse(rsp *http.Response) (*GetHeaderResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &GetHeaderResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - return response, nil -} - -// ParseGetLabelExplodeArrayResponse parses an HTTP response from a GetLabelExplodeArrayWithResponse call -func ParseGetLabelExplodeArrayResponse(rsp *http.Response) (*GetLabelExplodeArrayResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &GetLabelExplodeArrayResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - return response, nil -} - -// ParseGetLabelExplodeObjectResponse parses an HTTP response from a GetLabelExplodeObjectWithResponse call -func ParseGetLabelExplodeObjectResponse(rsp *http.Response) (*GetLabelExplodeObjectResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &GetLabelExplodeObjectResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - return response, nil -} - -// ParseGetLabelNoExplodeArrayResponse parses an HTTP response from a GetLabelNoExplodeArrayWithResponse call -func ParseGetLabelNoExplodeArrayResponse(rsp *http.Response) (*GetLabelNoExplodeArrayResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &GetLabelNoExplodeArrayResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - return response, nil -} - -// ParseGetLabelNoExplodeObjectResponse parses an HTTP response from a GetLabelNoExplodeObjectWithResponse call -func ParseGetLabelNoExplodeObjectResponse(rsp *http.Response) (*GetLabelNoExplodeObjectResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &GetLabelNoExplodeObjectResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - return response, nil -} - -// ParseGetMatrixExplodeArrayResponse parses an HTTP response from a GetMatrixExplodeArrayWithResponse call -func ParseGetMatrixExplodeArrayResponse(rsp *http.Response) (*GetMatrixExplodeArrayResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &GetMatrixExplodeArrayResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - return response, nil -} - -// ParseGetMatrixExplodeObjectResponse parses an HTTP response from a GetMatrixExplodeObjectWithResponse call -func ParseGetMatrixExplodeObjectResponse(rsp *http.Response) (*GetMatrixExplodeObjectResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &GetMatrixExplodeObjectResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - return response, nil -} - -// ParseGetMatrixNoExplodeArrayResponse parses an HTTP response from a GetMatrixNoExplodeArrayWithResponse call -func ParseGetMatrixNoExplodeArrayResponse(rsp *http.Response) (*GetMatrixNoExplodeArrayResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &GetMatrixNoExplodeArrayResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - return response, nil -} - -// ParseGetMatrixNoExplodeObjectResponse parses an HTTP response from a GetMatrixNoExplodeObjectWithResponse call -func ParseGetMatrixNoExplodeObjectResponse(rsp *http.Response) (*GetMatrixNoExplodeObjectResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &GetMatrixNoExplodeObjectResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - return response, nil -} - -// ParseGetPassThroughResponse parses an HTTP response from a GetPassThroughWithResponse call -func ParseGetPassThroughResponse(rsp *http.Response) (*GetPassThroughResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &GetPassThroughResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - return response, nil -} - -// ParseGetDeepObjectResponse parses an HTTP response from a GetDeepObjectWithResponse call -func ParseGetDeepObjectResponse(rsp *http.Response) (*GetDeepObjectResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &GetDeepObjectResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - return response, nil -} - -// ParseGetQueryFormResponse parses an HTTP response from a GetQueryFormWithResponse call -func ParseGetQueryFormResponse(rsp *http.Response) (*GetQueryFormResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &GetQueryFormResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - return response, nil -} - -// ParseGetSimpleExplodeArrayResponse parses an HTTP response from a GetSimpleExplodeArrayWithResponse call -func ParseGetSimpleExplodeArrayResponse(rsp *http.Response) (*GetSimpleExplodeArrayResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &GetSimpleExplodeArrayResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - return response, nil -} - -// ParseGetSimpleExplodeObjectResponse parses an HTTP response from a GetSimpleExplodeObjectWithResponse call -func ParseGetSimpleExplodeObjectResponse(rsp *http.Response) (*GetSimpleExplodeObjectResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &GetSimpleExplodeObjectResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - return response, nil -} - -// ParseGetSimpleNoExplodeArrayResponse parses an HTTP response from a GetSimpleNoExplodeArrayWithResponse call -func ParseGetSimpleNoExplodeArrayResponse(rsp *http.Response) (*GetSimpleNoExplodeArrayResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &GetSimpleNoExplodeArrayResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - return response, nil -} - -// ParseGetSimpleNoExplodeObjectResponse parses an HTTP response from a GetSimpleNoExplodeObjectWithResponse call -func ParseGetSimpleNoExplodeObjectResponse(rsp *http.Response) (*GetSimpleNoExplodeObjectResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &GetSimpleNoExplodeObjectResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - return response, nil -} - -// ParseGetSimplePrimitiveResponse parses an HTTP response from a GetSimplePrimitiveWithResponse call -func ParseGetSimplePrimitiveResponse(rsp *http.Response) (*GetSimplePrimitiveResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &GetSimplePrimitiveResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - return response, nil -} - -// ParseGetStartingWithNumberResponse parses an HTTP response from a GetStartingWithNumberWithResponse call -func ParseGetStartingWithNumberResponse(rsp *http.Response) (*GetStartingWithNumberResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &GetStartingWithNumberResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - return response, nil -} - -// ServerInterface represents all server handlers. -type ServerInterface interface { - - // (GET /contentObject/{param}) - GetContentObject(ctx echo.Context, param ComplexObject) error - - // (GET /cookie) - GetCookie(ctx echo.Context, params GetCookieParams) error - - // (GET /enums) - EnumParams(ctx echo.Context, params EnumParamsParams) error - - // (GET /header) - GetHeader(ctx echo.Context, params GetHeaderParams) error - - // (GET /labelExplodeArray/{.param*}) - GetLabelExplodeArray(ctx echo.Context, param []int32) error - - // (GET /labelExplodeObject/{.param*}) - GetLabelExplodeObject(ctx echo.Context, param Object) error - - // (GET /labelNoExplodeArray/{.param}) - GetLabelNoExplodeArray(ctx echo.Context, param []int32) error - - // (GET /labelNoExplodeObject/{.param}) - GetLabelNoExplodeObject(ctx echo.Context, param Object) error - - // (GET /matrixExplodeArray/{.id*}) - GetMatrixExplodeArray(ctx echo.Context, id []int32) error - - // (GET /matrixExplodeObject/{.id*}) - GetMatrixExplodeObject(ctx echo.Context, id Object) error - - // (GET /matrixNoExplodeArray/{.id}) - GetMatrixNoExplodeArray(ctx echo.Context, id []int32) error - - // (GET /matrixNoExplodeObject/{.id}) - GetMatrixNoExplodeObject(ctx echo.Context, id Object) error - - // (GET /passThrough/{param}) - GetPassThrough(ctx echo.Context, param string) error - - // (GET /queryDeepObject) - GetDeepObject(ctx echo.Context, params GetDeepObjectParams) error - - // (GET /queryForm) - GetQueryForm(ctx echo.Context, params GetQueryFormParams) error - - // (GET /simpleExplodeArray/{param*}) - GetSimpleExplodeArray(ctx echo.Context, param []int32) error - - // (GET /simpleExplodeObject/{param*}) - GetSimpleExplodeObject(ctx echo.Context, param Object) error - - // (GET /simpleNoExplodeArray/{param}) - GetSimpleNoExplodeArray(ctx echo.Context, param []int32) error - - // (GET /simpleNoExplodeObject/{param}) - GetSimpleNoExplodeObject(ctx echo.Context, param Object) error - - // (GET /simplePrimitive/{param}) - GetSimplePrimitive(ctx echo.Context, param int32) error - - // (GET /startingWithNumber/{1param}) - GetStartingWithNumber(ctx echo.Context, n1param string) error -} - -// ServerInterfaceWrapper converts echo contexts to parameters. -type ServerInterfaceWrapper struct { - Handler ServerInterface -} - -// GetContentObject converts echo context to params. -func (w *ServerInterfaceWrapper) GetContentObject(ctx echo.Context) error { - var err error - // ------------- Path parameter "param" ------------- - var param ComplexObject - - err = json.Unmarshal([]byte(ctx.Param("param")), ¶m) - if err != nil { - return echo.NewHTTPError(http.StatusBadRequest, "Error unmarshaling parameter 'param' as JSON") - } - - // Invoke the callback with all the unmarshaled arguments - err = w.Handler.GetContentObject(ctx, param) - return err -} - -// GetCookie converts echo context to params. -func (w *ServerInterfaceWrapper) GetCookie(ctx echo.Context) error { - var err error - - // Parameter object where we will unmarshal all parameters from the context - var params GetCookieParams - - if cookie, err := ctx.Cookie("p"); err == nil { - - var value int32 - err = runtime.BindStyledParameterWithOptions("simple", "p", cookie.Value, &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationCookie, Explode: false, Required: false, Type: "integer", Format: "int32"}) - if err != nil { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter p: %s", err)) - } - params.P = &value - - } - - if cookie, err := ctx.Cookie("ep"); err == nil { - - var value int32 - err = runtime.BindStyledParameterWithOptions("simple", "ep", cookie.Value, &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationCookie, Explode: true, Required: false, Type: "integer", Format: "int32"}) - if err != nil { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter ep: %s", err)) - } - params.Ep = &value - - } - - if cookie, err := ctx.Cookie("ea"); err == nil { - - var value []int32 - err = runtime.BindStyledParameterWithOptions("simple", "ea", cookie.Value, &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationCookie, Explode: true, Required: false, Type: "array", Format: ""}) - if err != nil { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter ea: %s", err)) - } - params.Ea = &value - - } - - if cookie, err := ctx.Cookie("a"); err == nil { - - var value []int32 - err = runtime.BindStyledParameterWithOptions("simple", "a", cookie.Value, &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationCookie, Explode: false, Required: false, Type: "array", Format: ""}) - if err != nil { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter a: %s", err)) - } - params.A = &value - - } - - if cookie, err := ctx.Cookie("eo"); err == nil { - - var value Object - err = runtime.BindStyledParameterWithOptions("simple", "eo", cookie.Value, &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationCookie, Explode: true, Required: false, Type: "", Format: ""}) - if err != nil { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter eo: %s", err)) - } - params.Eo = &value - - } - - if cookie, err := ctx.Cookie("o"); err == nil { - - var value Object - err = runtime.BindStyledParameterWithOptions("simple", "o", cookie.Value, &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationCookie, Explode: false, Required: false, Type: "", Format: ""}) - if err != nil { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter o: %s", err)) - } - params.O = &value - - } - - if cookie, err := ctx.Cookie("co"); err == nil { - - var value ComplexObject - var decoded string - decoded, err := url.QueryUnescape(cookie.Value) - if err != nil { - return echo.NewHTTPError(http.StatusBadRequest, "Error unescaping cookie parameter 'co'") - } - err = json.Unmarshal([]byte(decoded), &value) - if err != nil { - return echo.NewHTTPError(http.StatusBadRequest, "Error unmarshaling parameter 'co' as JSON") - } - params.Co = &value - - } - - if cookie, err := ctx.Cookie("1s"); err == nil { - - var value string - err = runtime.BindStyledParameterWithOptions("simple", "1s", cookie.Value, &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationCookie, Explode: true, Required: false, Type: "string", Format: ""}) - if err != nil { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter 1s: %s", err)) - } - params.N1s = &value - - } - - // Invoke the callback with all the unmarshaled arguments - err = w.Handler.GetCookie(ctx, params) - return err -} - -// EnumParams converts echo context to params. -func (w *ServerInterfaceWrapper) EnumParams(ctx echo.Context) error { - var err error - - // Parameter object where we will unmarshal all parameters from the context - var params EnumParamsParams - // ------------- Optional query parameter "enumPathParam" ------------- - - err = runtime.BindQueryParameterWithOptions("form", true, false, "enumPathParam", ctx.QueryParams(), ¶ms.EnumPathParam, runtime.BindQueryParameterOptions{Type: "integer", Format: "int32"}) - if err != nil { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter enumPathParam: %s", err)) - } - - // Invoke the callback with all the unmarshaled arguments - err = w.Handler.EnumParams(ctx, params) - return err -} - -// GetHeader converts echo context to params. -func (w *ServerInterfaceWrapper) GetHeader(ctx echo.Context) error { - var err error - - // Parameter object where we will unmarshal all parameters from the context - var params GetHeaderParams - - headers := ctx.Request().Header - // ------------- Optional header parameter "X-Primitive" ------------- - if valueList, found := headers[http.CanonicalHeaderKey("X-Primitive")]; found { - var XPrimitive int32 - n := len(valueList) - if n != 1 { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Expected one value for X-Primitive, got %d", n)) - } - - err = runtime.BindStyledParameterWithOptions("simple", "X-Primitive", valueList[0], &XPrimitive, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int32"}) - if err != nil { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter X-Primitive: %s", err)) - } - - params.XPrimitive = &XPrimitive - } - // ------------- Optional header parameter "X-Primitive-Exploded" ------------- - if valueList, found := headers[http.CanonicalHeaderKey("X-Primitive-Exploded")]; found { - var XPrimitiveExploded int32 - n := len(valueList) - if n != 1 { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Expected one value for X-Primitive-Exploded, got %d", n)) - } - - err = runtime.BindStyledParameterWithOptions("simple", "X-Primitive-Exploded", valueList[0], &XPrimitiveExploded, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: true, Required: false, Type: "integer", Format: "int32"}) - if err != nil { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter X-Primitive-Exploded: %s", err)) - } - - params.XPrimitiveExploded = &XPrimitiveExploded - } - // ------------- Optional header parameter "X-Array-Exploded" ------------- - if valueList, found := headers[http.CanonicalHeaderKey("X-Array-Exploded")]; found { - var XArrayExploded []int32 - n := len(valueList) - if n != 1 { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Expected one value for X-Array-Exploded, got %d", n)) - } - - err = runtime.BindStyledParameterWithOptions("simple", "X-Array-Exploded", valueList[0], &XArrayExploded, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: true, Required: false, Type: "array", Format: ""}) - if err != nil { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter X-Array-Exploded: %s", err)) - } - - params.XArrayExploded = &XArrayExploded - } - // ------------- Optional header parameter "X-Array" ------------- - if valueList, found := headers[http.CanonicalHeaderKey("X-Array")]; found { - var XArray []int32 - n := len(valueList) - if n != 1 { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Expected one value for X-Array, got %d", n)) - } - - err = runtime.BindStyledParameterWithOptions("simple", "X-Array", valueList[0], &XArray, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "array", Format: ""}) - if err != nil { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter X-Array: %s", err)) - } - - params.XArray = &XArray - } - // ------------- Optional header parameter "X-Object-Exploded" ------------- - if valueList, found := headers[http.CanonicalHeaderKey("X-Object-Exploded")]; found { - var XObjectExploded Object - n := len(valueList) - if n != 1 { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Expected one value for X-Object-Exploded, got %d", n)) - } - - err = runtime.BindStyledParameterWithOptions("simple", "X-Object-Exploded", valueList[0], &XObjectExploded, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: true, Required: false, Type: "", Format: ""}) - if err != nil { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter X-Object-Exploded: %s", err)) - } - - params.XObjectExploded = &XObjectExploded - } - // ------------- Optional header parameter "X-Object" ------------- - if valueList, found := headers[http.CanonicalHeaderKey("X-Object")]; found { - var XObject Object - n := len(valueList) - if n != 1 { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Expected one value for X-Object, got %d", n)) - } - - err = runtime.BindStyledParameterWithOptions("simple", "X-Object", valueList[0], &XObject, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "", Format: ""}) - if err != nil { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter X-Object: %s", err)) - } - - params.XObject = &XObject - } - // ------------- Optional header parameter "X-Complex-Object" ------------- - if valueList, found := headers[http.CanonicalHeaderKey("X-Complex-Object")]; found { - var XComplexObject ComplexObject - n := len(valueList) - if n != 1 { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Expected one value for X-Complex-Object, got %d", n)) - } - - err = json.Unmarshal([]byte(valueList[0]), &XComplexObject) - if err != nil { - return echo.NewHTTPError(http.StatusBadRequest, "Error unmarshaling parameter 'X-Complex-Object' as JSON") - } - - params.XComplexObject = &XComplexObject - } - // ------------- Optional header parameter "1-Starting-With-Number" ------------- - if valueList, found := headers[http.CanonicalHeaderKey("1-Starting-With-Number")]; found { - var N1StartingWithNumber string - n := len(valueList) - if n != 1 { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Expected one value for 1-Starting-With-Number, got %d", n)) - } - - err = runtime.BindStyledParameterWithOptions("simple", "1-Starting-With-Number", valueList[0], &N1StartingWithNumber, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "string", Format: ""}) - if err != nil { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter 1-Starting-With-Number: %s", err)) - } - - params.N1StartingWithNumber = &N1StartingWithNumber - } - - // Invoke the callback with all the unmarshaled arguments - err = w.Handler.GetHeader(ctx, params) - return err -} - -// GetLabelExplodeArray converts echo context to params. -func (w *ServerInterfaceWrapper) GetLabelExplodeArray(ctx echo.Context) error { - var err error - // ------------- Path parameter "param" ------------- - var param []int32 - - err = runtime.BindStyledParameterWithOptions("label", "param", ctx.Param("param"), ¶m, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: true, Required: true, Type: "array", Format: ""}) - if err != nil { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter param: %s", err)) - } - - // Invoke the callback with all the unmarshaled arguments - err = w.Handler.GetLabelExplodeArray(ctx, param) - return err -} - -// GetLabelExplodeObject converts echo context to params. -func (w *ServerInterfaceWrapper) GetLabelExplodeObject(ctx echo.Context) error { - var err error - // ------------- Path parameter "param" ------------- - var param Object - - err = runtime.BindStyledParameterWithOptions("label", "param", ctx.Param("param"), ¶m, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: true, Required: true, Type: "", Format: ""}) - if err != nil { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter param: %s", err)) - } - - // Invoke the callback with all the unmarshaled arguments - err = w.Handler.GetLabelExplodeObject(ctx, param) - return err -} - -// GetLabelNoExplodeArray converts echo context to params. -func (w *ServerInterfaceWrapper) GetLabelNoExplodeArray(ctx echo.Context) error { - var err error - // ------------- Path parameter "param" ------------- - var param []int32 - - err = runtime.BindStyledParameterWithOptions("label", "param", ctx.Param("param"), ¶m, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "array", Format: ""}) - if err != nil { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter param: %s", err)) - } - - // Invoke the callback with all the unmarshaled arguments - err = w.Handler.GetLabelNoExplodeArray(ctx, param) - return err -} - -// GetLabelNoExplodeObject converts echo context to params. -func (w *ServerInterfaceWrapper) GetLabelNoExplodeObject(ctx echo.Context) error { - var err error - // ------------- Path parameter "param" ------------- - var param Object - - err = runtime.BindStyledParameterWithOptions("label", "param", ctx.Param("param"), ¶m, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "", Format: ""}) - if err != nil { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter param: %s", err)) - } - - // Invoke the callback with all the unmarshaled arguments - err = w.Handler.GetLabelNoExplodeObject(ctx, param) - return err -} - -// GetMatrixExplodeArray converts echo context to params. -func (w *ServerInterfaceWrapper) GetMatrixExplodeArray(ctx echo.Context) error { - var err error - // ------------- Path parameter "id" ------------- - var id []int32 - - err = runtime.BindStyledParameterWithOptions("matrix", "id", ctx.Param("id"), &id, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: true, Required: true, Type: "array", Format: ""}) - if err != nil { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter id: %s", err)) - } - - // Invoke the callback with all the unmarshaled arguments - err = w.Handler.GetMatrixExplodeArray(ctx, id) - return err -} - -// GetMatrixExplodeObject converts echo context to params. -func (w *ServerInterfaceWrapper) GetMatrixExplodeObject(ctx echo.Context) error { - var err error - // ------------- Path parameter "id" ------------- - var id Object - - err = runtime.BindStyledParameterWithOptions("matrix", "id", ctx.Param("id"), &id, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: true, Required: true, Type: "", Format: ""}) - if err != nil { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter id: %s", err)) - } - - // Invoke the callback with all the unmarshaled arguments - err = w.Handler.GetMatrixExplodeObject(ctx, id) - return err -} - -// GetMatrixNoExplodeArray converts echo context to params. -func (w *ServerInterfaceWrapper) GetMatrixNoExplodeArray(ctx echo.Context) error { - var err error - // ------------- Path parameter "id" ------------- - var id []int32 - - err = runtime.BindStyledParameterWithOptions("matrix", "id", ctx.Param("id"), &id, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "array", Format: ""}) - if err != nil { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter id: %s", err)) - } - - // Invoke the callback with all the unmarshaled arguments - err = w.Handler.GetMatrixNoExplodeArray(ctx, id) - return err -} - -// GetMatrixNoExplodeObject converts echo context to params. -func (w *ServerInterfaceWrapper) GetMatrixNoExplodeObject(ctx echo.Context) error { - var err error - // ------------- Path parameter "id" ------------- - var id Object - - err = runtime.BindStyledParameterWithOptions("matrix", "id", ctx.Param("id"), &id, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "", Format: ""}) - if err != nil { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter id: %s", err)) - } - - // Invoke the callback with all the unmarshaled arguments - err = w.Handler.GetMatrixNoExplodeObject(ctx, id) - return err -} - -// GetPassThrough converts echo context to params. -func (w *ServerInterfaceWrapper) GetPassThrough(ctx echo.Context) error { - var err error - // ------------- Path parameter "param" ------------- - var param string - - param = ctx.Param("param") - - // Invoke the callback with all the unmarshaled arguments - err = w.Handler.GetPassThrough(ctx, param) - return err -} - -// GetDeepObject converts echo context to params. -func (w *ServerInterfaceWrapper) GetDeepObject(ctx echo.Context) error { - var err error - - // Parameter object where we will unmarshal all parameters from the context - var params GetDeepObjectParams - // ------------- Required query parameter "deepObj" ------------- - - err = runtime.BindQueryParameterWithOptions("deepObject", true, true, "deepObj", ctx.QueryParams(), ¶ms.DeepObj, runtime.BindQueryParameterOptions{Type: "", Format: ""}) - if err != nil { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter deepObj: %s", err)) - } - - // Invoke the callback with all the unmarshaled arguments - err = w.Handler.GetDeepObject(ctx, params) - return err -} - -// GetQueryForm converts echo context to params. -func (w *ServerInterfaceWrapper) GetQueryForm(ctx echo.Context) error { - var err error - - // Parameter object where we will unmarshal all parameters from the context - var params GetQueryFormParams - // ------------- Optional query parameter "ea" ------------- - - err = runtime.BindQueryParameterWithOptions("form", true, false, "ea", ctx.QueryParams(), ¶ms.Ea, runtime.BindQueryParameterOptions{Type: "array", Format: ""}) - if err != nil { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter ea: %s", err)) - } - - // ------------- Optional query parameter "a" ------------- - - err = runtime.BindQueryParameterWithOptions("form", false, false, "a", ctx.QueryParams(), ¶ms.A, runtime.BindQueryParameterOptions{Type: "array", Format: ""}) - if err != nil { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter a: %s", err)) - } - - // ------------- Optional query parameter "eo" ------------- - - err = runtime.BindQueryParameterWithOptions("form", true, false, "eo", ctx.QueryParams(), ¶ms.Eo, runtime.BindQueryParameterOptions{Type: "", Format: ""}) - if err != nil { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter eo: %s", err)) - } - - // ------------- Optional query parameter "o" ------------- - - err = runtime.BindQueryParameterWithOptions("form", false, false, "o", ctx.QueryParams(), ¶ms.O, runtime.BindQueryParameterOptions{Type: "", Format: ""}) - if err != nil { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter o: %s", err)) - } - - // ------------- Optional query parameter "ep" ------------- - - err = runtime.BindQueryParameterWithOptions("form", true, false, "ep", ctx.QueryParams(), ¶ms.Ep, runtime.BindQueryParameterOptions{Type: "integer", Format: "int32"}) - if err != nil { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter ep: %s", err)) - } - - // ------------- Optional query parameter "p" ------------- - - err = runtime.BindQueryParameterWithOptions("form", false, false, "p", ctx.QueryParams(), ¶ms.P, runtime.BindQueryParameterOptions{Type: "integer", Format: "int32"}) - if err != nil { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter p: %s", err)) - } - - // ------------- Optional query parameter "ps" ------------- - - err = runtime.BindQueryParameterWithOptions("form", true, false, "ps", ctx.QueryParams(), ¶ms.Ps, runtime.BindQueryParameterOptions{Type: "string", Format: ""}) - if err != nil { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter ps: %s", err)) - } - - // ------------- Optional query parameter "co" ------------- - - if paramValue := ctx.QueryParam("co"); paramValue != "" { - - var value ComplexObject - err = json.Unmarshal([]byte(paramValue), &value) - if err != nil { - return echo.NewHTTPError(http.StatusBadRequest, "Error unmarshaling parameter 'co' as JSON") - } - params.Co = &value - - } - - // ------------- Optional query parameter "1s" ------------- - - err = runtime.BindQueryParameterWithOptions("form", true, false, "1s", ctx.QueryParams(), ¶ms.N1s, runtime.BindQueryParameterOptions{Type: "string", Format: ""}) - if err != nil { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter 1s: %s", err)) - } - - // Invoke the callback with all the unmarshaled arguments - err = w.Handler.GetQueryForm(ctx, params) - return err -} - -// GetSimpleExplodeArray converts echo context to params. -func (w *ServerInterfaceWrapper) GetSimpleExplodeArray(ctx echo.Context) error { - var err error - // ------------- Path parameter "param" ------------- - var param []int32 - - err = runtime.BindStyledParameterWithOptions("simple", "param", ctx.Param("param"), ¶m, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: true, Required: true, Type: "array", Format: ""}) - if err != nil { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter param: %s", err)) - } - - // Invoke the callback with all the unmarshaled arguments - err = w.Handler.GetSimpleExplodeArray(ctx, param) - return err -} - -// GetSimpleExplodeObject converts echo context to params. -func (w *ServerInterfaceWrapper) GetSimpleExplodeObject(ctx echo.Context) error { - var err error - // ------------- Path parameter "param" ------------- - var param Object - - err = runtime.BindStyledParameterWithOptions("simple", "param", ctx.Param("param"), ¶m, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: true, Required: true, Type: "", Format: ""}) - if err != nil { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter param: %s", err)) - } - - // Invoke the callback with all the unmarshaled arguments - err = w.Handler.GetSimpleExplodeObject(ctx, param) - return err -} - -// GetSimpleNoExplodeArray converts echo context to params. -func (w *ServerInterfaceWrapper) GetSimpleNoExplodeArray(ctx echo.Context) error { - var err error - // ------------- Path parameter "param" ------------- - var param []int32 - - err = runtime.BindStyledParameterWithOptions("simple", "param", ctx.Param("param"), ¶m, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "array", Format: ""}) - if err != nil { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter param: %s", err)) - } - - // Invoke the callback with all the unmarshaled arguments - err = w.Handler.GetSimpleNoExplodeArray(ctx, param) - return err -} - -// GetSimpleNoExplodeObject converts echo context to params. -func (w *ServerInterfaceWrapper) GetSimpleNoExplodeObject(ctx echo.Context) error { - var err error - // ------------- Path parameter "param" ------------- - var param Object - - err = runtime.BindStyledParameterWithOptions("simple", "param", ctx.Param("param"), ¶m, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "", Format: ""}) - if err != nil { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter param: %s", err)) - } - - // Invoke the callback with all the unmarshaled arguments - err = w.Handler.GetSimpleNoExplodeObject(ctx, param) - return err -} - -// GetSimplePrimitive converts echo context to params. -func (w *ServerInterfaceWrapper) GetSimplePrimitive(ctx echo.Context) error { - var err error - // ------------- Path parameter "param" ------------- - var param int32 - - err = runtime.BindStyledParameterWithOptions("simple", "param", ctx.Param("param"), ¶m, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "integer", Format: "int32"}) - if err != nil { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter param: %s", err)) - } - - // Invoke the callback with all the unmarshaled arguments - err = w.Handler.GetSimplePrimitive(ctx, param) - return err -} - -// GetStartingWithNumber converts echo context to params. -func (w *ServerInterfaceWrapper) GetStartingWithNumber(ctx echo.Context) error { - var err error - // ------------- Path parameter "1param" ------------- - var n1param string - - n1param = ctx.Param("1param") - - // Invoke the callback with all the unmarshaled arguments - err = w.Handler.GetStartingWithNumber(ctx, n1param) - return err -} - -// This is a simple interface which specifies echo.Route addition functions which -// are present on both echo.Echo and echo.Group, since we want to allow using -// either of them for path registration -type EchoRouter interface { - CONNECT(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - DELETE(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - GET(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - HEAD(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - OPTIONS(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - PATCH(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - POST(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - PUT(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - TRACE(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route -} - -// RegisterHandlers adds each server route to the EchoRouter. -func RegisterHandlers(router EchoRouter, si ServerInterface) { - RegisterHandlersWithBaseURL(router, si, "") -} - -// Registers handlers, and prepends BaseURL to the paths, so that the paths -// can be served under a prefix. -func RegisterHandlersWithBaseURL(router EchoRouter, si ServerInterface, baseURL string) { - - wrapper := ServerInterfaceWrapper{ - Handler: si, - } - - router.GET(baseURL+"/contentObject/:param", wrapper.GetContentObject) - router.GET(baseURL+"/cookie", wrapper.GetCookie) - router.GET(baseURL+"/enums", wrapper.EnumParams) - router.GET(baseURL+"/header", wrapper.GetHeader) - router.GET(baseURL+"/labelExplodeArray/:param", wrapper.GetLabelExplodeArray) - router.GET(baseURL+"/labelExplodeObject/:param", wrapper.GetLabelExplodeObject) - router.GET(baseURL+"/labelNoExplodeArray/:param", wrapper.GetLabelNoExplodeArray) - router.GET(baseURL+"/labelNoExplodeObject/:param", wrapper.GetLabelNoExplodeObject) - router.GET(baseURL+"/matrixExplodeArray/:id", wrapper.GetMatrixExplodeArray) - router.GET(baseURL+"/matrixExplodeObject/:id", wrapper.GetMatrixExplodeObject) - router.GET(baseURL+"/matrixNoExplodeArray/:id", wrapper.GetMatrixNoExplodeArray) - router.GET(baseURL+"/matrixNoExplodeObject/:id", wrapper.GetMatrixNoExplodeObject) - router.GET(baseURL+"/passThrough/:param", wrapper.GetPassThrough) - router.GET(baseURL+"/queryDeepObject", wrapper.GetDeepObject) - router.GET(baseURL+"/queryForm", wrapper.GetQueryForm) - router.GET(baseURL+"/simpleExplodeArray/:param", wrapper.GetSimpleExplodeArray) - router.GET(baseURL+"/simpleExplodeObject/:param", wrapper.GetSimpleExplodeObject) - router.GET(baseURL+"/simpleNoExplodeArray/:param", wrapper.GetSimpleNoExplodeArray) - router.GET(baseURL+"/simpleNoExplodeObject/:param", wrapper.GetSimpleNoExplodeObject) - router.GET(baseURL+"/simplePrimitive/:param", wrapper.GetSimplePrimitive) - router.GET(baseURL+"/startingWithNumber/:1param", wrapper.GetStartingWithNumber) - -} - -// Base64 encoded, gzipped, json marshaled Swagger object -var swaggerSpec = []string{ - - "H4sIAAAAAAAC/9xaUXOjNhD+K8y2Tx1i7Ls+8Za5XtvM9HJpnZnrTCYPCqyDroB0kpwm4+G/dySBAYEx", - "dkyS61uCVvvtfqy+aJdsIGIZZznmSkK4AYGSs1yi+WVJM57iX+Uj/SRiucJc6R8VPqqAp4Tm+jcZJZgR", - "8/yJI4QglaD5PRRF4UOMMhKUK8pyCOHck8avV2F57O4rRgq0qfVj0D8wbfX42S6GG+CCcRSK2uAu4gYa", - "zRXeo4DChwt5Hmc2qHLxjrEUSa4Xa2c/ClxBCD8Edf5BCR58ruMR+G1NBcYQ3lSbfQ1d49y23LZjXFEh", - "1SXJsIcYHwRL+xYcVGPlN1zdGk5pvmJ6c0ojLF9OboDg08W19q6o0u7hGqXyligeUIAPDyikfQ2L2Xw2", - "14aMY044hRDez+azBfjAiUpM/EH5vm1+wYYTQbJCr9yjSVcnS/R71W8DfkP1obnBuBIkQ4VCQnjTqh/C", - "eUojszn4KplTRUOvp10YJRsQmrDBr2gwyNDkUok1Frd+u8bfzee78LZ2gXMQCoMZRIz9Q3GYDWPRoaF9", - "ILigGVX0QRviI09ZjBCuSCqxTCyq3FSpgd+gasVERpQ9BO/fgd85E4U/ClHTswMQn41YosQeEYI8jYUl", - "LViqMJOj8LdPLFpPPJ0whvieLowtLaw6MKN4Ya2AxkmZC91FHKLgOMSpjns7k8ga1Bz2ZhAx6JKg1zyp", - "iFA0v/f+pSrx8nV2Z6Sy18tCtohwpdtVlxhXZJ2qYxUG87UttV6B+ZivsystLHKfwlxVizZF7dZ7IOka", - "ZZXntzWKp0aFGdcquSpFtM5Yr0B4s5jP/Xfz+a0/Qgy6kvuz5ab1JphXVUuZfIIkRjEkr79bi+fKa1K5", - "KZP/++yqsWVSoR2APvtYasOLSG83kHNt3R/EiwnxjqheWY67UVlt6idrCnXeFcF3J9LdREpHVUJHSLbr", - "c3G2LK3PvlCVnF1W1i8m4ym5w7QsDlPAwWZmJOunwbv0H+62rtL1leeYa/BpDpAPUj2ZJsNkCKe8XDc5", - "q9qPQ0nb1YWcgrUxp2tyfi5ZX1Xt56e9b4Cgpuj8j+pqm3+7sg4gbm9pPYe5166tjChBH53SovHwwfvU", - "2XTMwaPx5DVls5uOsG1NHcTY8Vq1h7LDimkycjpSReMR5JxAqL7niurq1GGsPUOl3npVcSLldSLY+j4Z", - "M5e8qs0Hp5IHTLVfZeZo+vRfEHk9ct6VcsNqT4ccI/LhlscZD8TW9dEV4nQLdaHEdcynvoSbFH5lIhvi", - "7M+t0R7KRjXV7lDlVHPEmi+9FQ5sqp2oXiyocc21y9n0o04H8RSA21T3zX/cbKeZ7A9kezpAr9TGHTjD", - "c9NXHkM4wR43KnacHDgpfsbfBPs5tX29GtEpLzvb3u58waYIk7HW+sB5AG1vZ8IwGUPuxX3/XWvZs+8N", - "zximZ2785/Nl38Y3MWWYjKXtB4/x/DQ/zzjMHMXEiOKZkobyb8oXqhI7mw42ixFUdLZN2NgsJu5sNMPm", - "X1Rs3GuRQgiJUjwMgvL/UxRKNdP9QUb4jFAobov/AgAA//8eGGgVvSQAAA==", -} - -// GetSwagger returns the content of the embedded swagger specification file -// or error if failed to decode -func decodeSpec() ([]byte, error) { - zipped, err := base64.StdEncoding.DecodeString(strings.Join(swaggerSpec, "")) - if err != nil { - return nil, fmt.Errorf("error base64 decoding spec: %w", err) - } - zr, err := gzip.NewReader(bytes.NewReader(zipped)) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - var buf bytes.Buffer - _, err = buf.ReadFrom(zr) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - - return buf.Bytes(), nil -} - -var rawSpec = decodeSpecCached() - -// a naive cached of a decoded swagger spec -func decodeSpecCached() func() ([]byte, error) { - data, err := decodeSpec() - return func() ([]byte, error) { - return data, err - } -} - -// Constructs a synthetic filesystem for resolving external references when loading openapi specifications. -func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { - res := make(map[string]func() ([]byte, error)) - if len(pathToFile) > 0 { - res[pathToFile] = rawSpec - } - - return res -} - -// GetSwagger returns the Swagger specification corresponding to the generated code -// in this file. The external references of Swagger specification are resolved. -// The logic of resolving external references is tightly connected to "import-mapping" feature. -// Externally referenced files must be embedded in the corresponding golang packages. -// Urls can be supported but this task was out of the scope. -func GetSwagger() (swagger *openapi3.T, err error) { - resolvePath := PathToRawSpec("") - - loader := openapi3.NewLoader() - loader.IsExternalRefsAllowed = true - loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() - pathToFile = path.Clean(pathToFile) - getSpec, ok := resolvePath[pathToFile] - if !ok { - err1 := fmt.Errorf("path not found: %s", pathToFile) - return nil, err1 - } - return getSpec() - } - var specData []byte - specData, err = rawSpec() - if err != nil { - return - } - swagger, err = loader.LoadFromData(specData) - if err != nil { - return - } - return -} diff --git a/internal/test/parameters/parameters.yaml b/internal/test/parameters/parameters.yaml deleted file mode 100644 index 682af6ab17..0000000000 --- a/internal/test/parameters/parameters.yaml +++ /dev/null @@ -1,533 +0,0 @@ -openapi: "3.0.1" -info: - version: 1.0.0 - title: Test Server - license: - name: MIT -servers: - - url: http://openapitest.deepmap.ai -paths: - /simplePrimitive/{param}: - get: - operationId: getSimplePrimitive - parameters: - - name: param - in: path - required: true - style: simple - schema: - type: integer - format: int32 - responses: - '200': - $ref: "#/components/responses/SimpleResponse" - /simpleNoExplodeArray/{param}: - get: - operationId: getSimpleNoExplodeArray - parameters: - - name: param - in: path - required: true - style: simple - explode: false - schema: - type: array - items: - type: integer - format: int32 - responses: - '200': - $ref: "#/components/responses/SimpleResponse" - /simpleExplodeArray/{param*}: - get: - operationId: getSimpleExplodeArray - parameters: - - name: param - in: path - required: true - style: simple - explode: true - schema: - type: array - items: - type: integer - format: int32 - responses: - '200': - $ref: "#/components/responses/SimpleResponse" - /simpleNoExplodeObject/{param}: - get: - operationId: getSimpleNoExplodeObject - parameters: - - name: param - in: path - required: true - style: simple - explode: false - schema: - $ref: "#/components/schemas/Object" - responses: - '200': - $ref: "#/components/responses/SimpleResponse" - /simpleExplodeObject/{param*}: - get: - operationId: getSimpleExplodeObject - parameters: - - name: param - in: path - required: true - style: simple - explode: true - schema: - $ref: "#/components/schemas/Object" - responses: - '200': - $ref: "#/components/responses/SimpleResponse" - /labelNoExplodeArray/{.param}: - get: - operationId: getLabelNoExplodeArray - parameters: - - name: param - in: path - required: true - style: label - explode: false - schema: - type: array - items: - type: integer - format: int32 - responses: - '200': - $ref: "#/components/responses/SimpleResponse" - /labelExplodeArray/{.param*}: - get: - operationId: getLabelExplodeArray - parameters: - - name: param - in: path - required: true - style: label - explode: true - schema: - type: array - items: - type: integer - format: int32 - responses: - '200': - $ref: "#/components/responses/SimpleResponse" - /labelNoExplodeObject/{.param}: - get: - operationId: getLabelNoExplodeObject - parameters: - - name: param - in: path - required: true - style: label - explode: false - schema: - $ref: "#/components/schemas/Object" - responses: - '200': - $ref: "#/components/responses/SimpleResponse" - /labelExplodeObject/{.param*}: - get: - operationId: getLabelExplodeObject - parameters: - - name: param - in: path - required: true - style: label - explode: true - schema: - $ref: "#/components/schemas/Object" - responses: - '200': - $ref: "#/components/responses/SimpleResponse" - /matrixNoExplodeArray/{.id}: - get: - operationId: getMatrixNoExplodeArray - parameters: - - name: id - in: path - required: true - style: matrix - explode: false - schema: - type: array - items: - type: integer - format: int32 - responses: - '200': - $ref: "#/components/responses/SimpleResponse" - /matrixExplodeArray/{.id*}: - get: - operationId: getMatrixExplodeArray - parameters: - - name: id - in: path - required: true - style: matrix - explode: true - schema: - type: array - items: - type: integer - format: int32 - responses: - '200': - $ref: "#/components/responses/SimpleResponse" - /matrixNoExplodeObject/{.id}: - get: - operationId: getMatrixNoExplodeObject - parameters: - - name: id - in: path - required: true - style: matrix - explode: false - schema: - $ref: "#/components/schemas/Object" - responses: - '200': - $ref: "#/components/responses/SimpleResponse" - /matrixExplodeObject/{.id*}: - get: - operationId: getMatrixExplodeObject - parameters: - - name: id - in: path - required: true - style: matrix - explode: true - schema: - $ref: "#/components/schemas/Object" - responses: - '200': - $ref: "#/components/responses/SimpleResponse" - /contentObject/{param}: - get: - operationId: getContentObject - parameters: - - name: param - in: path - required: true - content: - application/json: - schema: - $ref: "#/components/schemas/ComplexObject" - responses: - '200': - $ref: "#/components/responses/SimpleResponse" - /passThrough/{param}: - get: - operationId: getPassThrough - parameters: - - name: param - in: path - required: true - content: - text/plain: - schema: - type: string - responses: - '200': - $ref: "#/components/responses/SimpleResponse" - /startingWithNumber/{1param}: - get: - operationId: getStartingWithNumber - parameters: - - name: 1param - in: path - required: true - content: - text/plain: - schema: - type: string - responses: - '200': - $ref: "#/components/responses/SimpleResponse" - /queryForm: - get: - operationId: getQueryForm - parameters: - - name: ea - description: exploded array - in: query - required: false - style: form - explode: true - schema: - type: array - items: - type: integer - format: int32 - - name: a - description: array - in: query - required: false - style: form - explode: false - schema: - type: array - items: - type: integer - format: int32 - - name: eo - description: exploded object - in: query - required: false - explode: true - schema: - $ref: "#/components/schemas/Object" - - name: o - description: object - in: query - required: false - explode: false - schema: - $ref: "#/components/schemas/Object" - - name: ep - description: exploded primitive - in: query - required: false - explode: true - schema: - type: integer - format: int32 - - name: p - description: primitive - in: query - required: false - explode: false - schema: - type: integer - format: int32 - - name: ps - description: primitive string - in: query - required: false - schema: - type: string - - name: co - description: complex object - in: query - required: false - content: - application/json: - schema: - $ref: "#/components/schemas/ComplexObject" - - name: 1s - description: name starting with number - in: query - required: false - schema: - type: string - responses: - '200': - $ref: "#/components/responses/SimpleResponse" - /queryDeepObject: - get: - operationId: getDeepObject - parameters: - - name: deepObj - description: deep object - in: query - required: true - style: deepObject - explode: true - schema: - $ref: "#/components/schemas/ComplexObject" - responses: - default: - $ref: "#/components/responses/SimpleResponse" - /header: - get: - operationId: getHeader - parameters: - - name: X-Primitive - description: primitive - in: header - required: false - explode: false - schema: - type: integer - format: int32 - - name: X-Primitive-Exploded - description: primitive - in: header - required: false - explode: true - schema: - type: integer - format: int32 - - name: X-Array-Exploded - description: exploded array - in: header - required: false - explode: true - schema: - type: array - items: - type: integer - format: int32 - - name: X-Array - description: array - in: header - required: false - explode: false - schema: - type: array - items: - type: integer - format: int32 - - name: X-Object-Exploded - description: exploded object - in: header - required: false - explode: true - schema: - $ref: "#/components/schemas/Object" - - name: X-Object - description: object - in: header - required: false - explode: false - schema: - $ref: "#/components/schemas/Object" - - name: X-Complex-Object - description: complex object - in: header - required: false - content: - application/json: - schema: - $ref: "#/components/schemas/ComplexObject" - - name: 1-Starting-With-Number - description: name starting with number - in: header - required: false - schema: - type: string - responses: - default: - $ref: "#/components/responses/SimpleResponse" - - /cookie: - get: - operationId: getCookie - parameters: - - name: p - description: primitive - in: cookie - required: false - explode: false - schema: - type: integer - format: int32 - - name: ep - description: primitive - in: cookie - required: false - explode: true - schema: - type: integer - format: int32 - - name: ea - description: exploded array - in: cookie - required: false - explode: true - schema: - type: array - items: - type: integer - format: int32 - - name: a - description: array - in: cookie - required: false - explode: false - schema: - type: array - items: - type: integer - format: int32 - - name: eo - description: exploded object - in: cookie - required: false - explode: true - schema: - $ref: "#/components/schemas/Object" - - name: o - description: object - in: cookie - required: false - explode: false - schema: - $ref: "#/components/schemas/Object" - - name: co - description: complex object - in: cookie - required: false - content: - application/json: - schema: - $ref: "#/components/schemas/ComplexObject" - - name: 1s - description: name starting with number - in: cookie - required: false - schema: - type: string - responses: - default: - $ref: "#/components/responses/SimpleResponse" - /enums: - get: - operationId: enumParams - parameters: - - name: enumPathParam - description: Parameter with enum values - in: query - required: false - schema: - type: integer - format: int32 - enum: [ 100, 200 ] - responses: - 204: - description: no content -components: - schemas: - Object: - properties: - role: - type: string - firstName: - type: string - required: - - role - - firstName - ComplexObject: - properties: - Object: - $ref: "#/components/schemas/Object" - Id: - type: integer - IsAdmin: - type: boolean - required: - - Object - - Id - - IsAdmin - responses: - SimpleResponse: - description: A simple response object - content: - text/plain: - schema: - type: string diff --git a/internal/test/parameters/parameters_test.go b/internal/test/parameters/parameters_test.go deleted file mode 100644 index 0635301dfa..0000000000 --- a/internal/test/parameters/parameters_test.go +++ /dev/null @@ -1,733 +0,0 @@ -package parameters - -import ( - "encoding/json" - "fmt" - "net/http" - "net/http/httptest" - "testing" - - "github.com/oapi-codegen/testutil" - "github.com/labstack/echo/v4" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -type testServer struct { - array []int32 - object *Object - complexObject *ComplexObject - passThrough *string - n1param *string - primitive *int32 - primitiveString *string - cookieParams *GetCookieParams - queryParams *GetQueryFormParams - headerParams *GetHeaderParams -} - -func (t *testServer) reset() { - t.array = nil - t.object = nil - t.complexObject = nil - t.passThrough = nil - t.n1param = nil - t.primitive = nil - t.primitiveString = nil - t.cookieParams = nil - t.queryParams = nil - t.headerParams = nil -} - -// (GET /contentObject/{param}) -func (t *testServer) GetContentObject(ctx echo.Context, param ComplexObject) error { - t.complexObject = ¶m - return nil -} - -// (GET /labelExplodeArray/{.param*}) -func (t *testServer) GetLabelExplodeArray(ctx echo.Context, param []int32) error { - t.array = param - return nil -} - -// (GET /labelExplodeObject/{.param*}) -func (t *testServer) GetLabelExplodeObject(ctx echo.Context, param Object) error { - t.object = ¶m - return nil -} - -// (GET /labelNoExplodeArray/{.param}) -func (t *testServer) GetLabelNoExplodeArray(ctx echo.Context, param []int32) error { - t.array = param - return nil -} - -// (GET /labelNoExplodeObject/{.param}) -func (t *testServer) GetLabelNoExplodeObject(ctx echo.Context, param Object) error { - t.object = ¶m - return nil -} - -// (GET /matrixExplodeArray/{.param*}) -func (t *testServer) GetMatrixExplodeArray(ctx echo.Context, param []int32) error { - t.array = param - return nil -} - -// (GET /matrixExplodeObject/{.param*}) -func (t *testServer) GetMatrixExplodeObject(ctx echo.Context, param Object) error { - t.object = ¶m - return nil -} - -// (GET /matrixNoExplodeArray/{.param}) -func (t *testServer) GetMatrixNoExplodeArray(ctx echo.Context, param []int32) error { - t.array = param - return nil -} - -// (GET /matrixNoExplodeObject/{.param}) -func (t *testServer) GetMatrixNoExplodeObject(ctx echo.Context, param Object) error { - t.object = ¶m - return nil -} - -// (GET /simpleExplodeArray/{param*}) -func (t *testServer) GetSimpleExplodeArray(ctx echo.Context, param []int32) error { - t.array = param - return nil -} - -// (GET /simpleExplodeObject/{param*}) -func (t *testServer) GetSimpleExplodeObject(ctx echo.Context, param Object) error { - t.object = ¶m - return nil -} - -// (GET /simpleNoExplodeArray/{param}) -func (t *testServer) GetSimpleNoExplodeArray(ctx echo.Context, param []int32) error { - t.array = param - return nil -} - -// (GET /simpleNoExplodeObject/{param}) -func (t *testServer) GetSimpleNoExplodeObject(ctx echo.Context, param Object) error { - t.object = ¶m - return nil -} - -// (GET /passThrough/{param}) -func (t *testServer) GetPassThrough(ctx echo.Context, param string) error { - t.passThrough = ¶m - return nil -} - -// (GET /startingWithjNumber/{param}) -func (t *testServer) GetStartingWithNumber(ctx echo.Context, n1param string) error { - t.n1param = &n1param - return nil -} - -// (GET /queryDeepObject) -func (t *testServer) GetDeepObject(ctx echo.Context, params GetDeepObjectParams) error { - t.complexObject = ¶ms.DeepObj - return nil -} - -// (GET /simplePrimitive/{param}) -func (t *testServer) GetSimplePrimitive(ctx echo.Context, param int32) error { - t.primitive = ¶m - return nil -} - -// (GET /queryForm) -func (t *testServer) GetQueryForm(ctx echo.Context, params GetQueryFormParams) error { - t.queryParams = ¶ms - if params.Ea != nil { - t.array = *params.Ea - } - if params.A != nil { - t.array = *params.A - } - if params.Eo != nil { - t.object = params.Eo - } - if params.O != nil { - t.object = params.O - } - if params.P != nil { - t.primitive = params.P - } - if params.Ps != nil { - t.primitiveString = params.Ps - } - if params.Ep != nil { - t.primitive = params.Ep - } - if params.Co != nil { - t.complexObject = params.Co - } - if params.N1s != nil { - t.n1param = params.N1s - } - return nil -} - -// (GET /header) -func (t *testServer) GetHeader(ctx echo.Context, params GetHeaderParams) error { - t.headerParams = ¶ms - if params.XPrimitive != nil { - t.primitive = params.XPrimitive - } - if params.XPrimitiveExploded != nil { - t.primitive = params.XPrimitiveExploded - } - if params.XArray != nil { - t.array = *params.XArray - } - if params.XArrayExploded != nil { - t.array = *params.XArrayExploded - } - if params.XObject != nil { - t.object = params.XObject - } - if params.XObjectExploded != nil { - t.object = params.XObjectExploded - } - if params.XComplexObject != nil { - t.complexObject = params.XComplexObject - } - if params.N1StartingWithNumber != nil { - t.n1param = params.N1StartingWithNumber - } - return nil -} - -// (GET /cookie) -func (t *testServer) GetCookie(ctx echo.Context, params GetCookieParams) error { - t.cookieParams = ¶ms - if params.Ea != nil { - t.array = *params.Ea - } - if params.A != nil { - t.array = *params.A - } - if params.Eo != nil { - t.object = params.Eo - } - if params.O != nil { - t.object = params.O - } - if params.P != nil { - t.primitive = params.P - } - if params.Ep != nil { - t.primitive = params.Ep - } - if params.Co != nil { - t.complexObject = params.Co - } - if params.N1s != nil { - t.n1param = params.N1s - } - return nil -} - -// (GET /enums) -func (t *testServer) EnumParams(ctx echo.Context, params EnumParamsParams) error { - return ctx.NoContent(http.StatusNotImplemented) -} - -func TestParameterBinding(t *testing.T) { - var ts testServer - e := echo.New() - RegisterHandlers(e, &ts) - - expectedObject := Object{ - FirstName: "Alex", - Role: "admin", - } - - expectedComplexObject := ComplexObject{ - Object: expectedObject, - Id: 12345, - IsAdmin: true, - } - - expectedArray := []int32{3, 4, 5} - - var expectedPrimitive int32 = 5 - - var expectedPrimitiveString = "123;456" - - var expectedN1Param = "foo" - - // Check the passthrough case - // (GET /passThrough/{param}) - result := testutil.NewRequest().Get("/passThrough/some%20string").GoWithHTTPHandler(t, e) - assert.Equal(t, http.StatusOK, result.Code()) - require.NotNil(t, ts.passThrough) - assert.EqualValues(t, "some string", *ts.passThrough) - ts.reset() - - // Check JSON marshaling of Content based parameter - // (GET /contentObject/{param}) - marshaledComplexObject, err := json.Marshal(expectedComplexObject) - assert.NoError(t, err) - q := fmt.Sprintf("/contentObject/%s", string(marshaledComplexObject)) - result = testutil.NewRequest().Get(q).GoWithHTTPHandler(t, e) - assert.Equal(t, http.StatusOK, result.Code()) - assert.EqualValues(t, &expectedComplexObject, ts.complexObject) - ts.reset() - - // (GET /labelExplodeArray/{.param*}) - result = testutil.NewRequest().Get("/labelExplodeArray/.3.4.5").GoWithHTTPHandler(t, e) - assert.Equal(t, http.StatusOK, result.Code()) - assert.EqualValues(t, expectedArray, ts.array) - ts.reset() - - // (GET /labelExplodeObject/{.param*}) - result = testutil.NewRequest().Get("/labelExplodeObject/.role=admin.firstName=Alex").GoWithHTTPHandler(t, e) - assert.Equal(t, http.StatusOK, result.Code()) - assert.EqualValues(t, &expectedObject, ts.object) - ts.reset() - - // (GET /labelNoExplodeArray/{.param}) - result = testutil.NewRequest().Get("/labelNoExplodeArray/.3,4,5").GoWithHTTPHandler(t, e) - assert.Equal(t, http.StatusOK, result.Code()) - assert.EqualValues(t, expectedArray, ts.array) - ts.reset() - - // (GET /labelNoExplodeObject/{.param}) - result = testutil.NewRequest().Get("/labelNoExplodeObject/.role,admin,firstName,Alex").GoWithHTTPHandler(t, e) - assert.Equal(t, http.StatusOK, result.Code()) - assert.EqualValues(t, &expectedObject, ts.object) - ts.reset() - - // (GET /matrixExplodeArray/{.param*}) - uri := "/matrixExplodeArray/;id=3;id=4;id=5" - result = testutil.NewRequest().Get(uri).GoWithHTTPHandler(t, e) - assert.Equal(t, http.StatusOK, result.Code()) - assert.EqualValues(t, expectedArray, ts.array) - ts.reset() - - // (GET /matrixExplodeObject/{.param*}) - uri = "/matrixExplodeObject/;role=admin;firstName=Alex" - result = testutil.NewRequest().Get(uri).GoWithHTTPHandler(t, e) - assert.Equal(t, http.StatusOK, result.Code()) - assert.EqualValues(t, &expectedObject, ts.object) - ts.reset() - - // (GET /matrixNoExplodeArray/{.param}) - result = testutil.NewRequest().Get("/matrixNoExplodeArray/;id=3,4,5").GoWithHTTPHandler(t, e) - assert.Equal(t, http.StatusOK, result.Code()) - assert.EqualValues(t, expectedArray, ts.array) - ts.reset() - - // (GET /matrixNoExplodeObject/{.param}) - result = testutil.NewRequest().Get("/matrixNoExplodeObject/;id=role,admin,firstName,Alex").GoWithHTTPHandler(t, e) - assert.Equal(t, http.StatusOK, result.Code()) - assert.EqualValues(t, &expectedObject, ts.object) - ts.reset() - - // (GET /simpleExplodeArray/{param*}) - result = testutil.NewRequest().Get("/simpleExplodeArray/3,4,5").GoWithHTTPHandler(t, e) - assert.Equal(t, http.StatusOK, result.Code()) - assert.EqualValues(t, expectedArray, ts.array) - ts.reset() - - // (GET /simpleExplodeObject/{param*}) - result = testutil.NewRequest().Get("/simpleExplodeObject/role=admin,firstName=Alex").GoWithHTTPHandler(t, e) - assert.Equal(t, http.StatusOK, result.Code()) - assert.EqualValues(t, &expectedObject, ts.object) - ts.reset() - - // (GET /simpleNoExplodeArray/{param}) - result = testutil.NewRequest().Get("/simpleNoExplodeArray/3,4,5").GoWithHTTPHandler(t, e) - assert.Equal(t, http.StatusOK, result.Code()) - assert.EqualValues(t, expectedArray, ts.array) - ts.reset() - - // (GET /simpleNoExplodeObject/{param}) - result = testutil.NewRequest().Get("/simpleNoExplodeObject/role,admin,firstName,Alex").GoWithHTTPHandler(t, e) - assert.Equal(t, http.StatusOK, result.Code()) - assert.EqualValues(t, &expectedObject, ts.object) - ts.reset() - - // (GET /simplePrimitive/{param}) - result = testutil.NewRequest().Get("/simplePrimitive/5").GoWithHTTPHandler(t, e) - assert.Equal(t, http.StatusOK, result.Code()) - assert.EqualValues(t, &expectedPrimitive, ts.primitive) - ts.reset() - - // (GET /startingWithNumber/{1param}) - result = testutil.NewRequest().Get("/startingWithNumber/foo").GoWithHTTPHandler(t, e) - assert.Equal(t, http.StatusOK, result.Code()) - assert.EqualValues(t, &expectedN1Param, ts.n1param) - ts.reset() - - // ---------------------- Test Form Query Parameters ---------------------- - // (GET /queryForm) - - // unexploded array - result = testutil.NewRequest().Get("/queryForm?a=3,4,5").GoWithHTTPHandler(t, e) - assert.Equal(t, http.StatusOK, result.Code()) - assert.EqualValues(t, expectedArray, ts.array) - ts.reset() - - // exploded array - result = testutil.NewRequest().Get("/queryForm?ea=3&ea=4&ea=5").GoWithHTTPHandler(t, e) - assert.Equal(t, http.StatusOK, result.Code()) - assert.EqualValues(t, expectedArray, ts.array) - ts.reset() - - // unexploded object - result = testutil.NewRequest().Get("/queryForm?o=role,admin,firstName,Alex").GoWithHTTPHandler(t, e) - assert.Equal(t, http.StatusOK, result.Code()) - assert.EqualValues(t, &expectedObject, ts.object) - ts.reset() - - // exploded object - result = testutil.NewRequest().Get("/queryForm?role=admin&firstName=Alex").GoWithHTTPHandler(t, e) - assert.Equal(t, http.StatusOK, result.Code()) - assert.EqualValues(t, &expectedObject, ts.object) - ts.reset() - - // exploded primitive - result = testutil.NewRequest().Get("/queryForm?ep=5").GoWithHTTPHandler(t, e) - assert.Equal(t, http.StatusOK, result.Code()) - assert.EqualValues(t, &expectedPrimitive, ts.primitive) - ts.reset() - - // unexploded primitive - result = testutil.NewRequest().Get("/queryForm?p=5").GoWithHTTPHandler(t, e) - assert.Equal(t, http.StatusOK, result.Code()) - assert.EqualValues(t, &expectedPrimitive, ts.primitive) - ts.reset() - - // primitive string within reserved char, i.e., ';' escaped to '%3B' - result = testutil.NewRequest().Get("/queryForm?ps=123%3B456").GoWithHTTPHandler(t, e) - assert.Equal(t, http.StatusOK, result.Code()) - assert.EqualValues(t, &expectedPrimitiveString, ts.primitiveString) - ts.reset() - - // complex object - q = fmt.Sprintf("/queryForm?co=%s", string(marshaledComplexObject)) - result = testutil.NewRequest().Get(q).GoWithHTTPHandler(t, e) - assert.Equal(t, http.StatusOK, result.Code()) - assert.EqualValues(t, &expectedComplexObject, ts.complexObject) - ts.reset() - - // starting with number - result = testutil.NewRequest().Get("/queryForm?1s=foo").GoWithHTTPHandler(t, e) - assert.Equal(t, http.StatusOK, result.Code()) - assert.EqualValues(t, &expectedN1Param, ts.n1param) - ts.reset() - - // complex object via deepObject - do := `deepObj[Id]=12345&deepObj[IsAdmin]=true&deepObj[Object][firstName]=Alex&deepObj[Object][role]=admin` - q = "/queryDeepObject?" + do - result = testutil.NewRequest().Get(q).GoWithHTTPHandler(t, e) - assert.Equal(t, http.StatusOK, result.Code()) - assert.EqualValues(t, &expectedComplexObject, ts.complexObject) - ts.reset() - - // ---------------------- Test Header Query Parameters -------------------- - - // unexploded header primitive. - result = testutil.NewRequest().WithHeader("X-Primitive", "5").Get("/header").GoWithHTTPHandler(t, e) - assert.Equal(t, http.StatusOK, result.Code()) - assert.EqualValues(t, &expectedPrimitive, ts.primitive) - ts.reset() - - // exploded header primitive. - result = testutil.NewRequest().WithHeader("X-Primitive-Exploded", "5").Get("/header").GoWithHTTPHandler(t, e) - assert.Equal(t, http.StatusOK, result.Code()) - assert.EqualValues(t, &expectedPrimitive, ts.primitive) - ts.reset() - - // unexploded header array - result = testutil.NewRequest().WithHeader("X-Array", "3,4,5").Get("/header").GoWithHTTPHandler(t, e) - assert.Equal(t, http.StatusOK, result.Code()) - assert.EqualValues(t, expectedArray, ts.array) - ts.reset() - - // exploded header array - result = testutil.NewRequest().WithHeader("X-Array-Exploded", "3,4,5").Get("/header").GoWithHTTPHandler(t, e) - assert.Equal(t, http.StatusOK, result.Code()) - assert.EqualValues(t, expectedArray, ts.array) - ts.reset() - - // unexploded header object - result = testutil.NewRequest().WithHeader("X-Object", - "role,admin,firstName,Alex").Get("/header").GoWithHTTPHandler(t, e) - assert.Equal(t, http.StatusOK, result.Code()) - assert.EqualValues(t, &expectedObject, ts.object) - ts.reset() - - // exploded header object - result = testutil.NewRequest().WithHeader("X-Object-Exploded", - "role=admin,firstName=Alex").Get("/header").GoWithHTTPHandler(t, e) - assert.Equal(t, http.StatusOK, result.Code()) - assert.EqualValues(t, &expectedObject, ts.object) - ts.reset() - - // complex object - result = testutil.NewRequest().WithHeader("X-Complex-Object", - string(marshaledComplexObject)).Get("/header").GoWithHTTPHandler(t, e) - assert.Equal(t, http.StatusOK, result.Code()) - assert.EqualValues(t, &expectedComplexObject, ts.complexObject) - ts.reset() - - // starting with number - result = testutil.NewRequest().WithHeader("1-Starting-With-Number", - "foo").Get("/header").GoWithHTTPHandler(t, e) - assert.Equal(t, http.StatusOK, result.Code()) - assert.EqualValues(t, &expectedN1Param, ts.n1param) - ts.reset() - - // ------------------------- Test Cookie Parameters ------------------------ - result = testutil.NewRequest().WithCookieNameValue("p", "5").Get("/cookie").GoWithHTTPHandler(t, e) - assert.Equal(t, http.StatusOK, result.Code()) - assert.EqualValues(t, &expectedPrimitive, ts.primitive) - ts.reset() - - result = testutil.NewRequest().WithCookieNameValue("ep", "5").Get("/cookie").GoWithHTTPHandler(t, e) - assert.Equal(t, http.StatusOK, result.Code()) - assert.EqualValues(t, &expectedPrimitive, ts.primitive) - ts.reset() - - result = testutil.NewRequest().WithCookieNameValue("a", "3,4,5").Get("/cookie").GoWithHTTPHandler(t, e) - assert.Equal(t, http.StatusOK, result.Code()) - assert.EqualValues(t, expectedArray, ts.array) - ts.reset() - - result = testutil.NewRequest().WithCookieNameValue( - "o", "role,admin,firstName,Alex").Get("/cookie").GoWithHTTPHandler(t, e) - assert.Equal(t, http.StatusOK, result.Code()) - assert.EqualValues(t, &expectedObject, ts.object) - ts.reset() - - result = testutil.NewRequest().WithCookieNameValue("1s", "foo").Get("/cookie").GoWithHTTPHandler(t, e) - assert.Equal(t, http.StatusOK, result.Code()) - assert.EqualValues(t, &expectedN1Param, ts.n1param) - ts.reset() -} - -func doRequest(t *testing.T, e *echo.Echo, code int, req *http.Request) *httptest.ResponseRecorder { - rec := httptest.NewRecorder() - e.ServeHTTP(rec, req) - assert.Equal(t, code, rec.Code) - return rec -} - -func TestClientPathParams(t *testing.T) { - var ts testServer - e := echo.New() - RegisterHandlers(e, &ts) - server := "http://example.com" - - expectedObject := Object{ - FirstName: "Alex", - Role: "admin", - } - - expectedComplexObject := ComplexObject{ - Object: expectedObject, - Id: 12345, - IsAdmin: true, - } - - expectedArray := []int32{3, 4, 5} - - var expectedPrimitive int32 = 5 - - req, err := NewGetPassThroughRequest(server, "some string") - assert.NoError(t, err) - doRequest(t, e, http.StatusOK, req) - require.NotNil(t, ts.passThrough) - assert.Equal(t, "some string", *ts.passThrough) - ts.reset() - - req, err = NewGetStartingWithNumberRequest(server, "some string") - assert.NoError(t, err) - doRequest(t, e, http.StatusOK, req) - require.NotNil(t, ts.n1param) - assert.Equal(t, "some string", *ts.n1param) - ts.reset() - - req, err = NewGetContentObjectRequest(server, expectedComplexObject) - assert.NoError(t, err) - doRequest(t, e, http.StatusOK, req) - assert.EqualValues(t, &expectedComplexObject, ts.complexObject) - ts.reset() - - // Label style - req, err = NewGetLabelExplodeArrayRequest(server, expectedArray) - assert.NoError(t, err) - doRequest(t, e, http.StatusOK, req) - assert.EqualValues(t, expectedArray, ts.array) - ts.reset() - - req, err = NewGetLabelNoExplodeArrayRequest(server, expectedArray) - assert.NoError(t, err) - doRequest(t, e, http.StatusOK, req) - assert.EqualValues(t, expectedArray, ts.array) - ts.reset() - - req, err = NewGetLabelExplodeObjectRequest(server, expectedObject) - assert.NoError(t, err) - doRequest(t, e, http.StatusOK, req) - assert.EqualValues(t, &expectedObject, ts.object) - ts.reset() - - req, err = NewGetLabelNoExplodeObjectRequest(server, expectedObject) - assert.NoError(t, err) - doRequest(t, e, http.StatusOK, req) - assert.EqualValues(t, &expectedObject, ts.object) - ts.reset() - - // Matrix style - req, err = NewGetMatrixExplodeArrayRequest(server, expectedArray) - assert.NoError(t, err) - doRequest(t, e, http.StatusOK, req) - assert.EqualValues(t, expectedArray, ts.array) - ts.reset() - - req, err = NewGetMatrixNoExplodeArrayRequest(server, expectedArray) - assert.NoError(t, err) - doRequest(t, e, http.StatusOK, req) - assert.EqualValues(t, expectedArray, ts.array) - ts.reset() - - req, err = NewGetMatrixExplodeObjectRequest(server, expectedObject) - assert.NoError(t, err) - doRequest(t, e, http.StatusOK, req) - assert.EqualValues(t, &expectedObject, ts.object) - ts.reset() - - req, err = NewGetMatrixNoExplodeObjectRequest(server, expectedObject) - assert.NoError(t, err) - doRequest(t, e, http.StatusOK, req) - assert.EqualValues(t, &expectedObject, ts.object) - ts.reset() - - // Simple style - req, err = NewGetSimpleExplodeArrayRequest(server, expectedArray) - assert.NoError(t, err) - doRequest(t, e, http.StatusOK, req) - assert.EqualValues(t, expectedArray, ts.array) - ts.reset() - - req, err = NewGetSimpleNoExplodeArrayRequest(server, expectedArray) - assert.NoError(t, err) - doRequest(t, e, http.StatusOK, req) - assert.EqualValues(t, expectedArray, ts.array) - ts.reset() - - req, err = NewGetSimpleExplodeObjectRequest(server, expectedObject) - assert.NoError(t, err) - doRequest(t, e, http.StatusOK, req) - assert.EqualValues(t, &expectedObject, ts.object) - ts.reset() - - req, err = NewGetSimpleNoExplodeObjectRequest(server, expectedObject) - assert.NoError(t, err) - doRequest(t, e, http.StatusOK, req) - assert.EqualValues(t, &expectedObject, ts.object) - ts.reset() - - req, err = NewGetSimplePrimitiveRequest(server, expectedPrimitive) - assert.NoError(t, err) - doRequest(t, e, http.StatusOK, req) - assert.EqualValues(t, &expectedPrimitive, ts.primitive) - ts.reset() -} - -func TestClientQueryParams(t *testing.T) { - var ts testServer - e := echo.New() - RegisterHandlers(e, &ts) - server := "http://example.com" - - expectedObject1 := Object{ - FirstName: "Alex", - Role: "admin", - } - expectedObject2 := Object{ - FirstName: "Marcin", - Role: "annoyed_at_swagger", - } - - expectedComplexObject := ComplexObject{ - Object: expectedObject2, - Id: 12345, - IsAdmin: true, - } - - expectedArray1 := []int32{3, 4, 5} - expectedArray2 := []int32{6, 7, 8} - - var expectedPrimitive1 int32 = 5 - var expectedPrimitive2 int32 = 100 - var expectedPrimitiveString = "123;456" - - var expectedStartingWithNumber = "111" - - // Check query params - qParams := GetQueryFormParams{ - Ea: &expectedArray1, - A: &expectedArray2, - Eo: &expectedObject1, - O: &expectedObject2, - Ep: &expectedPrimitive1, - P: &expectedPrimitive2, - Ps: &expectedPrimitiveString, - Co: &expectedComplexObject, - N1s: &expectedStartingWithNumber, - } - - req, err := NewGetQueryFormRequest(server, &qParams) - assert.NoError(t, err) - doRequest(t, e, http.StatusOK, req) - require.NotNil(t, ts.queryParams) - assert.EqualValues(t, qParams, *ts.queryParams) - ts.reset() - - // Check cookie params - cParams := GetCookieParams{ - Ea: &expectedArray1, - A: &expectedArray2, - Eo: &expectedObject1, - O: &expectedObject2, - Ep: &expectedPrimitive1, - P: &expectedPrimitive2, - Co: &expectedComplexObject, - N1s: &expectedStartingWithNumber, - } - req, err = NewGetCookieRequest(server, &cParams) - assert.NoError(t, err) - doRequest(t, e, http.StatusOK, req) - require.NotNil(t, ts.cookieParams) - assert.EqualValues(t, cParams, *ts.cookieParams) - ts.reset() - - // Check Header parameters - hParams := GetHeaderParams{ - XArrayExploded: &expectedArray1, - XArray: &expectedArray2, - XObjectExploded: &expectedObject1, - XObject: &expectedObject2, - XPrimitiveExploded: &expectedPrimitive1, - XPrimitive: &expectedPrimitive2, - XComplexObject: &expectedComplexObject, - N1StartingWithNumber: &expectedStartingWithNumber, - } - req, err = NewGetHeaderRequest(server, &hParams) - assert.NoError(t, err) - doRequest(t, e, http.StatusOK, req) - require.NotNil(t, ts.headerParams) - assert.EqualValues(t, hParams, *ts.headerParams) - ts.reset() -} diff --git a/internal/test/issues/issue-1529/strict-echo/config.yaml b/internal/test/parameters/path/label/config.yaml similarity index 60% rename from internal/test/issues/issue-1529/strict-echo/config.yaml rename to internal/test/parameters/path/label/config.yaml index 56abc0bee7..a03fc0b3aa 100644 --- a/internal/test/issues/issue-1529/strict-echo/config.yaml +++ b/internal/test/parameters/path/label/config.yaml @@ -1,9 +1,7 @@ # yaml-language-server: $schema=../../../../../configuration-schema.json -package: issue1529 +package: pathlabel generate: + echo-server: true client: true models: true - embedded-spec: true - echo-server: true - strict-server: true -output: issue1529.gen.go +output: path_label.gen.go diff --git a/internal/test/parameters/path/label/doc.go b/internal/test/parameters/path/label/doc.go new file mode 100644 index 0000000000..b3b688af1f --- /dev/null +++ b/internal/test/parameters/path/label/doc.go @@ -0,0 +1,3 @@ +package pathlabel + +//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml spec.yaml diff --git a/internal/test/parameters/path/label/path_label.gen.go b/internal/test/parameters/path/label/path_label.gen.go new file mode 100644 index 0000000000..804dfd01cf --- /dev/null +++ b/internal/test/parameters/path/label/path_label.gen.go @@ -0,0 +1,888 @@ +// Package pathlabel provides primitives to interact with the openapi HTTP API. +// +// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. +package pathlabel + +import ( + "context" + "fmt" + "io" + "net/http" + "net/url" + "strings" + + "github.com/labstack/echo/v4" + "github.com/oapi-codegen/runtime" +) + +// Object defines model for Object. +type Object struct { + FirstName string `json:"firstName"` + Role string `json:"role"` +} + +// RequestEditorFn is the function signature for the RequestEditor callback function +type RequestEditorFn func(ctx context.Context, req *http.Request) error + +// Doer performs HTTP requests. +// +// The standard http.Client implements this interface. +type HttpRequestDoer interface { + Do(req *http.Request) (*http.Response, error) +} + +// Client which conforms to the OpenAPI3 specification for this service. +type Client struct { + // The endpoint of the server conforming to this interface, with scheme, + // https://api.deepmap.com for example. This can contain a path relative + // to the server, such as https://api.deepmap.com/dev-test, and all the + // paths in the swagger spec will be appended to the server. + Server string + + // Doer for performing requests, typically a *http.Client with any + // customized settings, such as certificate chains. + Client HttpRequestDoer + + // A list of callbacks for modifying requests which are generated before sending over + // the network. + RequestEditors []RequestEditorFn +} + +// ClientOption allows setting custom parameters during construction +type ClientOption func(*Client) error + +// Creates a new Client, with reasonable defaults +func NewClient(server string, opts ...ClientOption) (*Client, error) { + // create a client with sane default values + client := Client{ + Server: server, + } + // mutate client and add all optional params + for _, o := range opts { + if err := o(&client); err != nil { + return nil, err + } + } + // ensure the server URL always has a trailing slash + if !strings.HasSuffix(client.Server, "/") { + client.Server += "/" + } + // create httpClient, if not already present + if client.Client == nil { + client.Client = &http.Client{} + } + return &client, nil +} + +// WithHTTPClient allows overriding the default Doer, which is +// automatically created using http.Client. This is useful for tests. +func WithHTTPClient(doer HttpRequestDoer) ClientOption { + return func(c *Client) error { + c.Client = doer + return nil + } +} + +// WithRequestEditorFn allows setting up a callback function, which will be +// called right before sending the request. This can be used to mutate the request. +func WithRequestEditorFn(fn RequestEditorFn) ClientOption { + return func(c *Client) error { + c.RequestEditors = append(c.RequestEditors, fn) + return nil + } +} + +// The interface specification for the client above. +type ClientInterface interface { + // GetExplodeArray request + GetExplodeArray(ctx context.Context, param []int32, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetExplodeObject request + GetExplodeObject(ctx context.Context, param Object, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetExplodePrimitive request + GetExplodePrimitive(ctx context.Context, param int32, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetNoExplodeArray request + GetNoExplodeArray(ctx context.Context, param []int32, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetNoExplodeObject request + GetNoExplodeObject(ctx context.Context, param Object, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetNoExplodePrimitive request + GetNoExplodePrimitive(ctx context.Context, param int32, reqEditors ...RequestEditorFn) (*http.Response, error) +} + +func (c *Client) GetExplodeArray(ctx context.Context, param []int32, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetExplodeArrayRequest(c.Server, param) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetExplodeObject(ctx context.Context, param Object, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetExplodeObjectRequest(c.Server, param) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetExplodePrimitive(ctx context.Context, param int32, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetExplodePrimitiveRequest(c.Server, param) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetNoExplodeArray(ctx context.Context, param []int32, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetNoExplodeArrayRequest(c.Server, param) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetNoExplodeObject(ctx context.Context, param Object, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetNoExplodeObjectRequest(c.Server, param) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetNoExplodePrimitive(ctx context.Context, param int32, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetNoExplodePrimitiveRequest(c.Server, param) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +// NewGetExplodeArrayRequest generates requests for GetExplodeArray +func NewGetExplodeArrayRequest(server string, param []int32) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("label", true, "param", param, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "array", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/explodeArray/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetExplodeObjectRequest generates requests for GetExplodeObject +func NewGetExplodeObjectRequest(server string, param Object) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("label", true, "param", param, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "object", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/explodeObject/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetExplodePrimitiveRequest generates requests for GetExplodePrimitive +func NewGetExplodePrimitiveRequest(server string, param int32) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("label", true, "param", param, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "integer", Format: "int32"}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/explodePrimitive/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetNoExplodeArrayRequest generates requests for GetNoExplodeArray +func NewGetNoExplodeArrayRequest(server string, param []int32) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("label", false, "param", param, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "array", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/noExplodeArray/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetNoExplodeObjectRequest generates requests for GetNoExplodeObject +func NewGetNoExplodeObjectRequest(server string, param Object) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("label", false, "param", param, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "object", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/noExplodeObject/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetNoExplodePrimitiveRequest generates requests for GetNoExplodePrimitive +func NewGetNoExplodePrimitiveRequest(server string, param int32) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("label", false, "param", param, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "integer", Format: "int32"}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/noExplodePrimitive/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +func (c *Client) applyEditors(ctx context.Context, req *http.Request, additionalEditors []RequestEditorFn) error { + for _, r := range c.RequestEditors { + if err := r(ctx, req); err != nil { + return err + } + } + for _, r := range additionalEditors { + if err := r(ctx, req); err != nil { + return err + } + } + return nil +} + +// ClientWithResponses builds on ClientInterface to offer response payloads +type ClientWithResponses struct { + ClientInterface +} + +// NewClientWithResponses creates a new ClientWithResponses, which wraps +// Client with return type handling +func NewClientWithResponses(server string, opts ...ClientOption) (*ClientWithResponses, error) { + client, err := NewClient(server, opts...) + if err != nil { + return nil, err + } + return &ClientWithResponses{client}, nil +} + +// WithBaseURL overrides the baseURL. +func WithBaseURL(baseURL string) ClientOption { + return func(c *Client) error { + newBaseURL, err := url.Parse(baseURL) + if err != nil { + return err + } + c.Server = newBaseURL.String() + return nil + } +} + +// ClientWithResponsesInterface is the interface specification for the client with responses above. +type ClientWithResponsesInterface interface { + // GetExplodeArrayWithResponse request + GetExplodeArrayWithResponse(ctx context.Context, param []int32, reqEditors ...RequestEditorFn) (*GetExplodeArrayResponse, error) + + // GetExplodeObjectWithResponse request + GetExplodeObjectWithResponse(ctx context.Context, param Object, reqEditors ...RequestEditorFn) (*GetExplodeObjectResponse, error) + + // GetExplodePrimitiveWithResponse request + GetExplodePrimitiveWithResponse(ctx context.Context, param int32, reqEditors ...RequestEditorFn) (*GetExplodePrimitiveResponse, error) + + // GetNoExplodeArrayWithResponse request + GetNoExplodeArrayWithResponse(ctx context.Context, param []int32, reqEditors ...RequestEditorFn) (*GetNoExplodeArrayResponse, error) + + // GetNoExplodeObjectWithResponse request + GetNoExplodeObjectWithResponse(ctx context.Context, param Object, reqEditors ...RequestEditorFn) (*GetNoExplodeObjectResponse, error) + + // GetNoExplodePrimitiveWithResponse request + GetNoExplodePrimitiveWithResponse(ctx context.Context, param int32, reqEditors ...RequestEditorFn) (*GetNoExplodePrimitiveResponse, error) +} + +type GetExplodeArrayResponse struct { + Body []byte + HTTPResponse *http.Response +} + +// Status returns HTTPResponse.Status +func (r GetExplodeArrayResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetExplodeArrayResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetExplodeObjectResponse struct { + Body []byte + HTTPResponse *http.Response +} + +// Status returns HTTPResponse.Status +func (r GetExplodeObjectResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetExplodeObjectResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetExplodePrimitiveResponse struct { + Body []byte + HTTPResponse *http.Response +} + +// Status returns HTTPResponse.Status +func (r GetExplodePrimitiveResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetExplodePrimitiveResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetNoExplodeArrayResponse struct { + Body []byte + HTTPResponse *http.Response +} + +// Status returns HTTPResponse.Status +func (r GetNoExplodeArrayResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetNoExplodeArrayResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetNoExplodeObjectResponse struct { + Body []byte + HTTPResponse *http.Response +} + +// Status returns HTTPResponse.Status +func (r GetNoExplodeObjectResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetNoExplodeObjectResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetNoExplodePrimitiveResponse struct { + Body []byte + HTTPResponse *http.Response +} + +// Status returns HTTPResponse.Status +func (r GetNoExplodePrimitiveResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetNoExplodePrimitiveResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// GetExplodeArrayWithResponse request returning *GetExplodeArrayResponse +func (c *ClientWithResponses) GetExplodeArrayWithResponse(ctx context.Context, param []int32, reqEditors ...RequestEditorFn) (*GetExplodeArrayResponse, error) { + rsp, err := c.GetExplodeArray(ctx, param, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetExplodeArrayResponse(rsp) +} + +// GetExplodeObjectWithResponse request returning *GetExplodeObjectResponse +func (c *ClientWithResponses) GetExplodeObjectWithResponse(ctx context.Context, param Object, reqEditors ...RequestEditorFn) (*GetExplodeObjectResponse, error) { + rsp, err := c.GetExplodeObject(ctx, param, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetExplodeObjectResponse(rsp) +} + +// GetExplodePrimitiveWithResponse request returning *GetExplodePrimitiveResponse +func (c *ClientWithResponses) GetExplodePrimitiveWithResponse(ctx context.Context, param int32, reqEditors ...RequestEditorFn) (*GetExplodePrimitiveResponse, error) { + rsp, err := c.GetExplodePrimitive(ctx, param, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetExplodePrimitiveResponse(rsp) +} + +// GetNoExplodeArrayWithResponse request returning *GetNoExplodeArrayResponse +func (c *ClientWithResponses) GetNoExplodeArrayWithResponse(ctx context.Context, param []int32, reqEditors ...RequestEditorFn) (*GetNoExplodeArrayResponse, error) { + rsp, err := c.GetNoExplodeArray(ctx, param, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetNoExplodeArrayResponse(rsp) +} + +// GetNoExplodeObjectWithResponse request returning *GetNoExplodeObjectResponse +func (c *ClientWithResponses) GetNoExplodeObjectWithResponse(ctx context.Context, param Object, reqEditors ...RequestEditorFn) (*GetNoExplodeObjectResponse, error) { + rsp, err := c.GetNoExplodeObject(ctx, param, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetNoExplodeObjectResponse(rsp) +} + +// GetNoExplodePrimitiveWithResponse request returning *GetNoExplodePrimitiveResponse +func (c *ClientWithResponses) GetNoExplodePrimitiveWithResponse(ctx context.Context, param int32, reqEditors ...RequestEditorFn) (*GetNoExplodePrimitiveResponse, error) { + rsp, err := c.GetNoExplodePrimitive(ctx, param, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetNoExplodePrimitiveResponse(rsp) +} + +// ParseGetExplodeArrayResponse parses an HTTP response from a GetExplodeArrayWithResponse call +func ParseGetExplodeArrayResponse(rsp *http.Response) (*GetExplodeArrayResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetExplodeArrayResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + return response, nil +} + +// ParseGetExplodeObjectResponse parses an HTTP response from a GetExplodeObjectWithResponse call +func ParseGetExplodeObjectResponse(rsp *http.Response) (*GetExplodeObjectResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetExplodeObjectResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + return response, nil +} + +// ParseGetExplodePrimitiveResponse parses an HTTP response from a GetExplodePrimitiveWithResponse call +func ParseGetExplodePrimitiveResponse(rsp *http.Response) (*GetExplodePrimitiveResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetExplodePrimitiveResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + return response, nil +} + +// ParseGetNoExplodeArrayResponse parses an HTTP response from a GetNoExplodeArrayWithResponse call +func ParseGetNoExplodeArrayResponse(rsp *http.Response) (*GetNoExplodeArrayResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetNoExplodeArrayResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + return response, nil +} + +// ParseGetNoExplodeObjectResponse parses an HTTP response from a GetNoExplodeObjectWithResponse call +func ParseGetNoExplodeObjectResponse(rsp *http.Response) (*GetNoExplodeObjectResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetNoExplodeObjectResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + return response, nil +} + +// ParseGetNoExplodePrimitiveResponse parses an HTTP response from a GetNoExplodePrimitiveWithResponse call +func ParseGetNoExplodePrimitiveResponse(rsp *http.Response) (*GetNoExplodePrimitiveResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetNoExplodePrimitiveResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + return response, nil +} + +// ServerInterface represents all server handlers. +type ServerInterface interface { + + // (GET /explodeArray/{.param*}) + GetExplodeArray(ctx echo.Context, param []int32) error + + // (GET /explodeObject/{.param*}) + GetExplodeObject(ctx echo.Context, param Object) error + + // (GET /explodePrimitive/{.param}) + GetExplodePrimitive(ctx echo.Context, param int32) error + + // (GET /noExplodeArray/{.param}) + GetNoExplodeArray(ctx echo.Context, param []int32) error + + // (GET /noExplodeObject/{.param}) + GetNoExplodeObject(ctx echo.Context, param Object) error + + // (GET /noExplodePrimitive/{.param}) + GetNoExplodePrimitive(ctx echo.Context, param int32) error +} + +// ServerInterfaceWrapper converts echo contexts to parameters. +type ServerInterfaceWrapper struct { + Handler ServerInterface +} + +// GetExplodeArray converts echo context to params. +func (w *ServerInterfaceWrapper) GetExplodeArray(ctx echo.Context) error { + var err error + // ------------- Path parameter "param" ------------- + var param []int32 + + err = runtime.BindStyledParameterWithOptions("label", "param", ctx.Param("param"), ¶m, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: true, Required: true, Type: "array", Format: ""}) + if err != nil { + return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter param: %s", err)) + } + + // Invoke the callback with all the unmarshaled arguments + err = w.Handler.GetExplodeArray(ctx, param) + return err +} + +// GetExplodeObject converts echo context to params. +func (w *ServerInterfaceWrapper) GetExplodeObject(ctx echo.Context) error { + var err error + // ------------- Path parameter "param" ------------- + var param Object + + err = runtime.BindStyledParameterWithOptions("label", "param", ctx.Param("param"), ¶m, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: true, Required: true, Type: "object", Format: ""}) + if err != nil { + return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter param: %s", err)) + } + + // Invoke the callback with all the unmarshaled arguments + err = w.Handler.GetExplodeObject(ctx, param) + return err +} + +// GetExplodePrimitive converts echo context to params. +func (w *ServerInterfaceWrapper) GetExplodePrimitive(ctx echo.Context) error { + var err error + // ------------- Path parameter "param" ------------- + var param int32 + + err = runtime.BindStyledParameterWithOptions("label", "param", ctx.Param("param"), ¶m, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: true, Required: true, Type: "integer", Format: "int32"}) + if err != nil { + return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter param: %s", err)) + } + + // Invoke the callback with all the unmarshaled arguments + err = w.Handler.GetExplodePrimitive(ctx, param) + return err +} + +// GetNoExplodeArray converts echo context to params. +func (w *ServerInterfaceWrapper) GetNoExplodeArray(ctx echo.Context) error { + var err error + // ------------- Path parameter "param" ------------- + var param []int32 + + err = runtime.BindStyledParameterWithOptions("label", "param", ctx.Param("param"), ¶m, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "array", Format: ""}) + if err != nil { + return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter param: %s", err)) + } + + // Invoke the callback with all the unmarshaled arguments + err = w.Handler.GetNoExplodeArray(ctx, param) + return err +} + +// GetNoExplodeObject converts echo context to params. +func (w *ServerInterfaceWrapper) GetNoExplodeObject(ctx echo.Context) error { + var err error + // ------------- Path parameter "param" ------------- + var param Object + + err = runtime.BindStyledParameterWithOptions("label", "param", ctx.Param("param"), ¶m, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "object", Format: ""}) + if err != nil { + return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter param: %s", err)) + } + + // Invoke the callback with all the unmarshaled arguments + err = w.Handler.GetNoExplodeObject(ctx, param) + return err +} + +// GetNoExplodePrimitive converts echo context to params. +func (w *ServerInterfaceWrapper) GetNoExplodePrimitive(ctx echo.Context) error { + var err error + // ------------- Path parameter "param" ------------- + var param int32 + + err = runtime.BindStyledParameterWithOptions("label", "param", ctx.Param("param"), ¶m, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "integer", Format: "int32"}) + if err != nil { + return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter param: %s", err)) + } + + // Invoke the callback with all the unmarshaled arguments + err = w.Handler.GetNoExplodePrimitive(ctx, param) + return err +} + +// This is a simple interface which specifies echo.Route addition functions which +// are present on both echo.Echo and echo.Group, since we want to allow using +// either of them for path registration +type EchoRouter interface { + CONNECT(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route + DELETE(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route + GET(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route + HEAD(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route + OPTIONS(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route + PATCH(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route + POST(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route + PUT(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route + TRACE(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route +} + +// RegisterHandlers adds each server route to the EchoRouter. +func RegisterHandlers(router EchoRouter, si ServerInterface) { + RegisterHandlersWithBaseURL(router, si, "") +} + +// Registers handlers, and prepends BaseURL to the paths, so that the paths +// can be served under a prefix. +func RegisterHandlersWithBaseURL(router EchoRouter, si ServerInterface, baseURL string) { + + wrapper := ServerInterfaceWrapper{ + Handler: si, + } + + router.GET(baseURL+"/explodeArray/:param", wrapper.GetExplodeArray) + router.GET(baseURL+"/explodeObject/:param", wrapper.GetExplodeObject) + router.GET(baseURL+"/explodePrimitive/:param", wrapper.GetExplodePrimitive) + router.GET(baseURL+"/noExplodeArray/:param", wrapper.GetNoExplodeArray) + router.GET(baseURL+"/noExplodeObject/:param", wrapper.GetNoExplodeObject) + router.GET(baseURL+"/noExplodePrimitive/:param", wrapper.GetNoExplodePrimitive) + +} diff --git a/internal/test/parameters/path/label/path_label_test.go b/internal/test/parameters/path/label/path_label_test.go new file mode 100644 index 0000000000..7356a1ed03 --- /dev/null +++ b/internal/test/parameters/path/label/path_label_test.go @@ -0,0 +1,211 @@ +package pathlabel + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/labstack/echo/v4" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +type testServer struct { + primitive *int32 + array []int32 + object *Object +} + +func (s *testServer) reset() { + s.primitive = nil + s.array = nil + s.object = nil +} + +func (s *testServer) GetNoExplodePrimitive(ctx echo.Context, param int32) error { + s.primitive = ¶m + return nil +} + +func (s *testServer) GetNoExplodeArray(ctx echo.Context, param []int32) error { + s.array = param + return nil +} + +func (s *testServer) GetNoExplodeObject(ctx echo.Context, param Object) error { + s.object = ¶m + return nil +} + +func (s *testServer) GetExplodePrimitive(ctx echo.Context, param int32) error { + s.primitive = ¶m + return nil +} + +func (s *testServer) GetExplodeArray(ctx echo.Context, param []int32) error { + s.array = param + return nil +} + +func (s *testServer) GetExplodeObject(ctx echo.Context, param Object) error { + s.object = ¶m + return nil +} + +func doRequest(t *testing.T, e *echo.Echo, method, path string) *httptest.ResponseRecorder { + t.Helper() + req := httptest.NewRequest(method, path, nil) + rec := httptest.NewRecorder() + e.ServeHTTP(rec, req) + return rec +} + +func setup(t *testing.T) (*testServer, *echo.Echo, string) { + t.Helper() + ts := &testServer{} + e := echo.New() + RegisterHandlers(e, ts) + server := "http://example.com" + return ts, e, server +} + +// TestServerLabelPathParams tests server-side deserialization of label-style path parameters. +// +// Label encoding (RFC 6570 §3.2.5): +// +// noExplode primitive: .5 +// noExplode array: .3,4,5 +// noExplode object: .role,admin,firstName,Alex +// explode primitive: .5 +// explode array: .3.4.5 +// explode object: .role=admin.firstName=Alex +func TestServerLabelPathParams(t *testing.T) { + ts, e, _ := setup(t) + + expectedObject := Object{FirstName: "Alex", Role: "admin"} + expectedArray := []int32{3, 4, 5} + var expectedPrimitive int32 = 5 + + t.Run("noExplode/primitive", func(t *testing.T) { + t.Skip("runtime bug: BindStyledParameterWithOptions does not strip '.' prefix for label-style primitives") + rec := doRequest(t, e, http.MethodGet, "/noExplodePrimitive/.5") + assert.Equal(t, http.StatusOK, rec.Code) + require.NotNil(t, ts.primitive) + assert.EqualValues(t, expectedPrimitive, *ts.primitive) + ts.reset() + }) + + t.Run("noExplode/array", func(t *testing.T) { + rec := doRequest(t, e, http.MethodGet, "/noExplodeArray/.3,4,5") + assert.Equal(t, http.StatusOK, rec.Code) + assert.EqualValues(t, expectedArray, ts.array) + ts.reset() + }) + + t.Run("noExplode/object", func(t *testing.T) { + rec := doRequest(t, e, http.MethodGet, "/noExplodeObject/.role,admin,firstName,Alex") + assert.Equal(t, http.StatusOK, rec.Code) + require.NotNil(t, ts.object) + assert.EqualValues(t, expectedObject, *ts.object) + ts.reset() + }) + + t.Run("explode/primitive", func(t *testing.T) { + t.Skip("runtime bug: BindStyledParameterWithOptions does not strip '.' prefix for label-style primitives") + rec := doRequest(t, e, http.MethodGet, "/explodePrimitive/.5") + assert.Equal(t, http.StatusOK, rec.Code) + require.NotNil(t, ts.primitive) + assert.EqualValues(t, expectedPrimitive, *ts.primitive) + ts.reset() + }) + + t.Run("explode/array", func(t *testing.T) { + rec := doRequest(t, e, http.MethodGet, "/explodeArray/.3.4.5") + assert.Equal(t, http.StatusOK, rec.Code) + assert.EqualValues(t, expectedArray, ts.array) + ts.reset() + }) + + t.Run("explode/object", func(t *testing.T) { + rec := doRequest(t, e, http.MethodGet, "/explodeObject/.role=admin.firstName=Alex") + assert.Equal(t, http.StatusOK, rec.Code) + require.NotNil(t, ts.object) + assert.EqualValues(t, expectedObject, *ts.object) + ts.reset() + }) +} + +// TestClientLabelPathParams tests client serialization -> server deserialization round-trip. +func TestClientLabelPathParams(t *testing.T) { + ts, e, server := setup(t) + + expectedObject := Object{FirstName: "Alex", Role: "admin"} + expectedArray := []int32{3, 4, 5} + var expectedPrimitive int32 = 5 + + t.Run("noExplode/primitive", func(t *testing.T) { + t.Skip("runtime bug: BindStyledParameterWithOptions does not strip '.' prefix for label-style primitives") + req, err := NewGetNoExplodePrimitiveRequest(server, expectedPrimitive) + require.NoError(t, err) + rec := httptest.NewRecorder() + e.ServeHTTP(rec, req) + assert.Equal(t, http.StatusOK, rec.Code) + require.NotNil(t, ts.primitive) + assert.EqualValues(t, expectedPrimitive, *ts.primitive) + ts.reset() + }) + + t.Run("noExplode/array", func(t *testing.T) { + req, err := NewGetNoExplodeArrayRequest(server, expectedArray) + require.NoError(t, err) + rec := httptest.NewRecorder() + e.ServeHTTP(rec, req) + assert.Equal(t, http.StatusOK, rec.Code) + assert.EqualValues(t, expectedArray, ts.array) + ts.reset() + }) + + t.Run("noExplode/object", func(t *testing.T) { + req, err := NewGetNoExplodeObjectRequest(server, expectedObject) + require.NoError(t, err) + rec := httptest.NewRecorder() + e.ServeHTTP(rec, req) + assert.Equal(t, http.StatusOK, rec.Code) + require.NotNil(t, ts.object) + assert.EqualValues(t, expectedObject, *ts.object) + ts.reset() + }) + + t.Run("explode/primitive", func(t *testing.T) { + t.Skip("runtime bug: BindStyledParameterWithOptions does not strip '.' prefix for label-style primitives") + req, err := NewGetExplodePrimitiveRequest(server, expectedPrimitive) + require.NoError(t, err) + rec := httptest.NewRecorder() + e.ServeHTTP(rec, req) + assert.Equal(t, http.StatusOK, rec.Code) + require.NotNil(t, ts.primitive) + assert.EqualValues(t, expectedPrimitive, *ts.primitive) + ts.reset() + }) + + t.Run("explode/array", func(t *testing.T) { + req, err := NewGetExplodeArrayRequest(server, expectedArray) + require.NoError(t, err) + rec := httptest.NewRecorder() + e.ServeHTTP(rec, req) + assert.Equal(t, http.StatusOK, rec.Code) + assert.EqualValues(t, expectedArray, ts.array) + ts.reset() + }) + + t.Run("explode/object", func(t *testing.T) { + req, err := NewGetExplodeObjectRequest(server, expectedObject) + require.NoError(t, err) + rec := httptest.NewRecorder() + e.ServeHTTP(rec, req) + assert.Equal(t, http.StatusOK, rec.Code) + require.NotNil(t, ts.object) + assert.EqualValues(t, expectedObject, *ts.object) + ts.reset() + }) +} diff --git a/internal/test/parameters/path/label/spec.yaml b/internal/test/parameters/path/label/spec.yaml new file mode 100644 index 0000000000..a091745481 --- /dev/null +++ b/internal/test/parameters/path/label/spec.yaml @@ -0,0 +1,113 @@ +openapi: "3.0.1" +info: + version: 1.0.0 + title: Path Parameters - Label Style +paths: + # explode: false + /noExplodePrimitive/{.param}: + get: + operationId: getNoExplodePrimitive + parameters: + - name: param + in: path + required: true + style: label + explode: false + schema: + type: integer + format: int32 + responses: + "200": + description: OK + /noExplodeArray/{.param}: + get: + operationId: getNoExplodeArray + parameters: + - name: param + in: path + required: true + style: label + explode: false + schema: + type: array + items: + type: integer + format: int32 + responses: + "200": + description: OK + /noExplodeObject/{.param}: + get: + operationId: getNoExplodeObject + parameters: + - name: param + in: path + required: true + style: label + explode: false + schema: + $ref: "#/components/schemas/Object" + responses: + "200": + description: OK + + # explode: true + /explodePrimitive/{.param}: + get: + operationId: getExplodePrimitive + parameters: + - name: param + in: path + required: true + style: label + explode: true + schema: + type: integer + format: int32 + responses: + "200": + description: OK + /explodeArray/{.param*}: + get: + operationId: getExplodeArray + parameters: + - name: param + in: path + required: true + style: label + explode: true + schema: + type: array + items: + type: integer + format: int32 + responses: + "200": + description: OK + /explodeObject/{.param*}: + get: + operationId: getExplodeObject + parameters: + - name: param + in: path + required: true + style: label + explode: true + schema: + $ref: "#/components/schemas/Object" + responses: + "200": + description: OK + +components: + schemas: + Object: + type: object + properties: + role: + type: string + firstName: + type: string + required: + - role + - firstName diff --git a/internal/test/issues/issue-1182/pkg2/config.yaml b/internal/test/parameters/path/matrix/config.yaml similarity index 54% rename from internal/test/issues/issue-1182/pkg2/config.yaml rename to internal/test/parameters/path/matrix/config.yaml index e61fd48440..33f3cfc001 100644 --- a/internal/test/issues/issue-1182/pkg2/config.yaml +++ b/internal/test/parameters/path/matrix/config.yaml @@ -1,11 +1,7 @@ # yaml-language-server: $schema=../../../../../configuration-schema.json -package: pkg2 +package: pathmatrix generate: echo-server: true client: true models: true - embedded-spec: true - strict-server: true -output: pkg2.gen.go -output-options: - skip-prune: true +output: path_matrix.gen.go diff --git a/internal/test/parameters/path/matrix/doc.go b/internal/test/parameters/path/matrix/doc.go new file mode 100644 index 0000000000..37f8cd2ea6 --- /dev/null +++ b/internal/test/parameters/path/matrix/doc.go @@ -0,0 +1,3 @@ +package pathmatrix + +//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml spec.yaml diff --git a/internal/test/parameters/path/matrix/path_matrix.gen.go b/internal/test/parameters/path/matrix/path_matrix.gen.go new file mode 100644 index 0000000000..fdf5ed0cfc --- /dev/null +++ b/internal/test/parameters/path/matrix/path_matrix.gen.go @@ -0,0 +1,888 @@ +// Package pathmatrix provides primitives to interact with the openapi HTTP API. +// +// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. +package pathmatrix + +import ( + "context" + "fmt" + "io" + "net/http" + "net/url" + "strings" + + "github.com/labstack/echo/v4" + "github.com/oapi-codegen/runtime" +) + +// Object defines model for Object. +type Object struct { + FirstName string `json:"firstName"` + Role string `json:"role"` +} + +// RequestEditorFn is the function signature for the RequestEditor callback function +type RequestEditorFn func(ctx context.Context, req *http.Request) error + +// Doer performs HTTP requests. +// +// The standard http.Client implements this interface. +type HttpRequestDoer interface { + Do(req *http.Request) (*http.Response, error) +} + +// Client which conforms to the OpenAPI3 specification for this service. +type Client struct { + // The endpoint of the server conforming to this interface, with scheme, + // https://api.deepmap.com for example. This can contain a path relative + // to the server, such as https://api.deepmap.com/dev-test, and all the + // paths in the swagger spec will be appended to the server. + Server string + + // Doer for performing requests, typically a *http.Client with any + // customized settings, such as certificate chains. + Client HttpRequestDoer + + // A list of callbacks for modifying requests which are generated before sending over + // the network. + RequestEditors []RequestEditorFn +} + +// ClientOption allows setting custom parameters during construction +type ClientOption func(*Client) error + +// Creates a new Client, with reasonable defaults +func NewClient(server string, opts ...ClientOption) (*Client, error) { + // create a client with sane default values + client := Client{ + Server: server, + } + // mutate client and add all optional params + for _, o := range opts { + if err := o(&client); err != nil { + return nil, err + } + } + // ensure the server URL always has a trailing slash + if !strings.HasSuffix(client.Server, "/") { + client.Server += "/" + } + // create httpClient, if not already present + if client.Client == nil { + client.Client = &http.Client{} + } + return &client, nil +} + +// WithHTTPClient allows overriding the default Doer, which is +// automatically created using http.Client. This is useful for tests. +func WithHTTPClient(doer HttpRequestDoer) ClientOption { + return func(c *Client) error { + c.Client = doer + return nil + } +} + +// WithRequestEditorFn allows setting up a callback function, which will be +// called right before sending the request. This can be used to mutate the request. +func WithRequestEditorFn(fn RequestEditorFn) ClientOption { + return func(c *Client) error { + c.RequestEditors = append(c.RequestEditors, fn) + return nil + } +} + +// The interface specification for the client above. +type ClientInterface interface { + // GetExplodeArray request + GetExplodeArray(ctx context.Context, param []int32, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetExplodeObject request + GetExplodeObject(ctx context.Context, param Object, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetExplodePrimitive request + GetExplodePrimitive(ctx context.Context, param int32, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetNoExplodeArray request + GetNoExplodeArray(ctx context.Context, param []int32, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetNoExplodeObject request + GetNoExplodeObject(ctx context.Context, param Object, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetNoExplodePrimitive request + GetNoExplodePrimitive(ctx context.Context, param int32, reqEditors ...RequestEditorFn) (*http.Response, error) +} + +func (c *Client) GetExplodeArray(ctx context.Context, param []int32, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetExplodeArrayRequest(c.Server, param) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetExplodeObject(ctx context.Context, param Object, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetExplodeObjectRequest(c.Server, param) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetExplodePrimitive(ctx context.Context, param int32, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetExplodePrimitiveRequest(c.Server, param) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetNoExplodeArray(ctx context.Context, param []int32, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetNoExplodeArrayRequest(c.Server, param) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetNoExplodeObject(ctx context.Context, param Object, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetNoExplodeObjectRequest(c.Server, param) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetNoExplodePrimitive(ctx context.Context, param int32, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetNoExplodePrimitiveRequest(c.Server, param) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +// NewGetExplodeArrayRequest generates requests for GetExplodeArray +func NewGetExplodeArrayRequest(server string, param []int32) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("matrix", true, "param", param, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "array", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/explodeArray/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetExplodeObjectRequest generates requests for GetExplodeObject +func NewGetExplodeObjectRequest(server string, param Object) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("matrix", true, "param", param, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "object", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/explodeObject/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetExplodePrimitiveRequest generates requests for GetExplodePrimitive +func NewGetExplodePrimitiveRequest(server string, param int32) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("matrix", true, "param", param, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "integer", Format: "int32"}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/explodePrimitive/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetNoExplodeArrayRequest generates requests for GetNoExplodeArray +func NewGetNoExplodeArrayRequest(server string, param []int32) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("matrix", false, "param", param, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "array", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/noExplodeArray/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetNoExplodeObjectRequest generates requests for GetNoExplodeObject +func NewGetNoExplodeObjectRequest(server string, param Object) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("matrix", false, "param", param, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "object", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/noExplodeObject/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetNoExplodePrimitiveRequest generates requests for GetNoExplodePrimitive +func NewGetNoExplodePrimitiveRequest(server string, param int32) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("matrix", false, "param", param, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "integer", Format: "int32"}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/noExplodePrimitive/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +func (c *Client) applyEditors(ctx context.Context, req *http.Request, additionalEditors []RequestEditorFn) error { + for _, r := range c.RequestEditors { + if err := r(ctx, req); err != nil { + return err + } + } + for _, r := range additionalEditors { + if err := r(ctx, req); err != nil { + return err + } + } + return nil +} + +// ClientWithResponses builds on ClientInterface to offer response payloads +type ClientWithResponses struct { + ClientInterface +} + +// NewClientWithResponses creates a new ClientWithResponses, which wraps +// Client with return type handling +func NewClientWithResponses(server string, opts ...ClientOption) (*ClientWithResponses, error) { + client, err := NewClient(server, opts...) + if err != nil { + return nil, err + } + return &ClientWithResponses{client}, nil +} + +// WithBaseURL overrides the baseURL. +func WithBaseURL(baseURL string) ClientOption { + return func(c *Client) error { + newBaseURL, err := url.Parse(baseURL) + if err != nil { + return err + } + c.Server = newBaseURL.String() + return nil + } +} + +// ClientWithResponsesInterface is the interface specification for the client with responses above. +type ClientWithResponsesInterface interface { + // GetExplodeArrayWithResponse request + GetExplodeArrayWithResponse(ctx context.Context, param []int32, reqEditors ...RequestEditorFn) (*GetExplodeArrayResponse, error) + + // GetExplodeObjectWithResponse request + GetExplodeObjectWithResponse(ctx context.Context, param Object, reqEditors ...RequestEditorFn) (*GetExplodeObjectResponse, error) + + // GetExplodePrimitiveWithResponse request + GetExplodePrimitiveWithResponse(ctx context.Context, param int32, reqEditors ...RequestEditorFn) (*GetExplodePrimitiveResponse, error) + + // GetNoExplodeArrayWithResponse request + GetNoExplodeArrayWithResponse(ctx context.Context, param []int32, reqEditors ...RequestEditorFn) (*GetNoExplodeArrayResponse, error) + + // GetNoExplodeObjectWithResponse request + GetNoExplodeObjectWithResponse(ctx context.Context, param Object, reqEditors ...RequestEditorFn) (*GetNoExplodeObjectResponse, error) + + // GetNoExplodePrimitiveWithResponse request + GetNoExplodePrimitiveWithResponse(ctx context.Context, param int32, reqEditors ...RequestEditorFn) (*GetNoExplodePrimitiveResponse, error) +} + +type GetExplodeArrayResponse struct { + Body []byte + HTTPResponse *http.Response +} + +// Status returns HTTPResponse.Status +func (r GetExplodeArrayResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetExplodeArrayResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetExplodeObjectResponse struct { + Body []byte + HTTPResponse *http.Response +} + +// Status returns HTTPResponse.Status +func (r GetExplodeObjectResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetExplodeObjectResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetExplodePrimitiveResponse struct { + Body []byte + HTTPResponse *http.Response +} + +// Status returns HTTPResponse.Status +func (r GetExplodePrimitiveResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetExplodePrimitiveResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetNoExplodeArrayResponse struct { + Body []byte + HTTPResponse *http.Response +} + +// Status returns HTTPResponse.Status +func (r GetNoExplodeArrayResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetNoExplodeArrayResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetNoExplodeObjectResponse struct { + Body []byte + HTTPResponse *http.Response +} + +// Status returns HTTPResponse.Status +func (r GetNoExplodeObjectResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetNoExplodeObjectResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetNoExplodePrimitiveResponse struct { + Body []byte + HTTPResponse *http.Response +} + +// Status returns HTTPResponse.Status +func (r GetNoExplodePrimitiveResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetNoExplodePrimitiveResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// GetExplodeArrayWithResponse request returning *GetExplodeArrayResponse +func (c *ClientWithResponses) GetExplodeArrayWithResponse(ctx context.Context, param []int32, reqEditors ...RequestEditorFn) (*GetExplodeArrayResponse, error) { + rsp, err := c.GetExplodeArray(ctx, param, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetExplodeArrayResponse(rsp) +} + +// GetExplodeObjectWithResponse request returning *GetExplodeObjectResponse +func (c *ClientWithResponses) GetExplodeObjectWithResponse(ctx context.Context, param Object, reqEditors ...RequestEditorFn) (*GetExplodeObjectResponse, error) { + rsp, err := c.GetExplodeObject(ctx, param, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetExplodeObjectResponse(rsp) +} + +// GetExplodePrimitiveWithResponse request returning *GetExplodePrimitiveResponse +func (c *ClientWithResponses) GetExplodePrimitiveWithResponse(ctx context.Context, param int32, reqEditors ...RequestEditorFn) (*GetExplodePrimitiveResponse, error) { + rsp, err := c.GetExplodePrimitive(ctx, param, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetExplodePrimitiveResponse(rsp) +} + +// GetNoExplodeArrayWithResponse request returning *GetNoExplodeArrayResponse +func (c *ClientWithResponses) GetNoExplodeArrayWithResponse(ctx context.Context, param []int32, reqEditors ...RequestEditorFn) (*GetNoExplodeArrayResponse, error) { + rsp, err := c.GetNoExplodeArray(ctx, param, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetNoExplodeArrayResponse(rsp) +} + +// GetNoExplodeObjectWithResponse request returning *GetNoExplodeObjectResponse +func (c *ClientWithResponses) GetNoExplodeObjectWithResponse(ctx context.Context, param Object, reqEditors ...RequestEditorFn) (*GetNoExplodeObjectResponse, error) { + rsp, err := c.GetNoExplodeObject(ctx, param, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetNoExplodeObjectResponse(rsp) +} + +// GetNoExplodePrimitiveWithResponse request returning *GetNoExplodePrimitiveResponse +func (c *ClientWithResponses) GetNoExplodePrimitiveWithResponse(ctx context.Context, param int32, reqEditors ...RequestEditorFn) (*GetNoExplodePrimitiveResponse, error) { + rsp, err := c.GetNoExplodePrimitive(ctx, param, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetNoExplodePrimitiveResponse(rsp) +} + +// ParseGetExplodeArrayResponse parses an HTTP response from a GetExplodeArrayWithResponse call +func ParseGetExplodeArrayResponse(rsp *http.Response) (*GetExplodeArrayResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetExplodeArrayResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + return response, nil +} + +// ParseGetExplodeObjectResponse parses an HTTP response from a GetExplodeObjectWithResponse call +func ParseGetExplodeObjectResponse(rsp *http.Response) (*GetExplodeObjectResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetExplodeObjectResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + return response, nil +} + +// ParseGetExplodePrimitiveResponse parses an HTTP response from a GetExplodePrimitiveWithResponse call +func ParseGetExplodePrimitiveResponse(rsp *http.Response) (*GetExplodePrimitiveResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetExplodePrimitiveResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + return response, nil +} + +// ParseGetNoExplodeArrayResponse parses an HTTP response from a GetNoExplodeArrayWithResponse call +func ParseGetNoExplodeArrayResponse(rsp *http.Response) (*GetNoExplodeArrayResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetNoExplodeArrayResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + return response, nil +} + +// ParseGetNoExplodeObjectResponse parses an HTTP response from a GetNoExplodeObjectWithResponse call +func ParseGetNoExplodeObjectResponse(rsp *http.Response) (*GetNoExplodeObjectResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetNoExplodeObjectResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + return response, nil +} + +// ParseGetNoExplodePrimitiveResponse parses an HTTP response from a GetNoExplodePrimitiveWithResponse call +func ParseGetNoExplodePrimitiveResponse(rsp *http.Response) (*GetNoExplodePrimitiveResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetNoExplodePrimitiveResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + return response, nil +} + +// ServerInterface represents all server handlers. +type ServerInterface interface { + + // (GET /explodeArray/{.param*}) + GetExplodeArray(ctx echo.Context, param []int32) error + + // (GET /explodeObject/{.param*}) + GetExplodeObject(ctx echo.Context, param Object) error + + // (GET /explodePrimitive/{.param}) + GetExplodePrimitive(ctx echo.Context, param int32) error + + // (GET /noExplodeArray/{.param}) + GetNoExplodeArray(ctx echo.Context, param []int32) error + + // (GET /noExplodeObject/{.param}) + GetNoExplodeObject(ctx echo.Context, param Object) error + + // (GET /noExplodePrimitive/{.param}) + GetNoExplodePrimitive(ctx echo.Context, param int32) error +} + +// ServerInterfaceWrapper converts echo contexts to parameters. +type ServerInterfaceWrapper struct { + Handler ServerInterface +} + +// GetExplodeArray converts echo context to params. +func (w *ServerInterfaceWrapper) GetExplodeArray(ctx echo.Context) error { + var err error + // ------------- Path parameter "param" ------------- + var param []int32 + + err = runtime.BindStyledParameterWithOptions("matrix", "param", ctx.Param("param"), ¶m, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: true, Required: true, Type: "array", Format: ""}) + if err != nil { + return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter param: %s", err)) + } + + // Invoke the callback with all the unmarshaled arguments + err = w.Handler.GetExplodeArray(ctx, param) + return err +} + +// GetExplodeObject converts echo context to params. +func (w *ServerInterfaceWrapper) GetExplodeObject(ctx echo.Context) error { + var err error + // ------------- Path parameter "param" ------------- + var param Object + + err = runtime.BindStyledParameterWithOptions("matrix", "param", ctx.Param("param"), ¶m, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: true, Required: true, Type: "object", Format: ""}) + if err != nil { + return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter param: %s", err)) + } + + // Invoke the callback with all the unmarshaled arguments + err = w.Handler.GetExplodeObject(ctx, param) + return err +} + +// GetExplodePrimitive converts echo context to params. +func (w *ServerInterfaceWrapper) GetExplodePrimitive(ctx echo.Context) error { + var err error + // ------------- Path parameter "param" ------------- + var param int32 + + err = runtime.BindStyledParameterWithOptions("matrix", "param", ctx.Param("param"), ¶m, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: true, Required: true, Type: "integer", Format: "int32"}) + if err != nil { + return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter param: %s", err)) + } + + // Invoke the callback with all the unmarshaled arguments + err = w.Handler.GetExplodePrimitive(ctx, param) + return err +} + +// GetNoExplodeArray converts echo context to params. +func (w *ServerInterfaceWrapper) GetNoExplodeArray(ctx echo.Context) error { + var err error + // ------------- Path parameter "param" ------------- + var param []int32 + + err = runtime.BindStyledParameterWithOptions("matrix", "param", ctx.Param("param"), ¶m, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "array", Format: ""}) + if err != nil { + return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter param: %s", err)) + } + + // Invoke the callback with all the unmarshaled arguments + err = w.Handler.GetNoExplodeArray(ctx, param) + return err +} + +// GetNoExplodeObject converts echo context to params. +func (w *ServerInterfaceWrapper) GetNoExplodeObject(ctx echo.Context) error { + var err error + // ------------- Path parameter "param" ------------- + var param Object + + err = runtime.BindStyledParameterWithOptions("matrix", "param", ctx.Param("param"), ¶m, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "object", Format: ""}) + if err != nil { + return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter param: %s", err)) + } + + // Invoke the callback with all the unmarshaled arguments + err = w.Handler.GetNoExplodeObject(ctx, param) + return err +} + +// GetNoExplodePrimitive converts echo context to params. +func (w *ServerInterfaceWrapper) GetNoExplodePrimitive(ctx echo.Context) error { + var err error + // ------------- Path parameter "param" ------------- + var param int32 + + err = runtime.BindStyledParameterWithOptions("matrix", "param", ctx.Param("param"), ¶m, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "integer", Format: "int32"}) + if err != nil { + return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter param: %s", err)) + } + + // Invoke the callback with all the unmarshaled arguments + err = w.Handler.GetNoExplodePrimitive(ctx, param) + return err +} + +// This is a simple interface which specifies echo.Route addition functions which +// are present on both echo.Echo and echo.Group, since we want to allow using +// either of them for path registration +type EchoRouter interface { + CONNECT(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route + DELETE(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route + GET(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route + HEAD(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route + OPTIONS(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route + PATCH(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route + POST(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route + PUT(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route + TRACE(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route +} + +// RegisterHandlers adds each server route to the EchoRouter. +func RegisterHandlers(router EchoRouter, si ServerInterface) { + RegisterHandlersWithBaseURL(router, si, "") +} + +// Registers handlers, and prepends BaseURL to the paths, so that the paths +// can be served under a prefix. +func RegisterHandlersWithBaseURL(router EchoRouter, si ServerInterface, baseURL string) { + + wrapper := ServerInterfaceWrapper{ + Handler: si, + } + + router.GET(baseURL+"/explodeArray/:param", wrapper.GetExplodeArray) + router.GET(baseURL+"/explodeObject/:param", wrapper.GetExplodeObject) + router.GET(baseURL+"/explodePrimitive/:param", wrapper.GetExplodePrimitive) + router.GET(baseURL+"/noExplodeArray/:param", wrapper.GetNoExplodeArray) + router.GET(baseURL+"/noExplodeObject/:param", wrapper.GetNoExplodeObject) + router.GET(baseURL+"/noExplodePrimitive/:param", wrapper.GetNoExplodePrimitive) + +} diff --git a/internal/test/parameters/path/matrix/path_matrix_test.go b/internal/test/parameters/path/matrix/path_matrix_test.go new file mode 100644 index 0000000000..f7ad084628 --- /dev/null +++ b/internal/test/parameters/path/matrix/path_matrix_test.go @@ -0,0 +1,202 @@ +package pathmatrix + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/labstack/echo/v4" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +type testServer struct { + primitive *int32 + array []int32 + object *Object +} + +func (s *testServer) reset() { + s.primitive = nil + s.array = nil + s.object = nil +} + +func (s *testServer) GetNoExplodePrimitive(ctx echo.Context, param int32) error { + s.primitive = ¶m + return nil +} + +func (s *testServer) GetNoExplodeArray(ctx echo.Context, param []int32) error { + s.array = param + return nil +} + +func (s *testServer) GetNoExplodeObject(ctx echo.Context, param Object) error { + s.object = ¶m + return nil +} + +func (s *testServer) GetExplodePrimitive(ctx echo.Context, param int32) error { + s.primitive = ¶m + return nil +} + +func (s *testServer) GetExplodeArray(ctx echo.Context, param []int32) error { + s.array = param + return nil +} + +func (s *testServer) GetExplodeObject(ctx echo.Context, param Object) error { + s.object = ¶m + return nil +} + +func doRequest(t *testing.T, e *echo.Echo, method, path string) *httptest.ResponseRecorder { + t.Helper() + req := httptest.NewRequest(method, path, nil) + rec := httptest.NewRecorder() + e.ServeHTTP(rec, req) + return rec +} + +func setup(t *testing.T) (*testServer, *echo.Echo, string) { + t.Helper() + ts := &testServer{} + e := echo.New() + RegisterHandlers(e, ts) + server := "http://example.com" + return ts, e, server +} + +// TestServerMatrixPathParams tests server-side deserialization of matrix-style path parameters. +func TestServerMatrixPathParams(t *testing.T) { + ts, e, _ := setup(t) + + expectedObject := Object{FirstName: "Alex", Role: "admin"} + expectedArray := []int32{3, 4, 5} + var expectedPrimitive int32 = 5 + + t.Run("noExplode/primitive", func(t *testing.T) { + t.Skip("runtime bug: BindStyledParameterWithOptions does not strip ';name=val' prefix for matrix-style primitives") + rec := doRequest(t, e, http.MethodGet, "/noExplodePrimitive/;param=5") + assert.Equal(t, http.StatusOK, rec.Code) + require.NotNil(t, ts.primitive) + assert.EqualValues(t, expectedPrimitive, *ts.primitive) + ts.reset() + }) + + t.Run("noExplode/array", func(t *testing.T) { + rec := doRequest(t, e, http.MethodGet, "/noExplodeArray/;param=3,4,5") + assert.Equal(t, http.StatusOK, rec.Code) + assert.EqualValues(t, expectedArray, ts.array) + ts.reset() + }) + + t.Run("noExplode/object", func(t *testing.T) { + rec := doRequest(t, e, http.MethodGet, "/noExplodeObject/;param=role,admin,firstName,Alex") + assert.Equal(t, http.StatusOK, rec.Code) + require.NotNil(t, ts.object) + assert.EqualValues(t, expectedObject, *ts.object) + ts.reset() + }) + + t.Run("explode/primitive", func(t *testing.T) { + t.Skip("runtime bug: BindStyledParameterWithOptions does not strip ';name=val' prefix for matrix-style primitives") + rec := doRequest(t, e, http.MethodGet, "/explodePrimitive/;param=5") + assert.Equal(t, http.StatusOK, rec.Code) + require.NotNil(t, ts.primitive) + assert.EqualValues(t, expectedPrimitive, *ts.primitive) + ts.reset() + }) + + t.Run("explode/array", func(t *testing.T) { + rec := doRequest(t, e, http.MethodGet, "/explodeArray/;param=3;param=4;param=5") + assert.Equal(t, http.StatusOK, rec.Code) + assert.EqualValues(t, expectedArray, ts.array) + ts.reset() + }) + + t.Run("explode/object", func(t *testing.T) { + rec := doRequest(t, e, http.MethodGet, "/explodeObject/;role=admin;firstName=Alex") + assert.Equal(t, http.StatusOK, rec.Code) + require.NotNil(t, ts.object) + assert.EqualValues(t, expectedObject, *ts.object) + ts.reset() + }) +} + +// TestClientMatrixPathParams tests client serialization → server deserialization round-trip. +func TestClientMatrixPathParams(t *testing.T) { + ts, e, server := setup(t) + + expectedObject := Object{FirstName: "Alex", Role: "admin"} + expectedArray := []int32{3, 4, 5} + var expectedPrimitive int32 = 5 + + t.Run("noExplode/primitive", func(t *testing.T) { + t.Skip("runtime bug: BindStyledParameterWithOptions does not strip ';name=val' prefix for matrix-style primitives") + req, err := NewGetNoExplodePrimitiveRequest(server, expectedPrimitive) + require.NoError(t, err) + rec := httptest.NewRecorder() + e.ServeHTTP(rec, req) + assert.Equal(t, http.StatusOK, rec.Code) + require.NotNil(t, ts.primitive) + assert.EqualValues(t, expectedPrimitive, *ts.primitive) + ts.reset() + }) + + t.Run("noExplode/array", func(t *testing.T) { + req, err := NewGetNoExplodeArrayRequest(server, expectedArray) + require.NoError(t, err) + rec := httptest.NewRecorder() + e.ServeHTTP(rec, req) + assert.Equal(t, http.StatusOK, rec.Code) + assert.EqualValues(t, expectedArray, ts.array) + ts.reset() + }) + + t.Run("noExplode/object", func(t *testing.T) { + req, err := NewGetNoExplodeObjectRequest(server, expectedObject) + require.NoError(t, err) + rec := httptest.NewRecorder() + e.ServeHTTP(rec, req) + assert.Equal(t, http.StatusOK, rec.Code) + require.NotNil(t, ts.object) + assert.EqualValues(t, expectedObject, *ts.object) + ts.reset() + }) + + t.Run("explode/primitive", func(t *testing.T) { + t.Skip("runtime bug: BindStyledParameterWithOptions does not strip ';name=val' prefix for matrix-style primitives") + req, err := NewGetExplodePrimitiveRequest(server, expectedPrimitive) + require.NoError(t, err) + rec := httptest.NewRecorder() + e.ServeHTTP(rec, req) + assert.Equal(t, http.StatusOK, rec.Code) + require.NotNil(t, ts.primitive) + assert.EqualValues(t, expectedPrimitive, *ts.primitive) + ts.reset() + }) + + t.Run("explode/array", func(t *testing.T) { + req, err := NewGetExplodeArrayRequest(server, expectedArray) + require.NoError(t, err) + rec := httptest.NewRecorder() + e.ServeHTTP(rec, req) + assert.Equal(t, http.StatusOK, rec.Code) + assert.EqualValues(t, expectedArray, ts.array) + ts.reset() + }) + + t.Run("explode/object", func(t *testing.T) { + req, err := NewGetExplodeObjectRequest(server, expectedObject) + require.NoError(t, err) + rec := httptest.NewRecorder() + e.ServeHTTP(rec, req) + assert.Equal(t, http.StatusOK, rec.Code) + require.NotNil(t, ts.object) + assert.EqualValues(t, expectedObject, *ts.object) + ts.reset() + }) +} diff --git a/internal/test/parameters/path/matrix/spec.yaml b/internal/test/parameters/path/matrix/spec.yaml new file mode 100644 index 0000000000..93fadfd390 --- /dev/null +++ b/internal/test/parameters/path/matrix/spec.yaml @@ -0,0 +1,113 @@ +openapi: "3.0.1" +info: + version: 1.0.0 + title: Path Parameters - Matrix Style +paths: + # explode: false + /noExplodePrimitive/{.param}: + get: + operationId: getNoExplodePrimitive + parameters: + - name: param + in: path + required: true + style: matrix + explode: false + schema: + type: integer + format: int32 + responses: + "200": + description: OK + /noExplodeArray/{.param}: + get: + operationId: getNoExplodeArray + parameters: + - name: param + in: path + required: true + style: matrix + explode: false + schema: + type: array + items: + type: integer + format: int32 + responses: + "200": + description: OK + /noExplodeObject/{.param}: + get: + operationId: getNoExplodeObject + parameters: + - name: param + in: path + required: true + style: matrix + explode: false + schema: + $ref: "#/components/schemas/Object" + responses: + "200": + description: OK + + # explode: true + /explodePrimitive/{.param}: + get: + operationId: getExplodePrimitive + parameters: + - name: param + in: path + required: true + style: matrix + explode: true + schema: + type: integer + format: int32 + responses: + "200": + description: OK + /explodeArray/{.param*}: + get: + operationId: getExplodeArray + parameters: + - name: param + in: path + required: true + style: matrix + explode: true + schema: + type: array + items: + type: integer + format: int32 + responses: + "200": + description: OK + /explodeObject/{.param*}: + get: + operationId: getExplodeObject + parameters: + - name: param + in: path + required: true + style: matrix + explode: true + schema: + $ref: "#/components/schemas/Object" + responses: + "200": + description: OK + +components: + schemas: + Object: + type: object + properties: + role: + type: string + firstName: + type: string + required: + - role + - firstName diff --git a/internal/test/issues/issue-1676/cfg.yaml b/internal/test/parameters/path/simple/config.yaml similarity index 53% rename from internal/test/issues/issue-1676/cfg.yaml rename to internal/test/parameters/path/simple/config.yaml index 964454fe2f..c7c0f47650 100644 --- a/internal/test/issues/issue-1676/cfg.yaml +++ b/internal/test/parameters/path/simple/config.yaml @@ -1,7 +1,7 @@ # yaml-language-server: $schema=../../../../../configuration-schema.json -package: issue1676 -output: ping.gen.go +package: pathsimple generate: + echo-server: true + client: true models: true - gorilla-server: true - strict-server: true +output: path_simple.gen.go diff --git a/internal/test/parameters/path/simple/doc.go b/internal/test/parameters/path/simple/doc.go new file mode 100644 index 0000000000..bfb0361705 --- /dev/null +++ b/internal/test/parameters/path/simple/doc.go @@ -0,0 +1,3 @@ +package pathsimple + +//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml spec.yaml diff --git a/internal/test/parameters/path/simple/path_simple.gen.go b/internal/test/parameters/path/simple/path_simple.gen.go new file mode 100644 index 0000000000..64fe68d6fe --- /dev/null +++ b/internal/test/parameters/path/simple/path_simple.gen.go @@ -0,0 +1,888 @@ +// Package pathsimple provides primitives to interact with the openapi HTTP API. +// +// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. +package pathsimple + +import ( + "context" + "fmt" + "io" + "net/http" + "net/url" + "strings" + + "github.com/labstack/echo/v4" + "github.com/oapi-codegen/runtime" +) + +// Object defines model for Object. +type Object struct { + FirstName string `json:"firstName"` + Role string `json:"role"` +} + +// RequestEditorFn is the function signature for the RequestEditor callback function +type RequestEditorFn func(ctx context.Context, req *http.Request) error + +// Doer performs HTTP requests. +// +// The standard http.Client implements this interface. +type HttpRequestDoer interface { + Do(req *http.Request) (*http.Response, error) +} + +// Client which conforms to the OpenAPI3 specification for this service. +type Client struct { + // The endpoint of the server conforming to this interface, with scheme, + // https://api.deepmap.com for example. This can contain a path relative + // to the server, such as https://api.deepmap.com/dev-test, and all the + // paths in the swagger spec will be appended to the server. + Server string + + // Doer for performing requests, typically a *http.Client with any + // customized settings, such as certificate chains. + Client HttpRequestDoer + + // A list of callbacks for modifying requests which are generated before sending over + // the network. + RequestEditors []RequestEditorFn +} + +// ClientOption allows setting custom parameters during construction +type ClientOption func(*Client) error + +// Creates a new Client, with reasonable defaults +func NewClient(server string, opts ...ClientOption) (*Client, error) { + // create a client with sane default values + client := Client{ + Server: server, + } + // mutate client and add all optional params + for _, o := range opts { + if err := o(&client); err != nil { + return nil, err + } + } + // ensure the server URL always has a trailing slash + if !strings.HasSuffix(client.Server, "/") { + client.Server += "/" + } + // create httpClient, if not already present + if client.Client == nil { + client.Client = &http.Client{} + } + return &client, nil +} + +// WithHTTPClient allows overriding the default Doer, which is +// automatically created using http.Client. This is useful for tests. +func WithHTTPClient(doer HttpRequestDoer) ClientOption { + return func(c *Client) error { + c.Client = doer + return nil + } +} + +// WithRequestEditorFn allows setting up a callback function, which will be +// called right before sending the request. This can be used to mutate the request. +func WithRequestEditorFn(fn RequestEditorFn) ClientOption { + return func(c *Client) error { + c.RequestEditors = append(c.RequestEditors, fn) + return nil + } +} + +// The interface specification for the client above. +type ClientInterface interface { + // GetExplodeArray request + GetExplodeArray(ctx context.Context, param []int32, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetExplodeObject request + GetExplodeObject(ctx context.Context, param Object, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetExplodePrimitive request + GetExplodePrimitive(ctx context.Context, param int32, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetNoExplodeArray request + GetNoExplodeArray(ctx context.Context, param []int32, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetNoExplodeObject request + GetNoExplodeObject(ctx context.Context, param Object, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetNoExplodePrimitive request + GetNoExplodePrimitive(ctx context.Context, param int32, reqEditors ...RequestEditorFn) (*http.Response, error) +} + +func (c *Client) GetExplodeArray(ctx context.Context, param []int32, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetExplodeArrayRequest(c.Server, param) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetExplodeObject(ctx context.Context, param Object, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetExplodeObjectRequest(c.Server, param) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetExplodePrimitive(ctx context.Context, param int32, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetExplodePrimitiveRequest(c.Server, param) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetNoExplodeArray(ctx context.Context, param []int32, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetNoExplodeArrayRequest(c.Server, param) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetNoExplodeObject(ctx context.Context, param Object, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetNoExplodeObjectRequest(c.Server, param) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetNoExplodePrimitive(ctx context.Context, param int32, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetNoExplodePrimitiveRequest(c.Server, param) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +// NewGetExplodeArrayRequest generates requests for GetExplodeArray +func NewGetExplodeArrayRequest(server string, param []int32) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", true, "param", param, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "array", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/explodeArray/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetExplodeObjectRequest generates requests for GetExplodeObject +func NewGetExplodeObjectRequest(server string, param Object) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", true, "param", param, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "object", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/explodeObject/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetExplodePrimitiveRequest generates requests for GetExplodePrimitive +func NewGetExplodePrimitiveRequest(server string, param int32) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", true, "param", param, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "integer", Format: "int32"}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/explodePrimitive/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetNoExplodeArrayRequest generates requests for GetNoExplodeArray +func NewGetNoExplodeArrayRequest(server string, param []int32) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "param", param, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "array", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/noExplodeArray/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetNoExplodeObjectRequest generates requests for GetNoExplodeObject +func NewGetNoExplodeObjectRequest(server string, param Object) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "param", param, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "object", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/noExplodeObject/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetNoExplodePrimitiveRequest generates requests for GetNoExplodePrimitive +func NewGetNoExplodePrimitiveRequest(server string, param int32) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "param", param, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "integer", Format: "int32"}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/noExplodePrimitive/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +func (c *Client) applyEditors(ctx context.Context, req *http.Request, additionalEditors []RequestEditorFn) error { + for _, r := range c.RequestEditors { + if err := r(ctx, req); err != nil { + return err + } + } + for _, r := range additionalEditors { + if err := r(ctx, req); err != nil { + return err + } + } + return nil +} + +// ClientWithResponses builds on ClientInterface to offer response payloads +type ClientWithResponses struct { + ClientInterface +} + +// NewClientWithResponses creates a new ClientWithResponses, which wraps +// Client with return type handling +func NewClientWithResponses(server string, opts ...ClientOption) (*ClientWithResponses, error) { + client, err := NewClient(server, opts...) + if err != nil { + return nil, err + } + return &ClientWithResponses{client}, nil +} + +// WithBaseURL overrides the baseURL. +func WithBaseURL(baseURL string) ClientOption { + return func(c *Client) error { + newBaseURL, err := url.Parse(baseURL) + if err != nil { + return err + } + c.Server = newBaseURL.String() + return nil + } +} + +// ClientWithResponsesInterface is the interface specification for the client with responses above. +type ClientWithResponsesInterface interface { + // GetExplodeArrayWithResponse request + GetExplodeArrayWithResponse(ctx context.Context, param []int32, reqEditors ...RequestEditorFn) (*GetExplodeArrayResponse, error) + + // GetExplodeObjectWithResponse request + GetExplodeObjectWithResponse(ctx context.Context, param Object, reqEditors ...RequestEditorFn) (*GetExplodeObjectResponse, error) + + // GetExplodePrimitiveWithResponse request + GetExplodePrimitiveWithResponse(ctx context.Context, param int32, reqEditors ...RequestEditorFn) (*GetExplodePrimitiveResponse, error) + + // GetNoExplodeArrayWithResponse request + GetNoExplodeArrayWithResponse(ctx context.Context, param []int32, reqEditors ...RequestEditorFn) (*GetNoExplodeArrayResponse, error) + + // GetNoExplodeObjectWithResponse request + GetNoExplodeObjectWithResponse(ctx context.Context, param Object, reqEditors ...RequestEditorFn) (*GetNoExplodeObjectResponse, error) + + // GetNoExplodePrimitiveWithResponse request + GetNoExplodePrimitiveWithResponse(ctx context.Context, param int32, reqEditors ...RequestEditorFn) (*GetNoExplodePrimitiveResponse, error) +} + +type GetExplodeArrayResponse struct { + Body []byte + HTTPResponse *http.Response +} + +// Status returns HTTPResponse.Status +func (r GetExplodeArrayResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetExplodeArrayResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetExplodeObjectResponse struct { + Body []byte + HTTPResponse *http.Response +} + +// Status returns HTTPResponse.Status +func (r GetExplodeObjectResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetExplodeObjectResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetExplodePrimitiveResponse struct { + Body []byte + HTTPResponse *http.Response +} + +// Status returns HTTPResponse.Status +func (r GetExplodePrimitiveResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetExplodePrimitiveResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetNoExplodeArrayResponse struct { + Body []byte + HTTPResponse *http.Response +} + +// Status returns HTTPResponse.Status +func (r GetNoExplodeArrayResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetNoExplodeArrayResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetNoExplodeObjectResponse struct { + Body []byte + HTTPResponse *http.Response +} + +// Status returns HTTPResponse.Status +func (r GetNoExplodeObjectResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetNoExplodeObjectResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetNoExplodePrimitiveResponse struct { + Body []byte + HTTPResponse *http.Response +} + +// Status returns HTTPResponse.Status +func (r GetNoExplodePrimitiveResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetNoExplodePrimitiveResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// GetExplodeArrayWithResponse request returning *GetExplodeArrayResponse +func (c *ClientWithResponses) GetExplodeArrayWithResponse(ctx context.Context, param []int32, reqEditors ...RequestEditorFn) (*GetExplodeArrayResponse, error) { + rsp, err := c.GetExplodeArray(ctx, param, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetExplodeArrayResponse(rsp) +} + +// GetExplodeObjectWithResponse request returning *GetExplodeObjectResponse +func (c *ClientWithResponses) GetExplodeObjectWithResponse(ctx context.Context, param Object, reqEditors ...RequestEditorFn) (*GetExplodeObjectResponse, error) { + rsp, err := c.GetExplodeObject(ctx, param, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetExplodeObjectResponse(rsp) +} + +// GetExplodePrimitiveWithResponse request returning *GetExplodePrimitiveResponse +func (c *ClientWithResponses) GetExplodePrimitiveWithResponse(ctx context.Context, param int32, reqEditors ...RequestEditorFn) (*GetExplodePrimitiveResponse, error) { + rsp, err := c.GetExplodePrimitive(ctx, param, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetExplodePrimitiveResponse(rsp) +} + +// GetNoExplodeArrayWithResponse request returning *GetNoExplodeArrayResponse +func (c *ClientWithResponses) GetNoExplodeArrayWithResponse(ctx context.Context, param []int32, reqEditors ...RequestEditorFn) (*GetNoExplodeArrayResponse, error) { + rsp, err := c.GetNoExplodeArray(ctx, param, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetNoExplodeArrayResponse(rsp) +} + +// GetNoExplodeObjectWithResponse request returning *GetNoExplodeObjectResponse +func (c *ClientWithResponses) GetNoExplodeObjectWithResponse(ctx context.Context, param Object, reqEditors ...RequestEditorFn) (*GetNoExplodeObjectResponse, error) { + rsp, err := c.GetNoExplodeObject(ctx, param, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetNoExplodeObjectResponse(rsp) +} + +// GetNoExplodePrimitiveWithResponse request returning *GetNoExplodePrimitiveResponse +func (c *ClientWithResponses) GetNoExplodePrimitiveWithResponse(ctx context.Context, param int32, reqEditors ...RequestEditorFn) (*GetNoExplodePrimitiveResponse, error) { + rsp, err := c.GetNoExplodePrimitive(ctx, param, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetNoExplodePrimitiveResponse(rsp) +} + +// ParseGetExplodeArrayResponse parses an HTTP response from a GetExplodeArrayWithResponse call +func ParseGetExplodeArrayResponse(rsp *http.Response) (*GetExplodeArrayResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetExplodeArrayResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + return response, nil +} + +// ParseGetExplodeObjectResponse parses an HTTP response from a GetExplodeObjectWithResponse call +func ParseGetExplodeObjectResponse(rsp *http.Response) (*GetExplodeObjectResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetExplodeObjectResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + return response, nil +} + +// ParseGetExplodePrimitiveResponse parses an HTTP response from a GetExplodePrimitiveWithResponse call +func ParseGetExplodePrimitiveResponse(rsp *http.Response) (*GetExplodePrimitiveResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetExplodePrimitiveResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + return response, nil +} + +// ParseGetNoExplodeArrayResponse parses an HTTP response from a GetNoExplodeArrayWithResponse call +func ParseGetNoExplodeArrayResponse(rsp *http.Response) (*GetNoExplodeArrayResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetNoExplodeArrayResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + return response, nil +} + +// ParseGetNoExplodeObjectResponse parses an HTTP response from a GetNoExplodeObjectWithResponse call +func ParseGetNoExplodeObjectResponse(rsp *http.Response) (*GetNoExplodeObjectResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetNoExplodeObjectResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + return response, nil +} + +// ParseGetNoExplodePrimitiveResponse parses an HTTP response from a GetNoExplodePrimitiveWithResponse call +func ParseGetNoExplodePrimitiveResponse(rsp *http.Response) (*GetNoExplodePrimitiveResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetNoExplodePrimitiveResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + return response, nil +} + +// ServerInterface represents all server handlers. +type ServerInterface interface { + + // (GET /explodeArray/{param*}) + GetExplodeArray(ctx echo.Context, param []int32) error + + // (GET /explodeObject/{param*}) + GetExplodeObject(ctx echo.Context, param Object) error + + // (GET /explodePrimitive/{param}) + GetExplodePrimitive(ctx echo.Context, param int32) error + + // (GET /noExplodeArray/{param}) + GetNoExplodeArray(ctx echo.Context, param []int32) error + + // (GET /noExplodeObject/{param}) + GetNoExplodeObject(ctx echo.Context, param Object) error + + // (GET /noExplodePrimitive/{param}) + GetNoExplodePrimitive(ctx echo.Context, param int32) error +} + +// ServerInterfaceWrapper converts echo contexts to parameters. +type ServerInterfaceWrapper struct { + Handler ServerInterface +} + +// GetExplodeArray converts echo context to params. +func (w *ServerInterfaceWrapper) GetExplodeArray(ctx echo.Context) error { + var err error + // ------------- Path parameter "param" ------------- + var param []int32 + + err = runtime.BindStyledParameterWithOptions("simple", "param", ctx.Param("param"), ¶m, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: true, Required: true, Type: "array", Format: ""}) + if err != nil { + return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter param: %s", err)) + } + + // Invoke the callback with all the unmarshaled arguments + err = w.Handler.GetExplodeArray(ctx, param) + return err +} + +// GetExplodeObject converts echo context to params. +func (w *ServerInterfaceWrapper) GetExplodeObject(ctx echo.Context) error { + var err error + // ------------- Path parameter "param" ------------- + var param Object + + err = runtime.BindStyledParameterWithOptions("simple", "param", ctx.Param("param"), ¶m, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: true, Required: true, Type: "object", Format: ""}) + if err != nil { + return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter param: %s", err)) + } + + // Invoke the callback with all the unmarshaled arguments + err = w.Handler.GetExplodeObject(ctx, param) + return err +} + +// GetExplodePrimitive converts echo context to params. +func (w *ServerInterfaceWrapper) GetExplodePrimitive(ctx echo.Context) error { + var err error + // ------------- Path parameter "param" ------------- + var param int32 + + err = runtime.BindStyledParameterWithOptions("simple", "param", ctx.Param("param"), ¶m, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: true, Required: true, Type: "integer", Format: "int32"}) + if err != nil { + return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter param: %s", err)) + } + + // Invoke the callback with all the unmarshaled arguments + err = w.Handler.GetExplodePrimitive(ctx, param) + return err +} + +// GetNoExplodeArray converts echo context to params. +func (w *ServerInterfaceWrapper) GetNoExplodeArray(ctx echo.Context) error { + var err error + // ------------- Path parameter "param" ------------- + var param []int32 + + err = runtime.BindStyledParameterWithOptions("simple", "param", ctx.Param("param"), ¶m, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "array", Format: ""}) + if err != nil { + return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter param: %s", err)) + } + + // Invoke the callback with all the unmarshaled arguments + err = w.Handler.GetNoExplodeArray(ctx, param) + return err +} + +// GetNoExplodeObject converts echo context to params. +func (w *ServerInterfaceWrapper) GetNoExplodeObject(ctx echo.Context) error { + var err error + // ------------- Path parameter "param" ------------- + var param Object + + err = runtime.BindStyledParameterWithOptions("simple", "param", ctx.Param("param"), ¶m, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "object", Format: ""}) + if err != nil { + return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter param: %s", err)) + } + + // Invoke the callback with all the unmarshaled arguments + err = w.Handler.GetNoExplodeObject(ctx, param) + return err +} + +// GetNoExplodePrimitive converts echo context to params. +func (w *ServerInterfaceWrapper) GetNoExplodePrimitive(ctx echo.Context) error { + var err error + // ------------- Path parameter "param" ------------- + var param int32 + + err = runtime.BindStyledParameterWithOptions("simple", "param", ctx.Param("param"), ¶m, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "integer", Format: "int32"}) + if err != nil { + return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter param: %s", err)) + } + + // Invoke the callback with all the unmarshaled arguments + err = w.Handler.GetNoExplodePrimitive(ctx, param) + return err +} + +// This is a simple interface which specifies echo.Route addition functions which +// are present on both echo.Echo and echo.Group, since we want to allow using +// either of them for path registration +type EchoRouter interface { + CONNECT(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route + DELETE(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route + GET(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route + HEAD(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route + OPTIONS(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route + PATCH(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route + POST(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route + PUT(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route + TRACE(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route +} + +// RegisterHandlers adds each server route to the EchoRouter. +func RegisterHandlers(router EchoRouter, si ServerInterface) { + RegisterHandlersWithBaseURL(router, si, "") +} + +// Registers handlers, and prepends BaseURL to the paths, so that the paths +// can be served under a prefix. +func RegisterHandlersWithBaseURL(router EchoRouter, si ServerInterface, baseURL string) { + + wrapper := ServerInterfaceWrapper{ + Handler: si, + } + + router.GET(baseURL+"/explodeArray/:param", wrapper.GetExplodeArray) + router.GET(baseURL+"/explodeObject/:param", wrapper.GetExplodeObject) + router.GET(baseURL+"/explodePrimitive/:param", wrapper.GetExplodePrimitive) + router.GET(baseURL+"/noExplodeArray/:param", wrapper.GetNoExplodeArray) + router.GET(baseURL+"/noExplodeObject/:param", wrapper.GetNoExplodeObject) + router.GET(baseURL+"/noExplodePrimitive/:param", wrapper.GetNoExplodePrimitive) + +} diff --git a/internal/test/parameters/path/simple/path_simple_test.go b/internal/test/parameters/path/simple/path_simple_test.go new file mode 100644 index 0000000000..78f13246cb --- /dev/null +++ b/internal/test/parameters/path/simple/path_simple_test.go @@ -0,0 +1,198 @@ +package pathsimple + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/labstack/echo/v4" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +type testServer struct { + primitive *int32 + array []int32 + object *Object +} + +func (s *testServer) reset() { + s.primitive = nil + s.array = nil + s.object = nil +} + +func (s *testServer) GetNoExplodePrimitive(ctx echo.Context, param int32) error { + s.primitive = ¶m + return nil +} + +func (s *testServer) GetNoExplodeArray(ctx echo.Context, param []int32) error { + s.array = param + return nil +} + +func (s *testServer) GetNoExplodeObject(ctx echo.Context, param Object) error { + s.object = ¶m + return nil +} + +func (s *testServer) GetExplodePrimitive(ctx echo.Context, param int32) error { + s.primitive = ¶m + return nil +} + +func (s *testServer) GetExplodeArray(ctx echo.Context, param []int32) error { + s.array = param + return nil +} + +func (s *testServer) GetExplodeObject(ctx echo.Context, param Object) error { + s.object = ¶m + return nil +} + +func doRequest(t *testing.T, e *echo.Echo, method, path string) *httptest.ResponseRecorder { + t.Helper() + req := httptest.NewRequest(method, path, nil) + rec := httptest.NewRecorder() + e.ServeHTTP(rec, req) + return rec +} + +func setup(t *testing.T) (*testServer, *echo.Echo, string) { + t.Helper() + ts := &testServer{} + e := echo.New() + RegisterHandlers(e, ts) + server := "http://example.com" + return ts, e, server +} + +// TestServerSimplePathParams tests server-side deserialization of simple-style path parameters. +func TestServerSimplePathParams(t *testing.T) { + ts, e, _ := setup(t) + + expectedObject := Object{FirstName: "Alex", Role: "admin"} + expectedArray := []int32{3, 4, 5} + var expectedPrimitive int32 = 5 + + t.Run("noExplode/primitive", func(t *testing.T) { + rec := doRequest(t, e, http.MethodGet, "/noExplodePrimitive/5") + assert.Equal(t, http.StatusOK, rec.Code) + require.NotNil(t, ts.primitive) + assert.EqualValues(t, expectedPrimitive, *ts.primitive) + ts.reset() + }) + + t.Run("noExplode/array", func(t *testing.T) { + rec := doRequest(t, e, http.MethodGet, "/noExplodeArray/3,4,5") + assert.Equal(t, http.StatusOK, rec.Code) + assert.EqualValues(t, expectedArray, ts.array) + ts.reset() + }) + + t.Run("noExplode/object", func(t *testing.T) { + rec := doRequest(t, e, http.MethodGet, "/noExplodeObject/role,admin,firstName,Alex") + assert.Equal(t, http.StatusOK, rec.Code) + require.NotNil(t, ts.object) + assert.EqualValues(t, expectedObject, *ts.object) + ts.reset() + }) + + t.Run("explode/primitive", func(t *testing.T) { + rec := doRequest(t, e, http.MethodGet, "/explodePrimitive/5") + assert.Equal(t, http.StatusOK, rec.Code) + require.NotNil(t, ts.primitive) + assert.EqualValues(t, expectedPrimitive, *ts.primitive) + ts.reset() + }) + + t.Run("explode/array", func(t *testing.T) { + rec := doRequest(t, e, http.MethodGet, "/explodeArray/3,4,5") + assert.Equal(t, http.StatusOK, rec.Code) + assert.EqualValues(t, expectedArray, ts.array) + ts.reset() + }) + + t.Run("explode/object", func(t *testing.T) { + rec := doRequest(t, e, http.MethodGet, "/explodeObject/role=admin,firstName=Alex") + assert.Equal(t, http.StatusOK, rec.Code) + require.NotNil(t, ts.object) + assert.EqualValues(t, expectedObject, *ts.object) + ts.reset() + }) +} + +// TestClientSimplePathParams tests client serialization → server deserialization round-trip. +func TestClientSimplePathParams(t *testing.T) { + ts, e, server := setup(t) + + expectedObject := Object{FirstName: "Alex", Role: "admin"} + expectedArray := []int32{3, 4, 5} + var expectedPrimitive int32 = 5 + + t.Run("noExplode/primitive", func(t *testing.T) { + req, err := NewGetNoExplodePrimitiveRequest(server, expectedPrimitive) + require.NoError(t, err) + rec := httptest.NewRecorder() + e.ServeHTTP(rec, req) + assert.Equal(t, http.StatusOK, rec.Code) + require.NotNil(t, ts.primitive) + assert.EqualValues(t, expectedPrimitive, *ts.primitive) + ts.reset() + }) + + t.Run("noExplode/array", func(t *testing.T) { + req, err := NewGetNoExplodeArrayRequest(server, expectedArray) + require.NoError(t, err) + rec := httptest.NewRecorder() + e.ServeHTTP(rec, req) + assert.Equal(t, http.StatusOK, rec.Code) + assert.EqualValues(t, expectedArray, ts.array) + ts.reset() + }) + + t.Run("noExplode/object", func(t *testing.T) { + req, err := NewGetNoExplodeObjectRequest(server, expectedObject) + require.NoError(t, err) + rec := httptest.NewRecorder() + e.ServeHTTP(rec, req) + assert.Equal(t, http.StatusOK, rec.Code) + require.NotNil(t, ts.object) + assert.EqualValues(t, expectedObject, *ts.object) + ts.reset() + }) + + t.Run("explode/primitive", func(t *testing.T) { + req, err := NewGetExplodePrimitiveRequest(server, expectedPrimitive) + require.NoError(t, err) + rec := httptest.NewRecorder() + e.ServeHTTP(rec, req) + assert.Equal(t, http.StatusOK, rec.Code) + require.NotNil(t, ts.primitive) + assert.EqualValues(t, expectedPrimitive, *ts.primitive) + ts.reset() + }) + + t.Run("explode/array", func(t *testing.T) { + req, err := NewGetExplodeArrayRequest(server, expectedArray) + require.NoError(t, err) + rec := httptest.NewRecorder() + e.ServeHTTP(rec, req) + assert.Equal(t, http.StatusOK, rec.Code) + assert.EqualValues(t, expectedArray, ts.array) + ts.reset() + }) + + t.Run("explode/object", func(t *testing.T) { + req, err := NewGetExplodeObjectRequest(server, expectedObject) + require.NoError(t, err) + rec := httptest.NewRecorder() + e.ServeHTTP(rec, req) + assert.Equal(t, http.StatusOK, rec.Code) + require.NotNil(t, ts.object) + assert.EqualValues(t, expectedObject, *ts.object) + ts.reset() + }) +} diff --git a/internal/test/parameters/path/simple/spec.yaml b/internal/test/parameters/path/simple/spec.yaml new file mode 100644 index 0000000000..3a3292984f --- /dev/null +++ b/internal/test/parameters/path/simple/spec.yaml @@ -0,0 +1,113 @@ +openapi: "3.0.1" +info: + version: 1.0.0 + title: Path Parameters - Simple Style +paths: + # explode: false (default for path) + /noExplodePrimitive/{param}: + get: + operationId: getNoExplodePrimitive + parameters: + - name: param + in: path + required: true + style: simple + explode: false + schema: + type: integer + format: int32 + responses: + "200": + description: OK + /noExplodeArray/{param}: + get: + operationId: getNoExplodeArray + parameters: + - name: param + in: path + required: true + style: simple + explode: false + schema: + type: array + items: + type: integer + format: int32 + responses: + "200": + description: OK + /noExplodeObject/{param}: + get: + operationId: getNoExplodeObject + parameters: + - name: param + in: path + required: true + style: simple + explode: false + schema: + $ref: "#/components/schemas/Object" + responses: + "200": + description: OK + + # explode: true + /explodePrimitive/{param}: + get: + operationId: getExplodePrimitive + parameters: + - name: param + in: path + required: true + style: simple + explode: true + schema: + type: integer + format: int32 + responses: + "200": + description: OK + /explodeArray/{param*}: + get: + operationId: getExplodeArray + parameters: + - name: param + in: path + required: true + style: simple + explode: true + schema: + type: array + items: + type: integer + format: int32 + responses: + "200": + description: OK + /explodeObject/{param*}: + get: + operationId: getExplodeObject + parameters: + - name: param + in: path + required: true + style: simple + explode: true + schema: + $ref: "#/components/schemas/Object" + responses: + "200": + description: OK + +components: + schemas: + Object: + type: object + properties: + role: + type: string + firstName: + type: string + required: + - role + - firstName diff --git a/internal/test/any_of/param/config.yaml b/internal/test/parameters/precedence/config.yaml similarity index 70% rename from internal/test/any_of/param/config.yaml rename to internal/test/parameters/precedence/config.yaml index 1e35ec88ba..6262b8be13 100644 --- a/internal/test/any_of/param/config.yaml +++ b/internal/test/parameters/precedence/config.yaml @@ -1,6 +1,6 @@ # yaml-language-server: $schema=../../../../configuration-schema.json -package: param +package: precedence generate: - models: true client: true -output: param.gen.go + models: true +output: precedence.gen.go diff --git a/internal/test/parameters/precedence/doc.go b/internal/test/parameters/precedence/doc.go new file mode 100644 index 0000000000..8fccd92974 --- /dev/null +++ b/internal/test/parameters/precedence/doc.go @@ -0,0 +1,3 @@ +package precedence + +//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml spec.yaml diff --git a/internal/test/issues/issue-2031/prefer/issue2031.gen.go b/internal/test/parameters/precedence/precedence.gen.go similarity index 70% rename from internal/test/issues/issue-2031/prefer/issue2031.gen.go rename to internal/test/parameters/precedence/precedence.gen.go index 6144c0b4be..289ec3b6e1 100644 --- a/internal/test/issues/issue-2031/prefer/issue2031.gen.go +++ b/internal/test/parameters/precedence/precedence.gen.go @@ -1,7 +1,7 @@ -// Package issue2031 provides primitives to interact with the openapi HTTP API. +// Package precedence provides primitives to interact with the openapi HTTP API. // // Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package issue2031 +package precedence import ( "context" @@ -14,11 +14,6 @@ import ( "github.com/oapi-codegen/runtime" ) -// GetTestParams defines parameters for GetTest. -type GetTestParams struct { - UserIds []int `form:"user_ids[],omitempty" json:"user_ids[],omitempty"` -} - // RequestEditorFn is the function signature for the RequestEditor callback function type RequestEditorFn func(ctx context.Context, req *http.Request) error @@ -92,12 +87,12 @@ func WithRequestEditorFn(fn RequestEditorFn) ClientOption { // The interface specification for the client above. type ClientInterface interface { - // GetTest request - GetTest(ctx context.Context, params *GetTestParams, reqEditors ...RequestEditorFn) (*http.Response, error) + // GetSimplePrimitive request + GetSimplePrimitive(ctx context.Context, param string, reqEditors ...RequestEditorFn) (*http.Response, error) } -func (c *Client) GetTest(ctx context.Context, params *GetTestParams, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewGetTestRequest(c.Server, params) +func (c *Client) GetSimplePrimitive(ctx context.Context, param string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetSimplePrimitiveRequest(c.Server, param) if err != nil { return nil, err } @@ -108,16 +103,23 @@ func (c *Client) GetTest(ctx context.Context, params *GetTestParams, reqEditors return c.Client.Do(req) } -// NewGetTestRequest generates requests for GetTest -func NewGetTestRequest(server string, params *GetTestParams) (*http.Request, error) { +// NewGetSimplePrimitiveRequest generates requests for GetSimplePrimitive +func NewGetSimplePrimitiveRequest(server string, param string) (*http.Request, error) { var err error + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "param", param, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + serverURL, err := url.Parse(server) if err != nil { return nil, err } - operationPath := fmt.Sprintf("/test") + operationPath := fmt.Sprintf("/simplePrimitive/%s", pathParam0) if operationPath[0] == '/' { operationPath = "." + operationPath } @@ -127,28 +129,6 @@ func NewGetTestRequest(server string, params *GetTestParams) (*http.Request, err return nil, err } - if params != nil { - queryValues := queryURL.Query() - - if params.UserIds != nil { - - if queryFrag, err := runtime.StyleParamWithOptions("form", true, "user_ids[]", params.UserIds, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "array", Format: ""}); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { - return nil, err - } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } - } - } - - } - - queryURL.RawQuery = queryValues.Encode() - } - req, err := http.NewRequest("GET", queryURL.String(), nil) if err != nil { return nil, err @@ -200,17 +180,17 @@ func WithBaseURL(baseURL string) ClientOption { // ClientWithResponsesInterface is the interface specification for the client with responses above. type ClientWithResponsesInterface interface { - // GetTestWithResponse request - GetTestWithResponse(ctx context.Context, params *GetTestParams, reqEditors ...RequestEditorFn) (*GetTestResponse, error) + // GetSimplePrimitiveWithResponse request + GetSimplePrimitiveWithResponse(ctx context.Context, param string, reqEditors ...RequestEditorFn) (*GetSimplePrimitiveResponse, error) } -type GetTestResponse struct { +type GetSimplePrimitiveResponse struct { Body []byte HTTPResponse *http.Response } // Status returns HTTPResponse.Status -func (r GetTestResponse) Status() string { +func (r GetSimplePrimitiveResponse) Status() string { if r.HTTPResponse != nil { return r.HTTPResponse.Status } @@ -218,31 +198,31 @@ func (r GetTestResponse) Status() string { } // StatusCode returns HTTPResponse.StatusCode -func (r GetTestResponse) StatusCode() int { +func (r GetSimplePrimitiveResponse) StatusCode() int { if r.HTTPResponse != nil { return r.HTTPResponse.StatusCode } return 0 } -// GetTestWithResponse request returning *GetTestResponse -func (c *ClientWithResponses) GetTestWithResponse(ctx context.Context, params *GetTestParams, reqEditors ...RequestEditorFn) (*GetTestResponse, error) { - rsp, err := c.GetTest(ctx, params, reqEditors...) +// GetSimplePrimitiveWithResponse request returning *GetSimplePrimitiveResponse +func (c *ClientWithResponses) GetSimplePrimitiveWithResponse(ctx context.Context, param string, reqEditors ...RequestEditorFn) (*GetSimplePrimitiveResponse, error) { + rsp, err := c.GetSimplePrimitive(ctx, param, reqEditors...) if err != nil { return nil, err } - return ParseGetTestResponse(rsp) + return ParseGetSimplePrimitiveResponse(rsp) } -// ParseGetTestResponse parses an HTTP response from a GetTestWithResponse call -func ParseGetTestResponse(rsp *http.Response) (*GetTestResponse, error) { +// ParseGetSimplePrimitiveResponse parses an HTTP response from a GetSimplePrimitiveWithResponse call +func ParseGetSimplePrimitiveResponse(rsp *http.Response) (*GetSimplePrimitiveResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &GetTestResponse{ + response := &GetSimplePrimitiveResponse{ Body: bodyBytes, HTTPResponse: rsp, } diff --git a/internal/test/parameters/precedence/precedence_test.go b/internal/test/parameters/precedence/precedence_test.go new file mode 100644 index 0000000000..0c2c027295 --- /dev/null +++ b/internal/test/parameters/precedence/precedence_test.go @@ -0,0 +1,15 @@ +package precedence + +import ( + "testing" +) + +// TestParameterPrecedence validates that the operation-level parameter definition +// takes priority over the path-level parameter with the same name. +// In this spec, the path-level "param" is integer but the operation-level "param" is string. +// The generated client should accept a string, proving the operation-level definition won. +func TestParameterPrecedence(t *testing.T) { + // This compiles only if the generated client uses string (operation-level) + // rather than int32 (path-level) for the param parameter. + _, _ = NewGetSimplePrimitiveRequest("http://example.com/", "test-string") +} diff --git a/internal/test/issues/issue-1180/issue.yaml b/internal/test/parameters/precedence/spec.yaml similarity index 55% rename from internal/test/issues/issue-1180/issue.yaml rename to internal/test/parameters/precedence/spec.yaml index 540996086e..e7bada51b1 100644 --- a/internal/test/issues/issue-1180/issue.yaml +++ b/internal/test/parameters/precedence/spec.yaml @@ -1,11 +1,8 @@ openapi: "3.0.1" info: version: 1.0.0 - title: Test Server - license: - name: MIT -servers: - - url: http://openapitest.deepmap.ai + title: Parameter Precedence + description: Operation-level parameter should override path-level parameter with same name paths: /simplePrimitive/{param}: parameters: @@ -25,15 +22,6 @@ paths: style: simple schema: type: string - format: int32 responses: - '200': - $ref: "#/components/responses/SimpleResponse" -components: - responses: - SimpleResponse: - description: A simple response object - content: - text/plain: - schema: - type: string + "200": + description: OK diff --git a/internal/test/issues/issue-1087/deps/config.yaml b/internal/test/parameters/query/deep_object/config.yaml similarity index 51% rename from internal/test/issues/issue-1087/deps/config.yaml rename to internal/test/parameters/query/deep_object/config.yaml index 95c23f63e0..0c8a3cf42a 100644 --- a/internal/test/issues/issue-1087/deps/config.yaml +++ b/internal/test/parameters/query/deep_object/config.yaml @@ -1,9 +1,7 @@ # yaml-language-server: $schema=../../../../../configuration-schema.json -package: deps -output: - deps.gen.go -output-options: - skip-prune: true +package: querydeepobject generate: + echo-server: true + client: true models: true - embedded-spec: true +output: query_deep_object.gen.go diff --git a/internal/test/parameters/query/deep_object/doc.go b/internal/test/parameters/query/deep_object/doc.go new file mode 100644 index 0000000000..7387e56741 --- /dev/null +++ b/internal/test/parameters/query/deep_object/doc.go @@ -0,0 +1,3 @@ +package querydeepobject + +//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml spec.yaml diff --git a/internal/test/any_of/codegen/inline/openapi.gen.go b/internal/test/parameters/query/deep_object/query_deep_object.gen.go similarity index 61% rename from internal/test/any_of/codegen/inline/openapi.gen.go rename to internal/test/parameters/query/deep_object/query_deep_object.gen.go index d3f34bec6e..d4052dee50 100644 --- a/internal/test/any_of/codegen/inline/openapi.gen.go +++ b/internal/test/parameters/query/deep_object/query_deep_object.gen.go @@ -1,11 +1,10 @@ -// Package inline provides primitives to interact with the openapi HTTP API. +// Package querydeepobject provides primitives to interact with the openapi HTTP API. // // Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package inline +package querydeepobject import ( "context" - "encoding/json" "fmt" "io" "net/http" @@ -13,36 +12,29 @@ import ( "strings" "github.com/labstack/echo/v4" + "github.com/oapi-codegen/runtime" ) -const ( - ApiKeyAuthScopes = "ApiKeyAuth.Scopes" -) - -// Cat This is a cat -type Cat struct { - Breed *string `json:"breed,omitempty"` - Color *string `json:"color,omitempty"` - Id *string `json:"id,omitempty"` - Name *string `json:"name,omitempty"` - Purrs *bool `json:"purrs,omitempty"` +// ComplexObject defines model for ComplexObject. +type ComplexObject struct { + Id int `json:"Id"` + IsAdmin bool `json:"IsAdmin"` + Object Object `json:"Object"` } -// Dog This is a dog -type Dog struct { - Barks *bool `json:"barks,omitempty"` - Breed *string `json:"breed,omitempty"` - Color *string `json:"color,omitempty"` - Id *string `json:"id,omitempty"` - Name *string `json:"name,omitempty"` +// Object defines model for Object. +type Object struct { + FirstName string `json:"firstName"` + Role string `json:"role"` } -// Rat This is a rat -type Rat struct { - Color *string `json:"color,omitempty"` - Id *string `json:"id,omitempty"` - Name *string `json:"name,omitempty"` - Squeaks *bool `json:"squeaks,omitempty"` +// GetDeepObjectParams defines parameters for GetDeepObject. +type GetDeepObjectParams struct { + // Obj deep object + Obj Object `json:"obj"` + + // Complex deep complex object + Complex *ComplexObject `json:"complex,omitempty"` } // RequestEditorFn is the function signature for the RequestEditor callback function @@ -118,12 +110,12 @@ func WithRequestEditorFn(fn RequestEditorFn) ClientOption { // The interface specification for the client above. type ClientInterface interface { - // GetPets request - GetPets(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) + // GetDeepObject request + GetDeepObject(ctx context.Context, params *GetDeepObjectParams, reqEditors ...RequestEditorFn) (*http.Response, error) } -func (c *Client) GetPets(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewGetPetsRequest(c.Server) +func (c *Client) GetDeepObject(ctx context.Context, params *GetDeepObjectParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetDeepObjectRequest(c.Server, params) if err != nil { return nil, err } @@ -134,8 +126,8 @@ func (c *Client) GetPets(ctx context.Context, reqEditors ...RequestEditorFn) (*h return c.Client.Do(req) } -// NewGetPetsRequest generates requests for GetPets -func NewGetPetsRequest(server string) (*http.Request, error) { +// NewGetDeepObjectRequest generates requests for GetDeepObject +func NewGetDeepObjectRequest(server string, params *GetDeepObjectParams) (*http.Request, error) { var err error serverURL, err := url.Parse(server) @@ -143,7 +135,7 @@ func NewGetPetsRequest(server string) (*http.Request, error) { return nil, err } - operationPath := fmt.Sprintf("/pets") + operationPath := fmt.Sprintf("/deepObject") if operationPath[0] == '/' { operationPath = "." + operationPath } @@ -153,6 +145,40 @@ func NewGetPetsRequest(server string) (*http.Request, error) { return nil, err } + if params != nil { + queryValues := queryURL.Query() + + if queryFrag, err := runtime.StyleParamWithOptions("deepObject", true, "obj", params.Obj, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "object", Format: ""}); err != nil { + return nil, err + } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + return nil, err + } else { + for k, v := range parsed { + for _, v2 := range v { + queryValues.Add(k, v2) + } + } + } + + if params.Complex != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("deepObject", true, "complex", *params.Complex, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "object", Format: ""}); err != nil { + return nil, err + } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + return nil, err + } else { + for k, v := range parsed { + for _, v2 := range v { + queryValues.Add(k, v2) + } + } + } + + } + + queryURL.RawQuery = queryValues.Encode() + } + req, err := http.NewRequest("GET", queryURL.String(), nil) if err != nil { return nil, err @@ -204,23 +230,17 @@ func WithBaseURL(baseURL string) ClientOption { // ClientWithResponsesInterface is the interface specification for the client with responses above. type ClientWithResponsesInterface interface { - // GetPetsWithResponse request - GetPetsWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*GetPetsResponse, error) + // GetDeepObjectWithResponse request + GetDeepObjectWithResponse(ctx context.Context, params *GetDeepObjectParams, reqEditors ...RequestEditorFn) (*GetDeepObjectResponse, error) } -type GetPetsResponse struct { +type GetDeepObjectResponse struct { Body []byte HTTPResponse *http.Response - JSON200 *struct { - Data *[]GetPets_200_Data_Item `json:"data,omitempty"` - } -} -type GetPets_200_Data_Item struct { - union json.RawMessage } // Status returns HTTPResponse.Status -func (r GetPetsResponse) Status() string { +func (r GetDeepObjectResponse) Status() string { if r.HTTPResponse != nil { return r.HTTPResponse.Status } @@ -228,55 +248,43 @@ func (r GetPetsResponse) Status() string { } // StatusCode returns HTTPResponse.StatusCode -func (r GetPetsResponse) StatusCode() int { +func (r GetDeepObjectResponse) StatusCode() int { if r.HTTPResponse != nil { return r.HTTPResponse.StatusCode } return 0 } -// GetPetsWithResponse request returning *GetPetsResponse -func (c *ClientWithResponses) GetPetsWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*GetPetsResponse, error) { - rsp, err := c.GetPets(ctx, reqEditors...) +// GetDeepObjectWithResponse request returning *GetDeepObjectResponse +func (c *ClientWithResponses) GetDeepObjectWithResponse(ctx context.Context, params *GetDeepObjectParams, reqEditors ...RequestEditorFn) (*GetDeepObjectResponse, error) { + rsp, err := c.GetDeepObject(ctx, params, reqEditors...) if err != nil { return nil, err } - return ParseGetPetsResponse(rsp) + return ParseGetDeepObjectResponse(rsp) } -// ParseGetPetsResponse parses an HTTP response from a GetPetsWithResponse call -func ParseGetPetsResponse(rsp *http.Response) (*GetPetsResponse, error) { +// ParseGetDeepObjectResponse parses an HTTP response from a GetDeepObjectWithResponse call +func ParseGetDeepObjectResponse(rsp *http.Response) (*GetDeepObjectResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &GetPetsResponse{ + response := &GetDeepObjectResponse{ Body: bodyBytes, HTTPResponse: rsp, } - switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest struct { - Data *[]GetPets_200_Data_Item `json:"data,omitempty"` - } - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON200 = &dest - - } - return response, nil } // ServerInterface represents all server handlers. type ServerInterface interface { - // Get a list of pets - // (GET /pets) - GetPets(ctx echo.Context) error + + // (GET /deepObject) + GetDeepObject(ctx echo.Context, params GetDeepObjectParams) error } // ServerInterfaceWrapper converts echo contexts to parameters. @@ -284,14 +292,28 @@ type ServerInterfaceWrapper struct { Handler ServerInterface } -// GetPets converts echo context to params. -func (w *ServerInterfaceWrapper) GetPets(ctx echo.Context) error { +// GetDeepObject converts echo context to params. +func (w *ServerInterfaceWrapper) GetDeepObject(ctx echo.Context) error { var err error - ctx.Set(ApiKeyAuthScopes, []string{}) + // Parameter object where we will unmarshal all parameters from the context + var params GetDeepObjectParams + // ------------- Required query parameter "obj" ------------- + + err = runtime.BindQueryParameterWithOptions("deepObject", true, true, "obj", ctx.QueryParams(), ¶ms.Obj, runtime.BindQueryParameterOptions{Type: "object", Format: ""}) + if err != nil { + return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter obj: %s", err)) + } + + // ------------- Optional query parameter "complex" ------------- + + err = runtime.BindQueryParameterWithOptions("deepObject", true, false, "complex", ctx.QueryParams(), ¶ms.Complex, runtime.BindQueryParameterOptions{Type: "object", Format: ""}) + if err != nil { + return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter complex: %s", err)) + } // Invoke the callback with all the unmarshaled arguments - err = w.Handler.GetPets(ctx) + err = w.Handler.GetDeepObject(ctx, params) return err } @@ -323,6 +345,6 @@ func RegisterHandlersWithBaseURL(router EchoRouter, si ServerInterface, baseURL Handler: si, } - router.GET(baseURL+"/pets", wrapper.GetPets) + router.GET(baseURL+"/deepObject", wrapper.GetDeepObject) } diff --git a/internal/test/parameters/query/deep_object/query_deep_object_test.go b/internal/test/parameters/query/deep_object/query_deep_object_test.go new file mode 100644 index 0000000000..95a1dddbe5 --- /dev/null +++ b/internal/test/parameters/query/deep_object/query_deep_object_test.go @@ -0,0 +1,100 @@ +package querydeepobject + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/labstack/echo/v4" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +type testServer struct { + object *Object + complexObject *ComplexObject +} + +func (s *testServer) reset() { + s.object = nil + s.complexObject = nil +} + +func (s *testServer) GetDeepObject(ctx echo.Context, params GetDeepObjectParams) error { + s.object = ¶ms.Obj + if params.Complex != nil { + s.complexObject = params.Complex + } + return nil +} + +func setup(t *testing.T) (*testServer, *echo.Echo, string) { + t.Helper() + ts := &testServer{} + e := echo.New() + RegisterHandlers(e, ts) + return ts, e, "http://example.com" +} + +func TestServerDeepObjectParams(t *testing.T) { + ts, e, _ := setup(t) + + expectedObject := Object{FirstName: "Alex", Role: "admin"} + expectedComplex := ComplexObject{ + Object: expectedObject, + Id: 12345, + IsAdmin: true, + } + + t.Run("simple_object", func(t *testing.T) { + req := httptest.NewRequest(http.MethodGet, + "/deepObject?obj[role]=admin&obj[firstName]=Alex", nil) + rec := httptest.NewRecorder() + e.ServeHTTP(rec, req) + assert.Equal(t, http.StatusOK, rec.Code) + require.NotNil(t, ts.object) + assert.EqualValues(t, expectedObject, *ts.object) + ts.reset() + }) + + t.Run("complex_nested_object", func(t *testing.T) { + req := httptest.NewRequest(http.MethodGet, + "/deepObject?obj[role]=admin&obj[firstName]=Alex&complex[Id]=12345&complex[IsAdmin]=true&complex[Object][role]=admin&complex[Object][firstName]=Alex", nil) + rec := httptest.NewRecorder() + e.ServeHTTP(rec, req) + assert.Equal(t, http.StatusOK, rec.Code) + require.NotNil(t, ts.object) + assert.EqualValues(t, expectedObject, *ts.object) + require.NotNil(t, ts.complexObject) + assert.EqualValues(t, expectedComplex, *ts.complexObject) + ts.reset() + }) +} + +func TestClientDeepObjectParams(t *testing.T) { + ts, e, server := setup(t) + + expectedObject := Object{FirstName: "Alex", Role: "admin"} + expectedComplex := ComplexObject{ + Object: expectedObject, + Id: 12345, + IsAdmin: true, + } + + t.Run("simple_and_complex", func(t *testing.T) { + params := GetDeepObjectParams{ + Obj: expectedObject, + Complex: &expectedComplex, + } + req, err := NewGetDeepObjectRequest(server, ¶ms) + require.NoError(t, err) + rec := httptest.NewRecorder() + e.ServeHTTP(rec, req) + assert.Equal(t, http.StatusOK, rec.Code) + require.NotNil(t, ts.object) + assert.EqualValues(t, expectedObject, *ts.object) + require.NotNil(t, ts.complexObject) + assert.EqualValues(t, expectedComplex, *ts.complexObject) + ts.reset() + }) +} diff --git a/internal/test/parameters/query/deep_object/spec.yaml b/internal/test/parameters/query/deep_object/spec.yaml new file mode 100644 index 0000000000..7c8e20ef26 --- /dev/null +++ b/internal/test/parameters/query/deep_object/spec.yaml @@ -0,0 +1,53 @@ +openapi: "3.0.1" +info: + version: 1.0.0 + title: Query Parameters - DeepObject Style +paths: + /deepObject: + get: + operationId: getDeepObject + parameters: + - name: obj + description: deep object + in: query + required: true + style: deepObject + explode: true + schema: + $ref: "#/components/schemas/Object" + - name: complex + description: deep complex object + in: query + required: false + style: deepObject + explode: true + schema: + $ref: "#/components/schemas/ComplexObject" + responses: + "200": + description: OK +components: + schemas: + Object: + type: object + properties: + role: + type: string + firstName: + type: string + required: + - role + - firstName + ComplexObject: + type: object + properties: + Object: + $ref: "#/components/schemas/Object" + Id: + type: integer + IsAdmin: + type: boolean + required: + - Object + - Id + - IsAdmin diff --git a/internal/test/parameters/query/form/config.yaml b/internal/test/parameters/query/form/config.yaml new file mode 100644 index 0000000000..f44e745ae1 --- /dev/null +++ b/internal/test/parameters/query/form/config.yaml @@ -0,0 +1,7 @@ +# yaml-language-server: $schema=../../../../../configuration-schema.json +package: queryform +generate: + echo-server: true + client: true + models: true +output: query_form.gen.go diff --git a/internal/test/parameters/query/form/doc.go b/internal/test/parameters/query/form/doc.go new file mode 100644 index 0000000000..1c7c190e46 --- /dev/null +++ b/internal/test/parameters/query/form/doc.go @@ -0,0 +1,3 @@ +package queryform + +//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml spec.yaml diff --git a/internal/test/parameters/query/form/query_form.gen.go b/internal/test/parameters/query/form/query_form.gen.go new file mode 100644 index 0000000000..11a7c4fe5a --- /dev/null +++ b/internal/test/parameters/query/form/query_form.gen.go @@ -0,0 +1,451 @@ +// Package queryform provides primitives to interact with the openapi HTTP API. +// +// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. +package queryform + +import ( + "context" + "fmt" + "io" + "net/http" + "net/url" + "strings" + + "github.com/labstack/echo/v4" + "github.com/oapi-codegen/runtime" +) + +// Object defines model for Object. +type Object struct { + FirstName string `json:"firstName"` + Role string `json:"role"` +} + +// GetQueryFormParams defines parameters for GetQueryForm. +type GetQueryFormParams struct { + // P unexploded primitive + P *int32 `form:"p,omitempty" json:"p,omitempty"` + + // Ep exploded primitive + Ep *int32 `form:"ep,omitempty" json:"ep,omitempty"` + + // A unexploded array + A *[]int32 `form:"a,omitempty" json:"a,omitempty"` + + // Ea exploded array + Ea *[]int32 `form:"ea,omitempty" json:"ea,omitempty"` + + // O unexploded object + O *Object `form:"o,omitempty" json:"o,omitempty"` + + // Eo exploded object + Eo *Object `form:"eo,omitempty" json:"eo,omitempty"` +} + +// RequestEditorFn is the function signature for the RequestEditor callback function +type RequestEditorFn func(ctx context.Context, req *http.Request) error + +// Doer performs HTTP requests. +// +// The standard http.Client implements this interface. +type HttpRequestDoer interface { + Do(req *http.Request) (*http.Response, error) +} + +// Client which conforms to the OpenAPI3 specification for this service. +type Client struct { + // The endpoint of the server conforming to this interface, with scheme, + // https://api.deepmap.com for example. This can contain a path relative + // to the server, such as https://api.deepmap.com/dev-test, and all the + // paths in the swagger spec will be appended to the server. + Server string + + // Doer for performing requests, typically a *http.Client with any + // customized settings, such as certificate chains. + Client HttpRequestDoer + + // A list of callbacks for modifying requests which are generated before sending over + // the network. + RequestEditors []RequestEditorFn +} + +// ClientOption allows setting custom parameters during construction +type ClientOption func(*Client) error + +// Creates a new Client, with reasonable defaults +func NewClient(server string, opts ...ClientOption) (*Client, error) { + // create a client with sane default values + client := Client{ + Server: server, + } + // mutate client and add all optional params + for _, o := range opts { + if err := o(&client); err != nil { + return nil, err + } + } + // ensure the server URL always has a trailing slash + if !strings.HasSuffix(client.Server, "/") { + client.Server += "/" + } + // create httpClient, if not already present + if client.Client == nil { + client.Client = &http.Client{} + } + return &client, nil +} + +// WithHTTPClient allows overriding the default Doer, which is +// automatically created using http.Client. This is useful for tests. +func WithHTTPClient(doer HttpRequestDoer) ClientOption { + return func(c *Client) error { + c.Client = doer + return nil + } +} + +// WithRequestEditorFn allows setting up a callback function, which will be +// called right before sending the request. This can be used to mutate the request. +func WithRequestEditorFn(fn RequestEditorFn) ClientOption { + return func(c *Client) error { + c.RequestEditors = append(c.RequestEditors, fn) + return nil + } +} + +// The interface specification for the client above. +type ClientInterface interface { + // GetQueryForm request + GetQueryForm(ctx context.Context, params *GetQueryFormParams, reqEditors ...RequestEditorFn) (*http.Response, error) +} + +func (c *Client) GetQueryForm(ctx context.Context, params *GetQueryFormParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetQueryFormRequest(c.Server, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +// NewGetQueryFormRequest generates requests for GetQueryForm +func NewGetQueryFormRequest(server string, params *GetQueryFormParams) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/queryForm") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + queryValues := queryURL.Query() + + if params.P != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "p", *params.P, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: "int32"}); err != nil { + return nil, err + } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + return nil, err + } else { + for k, v := range parsed { + for _, v2 := range v { + queryValues.Add(k, v2) + } + } + } + + } + + if params.Ep != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "ep", *params.Ep, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: "int32"}); err != nil { + return nil, err + } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + return nil, err + } else { + for k, v := range parsed { + for _, v2 := range v { + queryValues.Add(k, v2) + } + } + } + + } + + if params.A != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "a", *params.A, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "array", Format: ""}); err != nil { + return nil, err + } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + return nil, err + } else { + for k, v := range parsed { + for _, v2 := range v { + queryValues.Add(k, v2) + } + } + } + + } + + if params.Ea != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "ea", *params.Ea, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "array", Format: ""}); err != nil { + return nil, err + } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + return nil, err + } else { + for k, v := range parsed { + for _, v2 := range v { + queryValues.Add(k, v2) + } + } + } + + } + + if params.O != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "o", *params.O, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "object", Format: ""}); err != nil { + return nil, err + } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + return nil, err + } else { + for k, v := range parsed { + for _, v2 := range v { + queryValues.Add(k, v2) + } + } + } + + } + + if params.Eo != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "eo", *params.Eo, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "object", Format: ""}); err != nil { + return nil, err + } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + return nil, err + } else { + for k, v := range parsed { + for _, v2 := range v { + queryValues.Add(k, v2) + } + } + } + + } + + queryURL.RawQuery = queryValues.Encode() + } + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +func (c *Client) applyEditors(ctx context.Context, req *http.Request, additionalEditors []RequestEditorFn) error { + for _, r := range c.RequestEditors { + if err := r(ctx, req); err != nil { + return err + } + } + for _, r := range additionalEditors { + if err := r(ctx, req); err != nil { + return err + } + } + return nil +} + +// ClientWithResponses builds on ClientInterface to offer response payloads +type ClientWithResponses struct { + ClientInterface +} + +// NewClientWithResponses creates a new ClientWithResponses, which wraps +// Client with return type handling +func NewClientWithResponses(server string, opts ...ClientOption) (*ClientWithResponses, error) { + client, err := NewClient(server, opts...) + if err != nil { + return nil, err + } + return &ClientWithResponses{client}, nil +} + +// WithBaseURL overrides the baseURL. +func WithBaseURL(baseURL string) ClientOption { + return func(c *Client) error { + newBaseURL, err := url.Parse(baseURL) + if err != nil { + return err + } + c.Server = newBaseURL.String() + return nil + } +} + +// ClientWithResponsesInterface is the interface specification for the client with responses above. +type ClientWithResponsesInterface interface { + // GetQueryFormWithResponse request + GetQueryFormWithResponse(ctx context.Context, params *GetQueryFormParams, reqEditors ...RequestEditorFn) (*GetQueryFormResponse, error) +} + +type GetQueryFormResponse struct { + Body []byte + HTTPResponse *http.Response +} + +// Status returns HTTPResponse.Status +func (r GetQueryFormResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetQueryFormResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// GetQueryFormWithResponse request returning *GetQueryFormResponse +func (c *ClientWithResponses) GetQueryFormWithResponse(ctx context.Context, params *GetQueryFormParams, reqEditors ...RequestEditorFn) (*GetQueryFormResponse, error) { + rsp, err := c.GetQueryForm(ctx, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetQueryFormResponse(rsp) +} + +// ParseGetQueryFormResponse parses an HTTP response from a GetQueryFormWithResponse call +func ParseGetQueryFormResponse(rsp *http.Response) (*GetQueryFormResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetQueryFormResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + return response, nil +} + +// ServerInterface represents all server handlers. +type ServerInterface interface { + + // (GET /queryForm) + GetQueryForm(ctx echo.Context, params GetQueryFormParams) error +} + +// ServerInterfaceWrapper converts echo contexts to parameters. +type ServerInterfaceWrapper struct { + Handler ServerInterface +} + +// GetQueryForm converts echo context to params. +func (w *ServerInterfaceWrapper) GetQueryForm(ctx echo.Context) error { + var err error + + // Parameter object where we will unmarshal all parameters from the context + var params GetQueryFormParams + // ------------- Optional query parameter "p" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "p", ctx.QueryParams(), ¶ms.P, runtime.BindQueryParameterOptions{Type: "integer", Format: "int32"}) + if err != nil { + return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter p: %s", err)) + } + + // ------------- Optional query parameter "ep" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "ep", ctx.QueryParams(), ¶ms.Ep, runtime.BindQueryParameterOptions{Type: "integer", Format: "int32"}) + if err != nil { + return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter ep: %s", err)) + } + + // ------------- Optional query parameter "a" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "a", ctx.QueryParams(), ¶ms.A, runtime.BindQueryParameterOptions{Type: "array", Format: ""}) + if err != nil { + return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter a: %s", err)) + } + + // ------------- Optional query parameter "ea" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "ea", ctx.QueryParams(), ¶ms.Ea, runtime.BindQueryParameterOptions{Type: "array", Format: ""}) + if err != nil { + return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter ea: %s", err)) + } + + // ------------- Optional query parameter "o" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "o", ctx.QueryParams(), ¶ms.O, runtime.BindQueryParameterOptions{Type: "object", Format: ""}) + if err != nil { + return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter o: %s", err)) + } + + // ------------- Optional query parameter "eo" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "eo", ctx.QueryParams(), ¶ms.Eo, runtime.BindQueryParameterOptions{Type: "object", Format: ""}) + if err != nil { + return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter eo: %s", err)) + } + + // Invoke the callback with all the unmarshaled arguments + err = w.Handler.GetQueryForm(ctx, params) + return err +} + +// This is a simple interface which specifies echo.Route addition functions which +// are present on both echo.Echo and echo.Group, since we want to allow using +// either of them for path registration +type EchoRouter interface { + CONNECT(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route + DELETE(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route + GET(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route + HEAD(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route + OPTIONS(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route + PATCH(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route + POST(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route + PUT(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route + TRACE(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route +} + +// RegisterHandlers adds each server route to the EchoRouter. +func RegisterHandlers(router EchoRouter, si ServerInterface) { + RegisterHandlersWithBaseURL(router, si, "") +} + +// Registers handlers, and prepends BaseURL to the paths, so that the paths +// can be served under a prefix. +func RegisterHandlersWithBaseURL(router EchoRouter, si ServerInterface, baseURL string) { + + wrapper := ServerInterfaceWrapper{ + Handler: si, + } + + router.GET(baseURL+"/queryForm", wrapper.GetQueryForm) + +} diff --git a/internal/test/parameters/query/form/query_form_test.go b/internal/test/parameters/query/form/query_form_test.go new file mode 100644 index 0000000000..465d691359 --- /dev/null +++ b/internal/test/parameters/query/form/query_form_test.go @@ -0,0 +1,143 @@ +package queryform + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/labstack/echo/v4" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +type testServer struct { + params GetQueryFormParams +} + +func (s *testServer) reset() { + s.params = GetQueryFormParams{} +} + +func (s *testServer) GetQueryForm(ctx echo.Context, params GetQueryFormParams) error { + s.params = params + return nil +} + +func doRequest(t *testing.T, e *echo.Echo, method, path string) *httptest.ResponseRecorder { + t.Helper() + req := httptest.NewRequest(method, path, nil) + rec := httptest.NewRecorder() + e.ServeHTTP(rec, req) + return rec +} + +func setup(t *testing.T) (*testServer, *echo.Echo, string) { + t.Helper() + ts := &testServer{} + e := echo.New() + RegisterHandlers(e, ts) + server := "http://example.com" + return ts, e, server +} + +// TestServerQueryFormParams tests server-side deserialization of form-style query parameters. +func TestServerQueryFormParams(t *testing.T) { + ts, e, _ := setup(t) + + t.Run("unexploded/primitive", func(t *testing.T) { + rec := doRequest(t, e, http.MethodGet, "/queryForm?p=5") + assert.Equal(t, http.StatusOK, rec.Code) + require.NotNil(t, ts.params.P) + assert.EqualValues(t, int32(5), *ts.params.P) + ts.reset() + }) + + t.Run("exploded/primitive", func(t *testing.T) { + rec := doRequest(t, e, http.MethodGet, "/queryForm?ep=5") + assert.Equal(t, http.StatusOK, rec.Code) + require.NotNil(t, ts.params.Ep) + assert.EqualValues(t, int32(5), *ts.params.Ep) + ts.reset() + }) + + t.Run("unexploded/array", func(t *testing.T) { + rec := doRequest(t, e, http.MethodGet, "/queryForm?a=3,4,5") + assert.Equal(t, http.StatusOK, rec.Code) + require.NotNil(t, ts.params.A) + assert.EqualValues(t, []int32{3, 4, 5}, *ts.params.A) + ts.reset() + }) + + t.Run("exploded/array", func(t *testing.T) { + rec := doRequest(t, e, http.MethodGet, "/queryForm?ea=3&ea=4&ea=5") + assert.Equal(t, http.StatusOK, rec.Code) + require.NotNil(t, ts.params.Ea) + assert.EqualValues(t, []int32{3, 4, 5}, *ts.params.Ea) + ts.reset() + }) + + t.Run("unexploded/object", func(t *testing.T) { + rec := doRequest(t, e, http.MethodGet, "/queryForm?o=role,admin,firstName,Alex") + assert.Equal(t, http.StatusOK, rec.Code) + require.NotNil(t, ts.params.O) + assert.EqualValues(t, Object{FirstName: "Alex", Role: "admin"}, *ts.params.O) + ts.reset() + }) + + t.Run("exploded/object", func(t *testing.T) { + rec := doRequest(t, e, http.MethodGet, "/queryForm?role=admin&firstName=Alex") + assert.Equal(t, http.StatusOK, rec.Code) + require.NotNil(t, ts.params.Eo) + assert.EqualValues(t, Object{FirstName: "Alex", Role: "admin"}, *ts.params.Eo) + ts.reset() + }) +} + +// TestClientQueryFormParams tests client serialization to server deserialization round-trip. +func TestClientQueryFormParams(t *testing.T) { + ts, e, server := setup(t) + + var p int32 = 5 + var ep int32 = 5 + a := []int32{3, 4, 5} + ea := []int32{3, 4, 5} + o := Object{FirstName: "Alex", Role: "admin"} + eo := Object{FirstName: "Alex", Role: "admin"} + + params := &GetQueryFormParams{ + P: &p, + Ep: &ep, + A: &a, + Ea: &ea, + O: &o, + Eo: &eo, + } + + t.Run("round-trip/all", func(t *testing.T) { + req, err := NewGetQueryFormRequest(server, params) + require.NoError(t, err) + rec := httptest.NewRecorder() + e.ServeHTTP(rec, req) + assert.Equal(t, http.StatusOK, rec.Code) + + require.NotNil(t, ts.params.P) + assert.EqualValues(t, p, *ts.params.P) + + require.NotNil(t, ts.params.Ep) + assert.EqualValues(t, ep, *ts.params.Ep) + + require.NotNil(t, ts.params.A) + assert.EqualValues(t, a, *ts.params.A) + + require.NotNil(t, ts.params.Ea) + assert.EqualValues(t, ea, *ts.params.Ea) + + require.NotNil(t, ts.params.O) + assert.EqualValues(t, o, *ts.params.O) + + require.NotNil(t, ts.params.Eo) + assert.EqualValues(t, eo, *ts.params.Eo) + + ts.reset() + }) +} diff --git a/internal/test/parameters/query/form/spec.yaml b/internal/test/parameters/query/form/spec.yaml new file mode 100644 index 0000000000..7a51a08f4b --- /dev/null +++ b/internal/test/parameters/query/form/spec.yaml @@ -0,0 +1,80 @@ +openapi: "3.0.1" +info: + version: 1.0.0 + title: Query Parameters - Form Style +paths: + /queryForm: + get: + operationId: getQueryForm + parameters: + - name: p + description: unexploded primitive + in: query + required: false + style: form + explode: false + schema: + type: integer + format: int32 + - name: ep + description: exploded primitive + in: query + required: false + style: form + explode: true + schema: + type: integer + format: int32 + - name: a + description: unexploded array + in: query + required: false + style: form + explode: false + schema: + type: array + items: + type: integer + format: int32 + - name: ea + description: exploded array + in: query + required: false + style: form + explode: true + schema: + type: array + items: + type: integer + format: int32 + - name: o + description: unexploded object + in: query + required: false + style: form + explode: false + schema: + $ref: "#/components/schemas/Object" + - name: eo + description: exploded object + in: query + required: false + style: form + explode: true + schema: + $ref: "#/components/schemas/Object" + responses: + "200": + description: OK +components: + schemas: + Object: + type: object + properties: + role: + type: string + firstName: + type: string + required: + - role + - firstName diff --git a/internal/test/schemas/config.yaml b/internal/test/schemas/config.yaml deleted file mode 100644 index a054e8daf8..0000000000 --- a/internal/test/schemas/config.yaml +++ /dev/null @@ -1,10 +0,0 @@ -# yaml-language-server: $schema=../../../configuration-schema.json -package: schemas -generate: - echo-server: true - client: true - models: true - embedded-spec: true -output: schemas.gen.go -output-options: - skip-prune: true diff --git a/internal/test/schemas/doc.go b/internal/test/schemas/doc.go deleted file mode 100644 index a4147ee5af..0000000000 --- a/internal/test/schemas/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -package schemas - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml schemas.yaml diff --git a/internal/test/schemas/schemas.gen.go b/internal/test/schemas/schemas.gen.go deleted file mode 100644 index 9c0871cb34..0000000000 --- a/internal/test/schemas/schemas.gen.go +++ /dev/null @@ -1,1699 +0,0 @@ -// Package schemas provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package schemas - -import ( - "bytes" - "compress/gzip" - "context" - "encoding/base64" - "encoding/json" - "encoding/xml" - "fmt" - "io" - "net/http" - "net/url" - "path" - "strings" - - "gopkg.in/yaml.v2" - - "github.com/getkin/kin-openapi/openapi3" - "github.com/labstack/echo/v4" - "github.com/oapi-codegen/runtime" -) - -const ( - Access_tokenScopes = "access_token.Scopes" -) - -// Defines values for EnumInObjInArrayVal. -const ( - First EnumInObjInArrayVal = "first" - Second EnumInObjInArrayVal = "second" -) - -// Valid indicates whether the value is a known member of the EnumInObjInArrayVal enum. -func (e EnumInObjInArrayVal) Valid() bool { - switch e { - case First: - return true - case Second: - return true - default: - return false - } -} - -// N5StartsWithNumber This schema name starts with a number -type N5StartsWithNumber = map[string]interface{} - -// AnyType1 defines model for AnyType1. -type AnyType1 = interface{} - -// AnyType2 AnyType2 represents any type. -// -// This should be an interface{} -type AnyType2 = interface{} - -// CustomStringType defines model for CustomStringType. -type CustomStringType = string - -// DeprecatedProperty defines model for DeprecatedProperty. -type DeprecatedProperty struct { - // NewProp Use this now! - NewProp string `json:"newProp"` - // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set - OldProp1 *string `json:"oldProp1,omitempty"` - - // OldProp2 It used to do this and that - // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set - OldProp2 *string `json:"oldProp2,omitempty"` - // Deprecated: Use NewProp instead! - OldProp3 *string `json:"oldProp3,omitempty"` - - // OldProp4 It used to do this and that - // Deprecated: Use NewProp instead! - OldProp4 *string `json:"oldProp4,omitempty"` -} - -// EnumInObjInArray defines model for EnumInObjInArray. -type EnumInObjInArray = []struct { - Val *EnumInObjInArrayVal `json:"val,omitempty"` -} - -// EnumInObjInArrayVal defines model for EnumInObjInArray.Val. -type EnumInObjInArrayVal string - -// GenericObject defines model for GenericObject. -type GenericObject = map[string]interface{} - -// NullableProperties defines model for NullableProperties. -type NullableProperties struct { - Optional *string `json:"optional,omitempty"` - OptionalAndNullable *string `json:"optionalAndNullable,omitempty"` - Required string `json:"required"` - RequiredAndNullable *string `json:"requiredAndNullable"` -} - -// OuterTypeWithAnonymousInner defines model for OuterTypeWithAnonymousInner. -type OuterTypeWithAnonymousInner struct { - Inner InnerRenamedAnonymousObject `json:"inner"` - Name string `json:"name"` -} - -// InnerRenamedAnonymousObject defines model for . -type InnerRenamedAnonymousObject struct { - Id int `json:"id"` -} - -// StringInPath defines model for StringInPath. -type StringInPath = string - -// Issue9JSONBody defines parameters for Issue9. -type Issue9JSONBody = interface{} - -// Issue9Params defines parameters for Issue9. -type Issue9Params struct { - Foo string `form:"foo" json:"foo"` -} - -// Issue185JSONRequestBody defines body for Issue185 for application/json ContentType. -type Issue185JSONRequestBody = NullableProperties - -// Issue9JSONRequestBody defines body for Issue9 for application/json ContentType. -type Issue9JSONRequestBody = Issue9JSONBody - -// RequestEditorFn is the function signature for the RequestEditor callback function -type RequestEditorFn func(ctx context.Context, req *http.Request) error - -// Doer performs HTTP requests. -// -// The standard http.Client implements this interface. -type HttpRequestDoer interface { - Do(req *http.Request) (*http.Response, error) -} - -// Client which conforms to the OpenAPI3 specification for this service. -type Client struct { - // The endpoint of the server conforming to this interface, with scheme, - // https://api.deepmap.com for example. This can contain a path relative - // to the server, such as https://api.deepmap.com/dev-test, and all the - // paths in the swagger spec will be appended to the server. - Server string - - // Doer for performing requests, typically a *http.Client with any - // customized settings, such as certificate chains. - Client HttpRequestDoer - - // A list of callbacks for modifying requests which are generated before sending over - // the network. - RequestEditors []RequestEditorFn -} - -// ClientOption allows setting custom parameters during construction -type ClientOption func(*Client) error - -// Creates a new Client, with reasonable defaults -func NewClient(server string, opts ...ClientOption) (*Client, error) { - // create a client with sane default values - client := Client{ - Server: server, - } - // mutate client and add all optional params - for _, o := range opts { - if err := o(&client); err != nil { - return nil, err - } - } - // ensure the server URL always has a trailing slash - if !strings.HasSuffix(client.Server, "/") { - client.Server += "/" - } - // create httpClient, if not already present - if client.Client == nil { - client.Client = &http.Client{} - } - return &client, nil -} - -// WithHTTPClient allows overriding the default Doer, which is -// automatically created using http.Client. This is useful for tests. -func WithHTTPClient(doer HttpRequestDoer) ClientOption { - return func(c *Client) error { - c.Client = doer - return nil - } -} - -// WithRequestEditorFn allows setting up a callback function, which will be -// called right before sending the request. This can be used to mutate the request. -func WithRequestEditorFn(fn RequestEditorFn) ClientOption { - return func(c *Client) error { - c.RequestEditors = append(c.RequestEditors, fn) - return nil - } -} - -// The interface specification for the client above. -type ClientInterface interface { - // EnsureEverythingIsReferenced request - EnsureEverythingIsReferenced(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) - - // Issue1051 request - Issue1051(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) - - // Issue127 request - Issue127(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) - - // Issue185WithBody request with any body - Issue185WithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) - - Issue185(ctx context.Context, body Issue185JSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) - - // Issue209 request - Issue209(ctx context.Context, str StringInPath, reqEditors ...RequestEditorFn) (*http.Response, error) - - // Issue30 request - Issue30(ctx context.Context, pFallthrough string, reqEditors ...RequestEditorFn) (*http.Response, error) - - // GetIssues375 request - GetIssues375(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) - - // Issue41 request - Issue41(ctx context.Context, n1param N5StartsWithNumber, reqEditors ...RequestEditorFn) (*http.Response, error) - - // Issue9WithBody request with any body - Issue9WithBody(ctx context.Context, params *Issue9Params, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) - - Issue9(ctx context.Context, params *Issue9Params, body Issue9JSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) - - // Issue975 request - Issue975(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) -} - -func (c *Client) EnsureEverythingIsReferenced(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewEnsureEverythingIsReferencedRequest(c.Server) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) Issue1051(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewIssue1051Request(c.Server) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) Issue127(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewIssue127Request(c.Server) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) Issue185WithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewIssue185RequestWithBody(c.Server, contentType, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) Issue185(ctx context.Context, body Issue185JSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewIssue185Request(c.Server, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) Issue209(ctx context.Context, str StringInPath, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewIssue209Request(c.Server, str) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) Issue30(ctx context.Context, pFallthrough string, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewIssue30Request(c.Server, pFallthrough) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) GetIssues375(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewGetIssues375Request(c.Server) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) Issue41(ctx context.Context, n1param N5StartsWithNumber, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewIssue41Request(c.Server, n1param) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) Issue9WithBody(ctx context.Context, params *Issue9Params, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewIssue9RequestWithBody(c.Server, params, contentType, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) Issue9(ctx context.Context, params *Issue9Params, body Issue9JSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewIssue9Request(c.Server, params, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) Issue975(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewIssue975Request(c.Server) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -// NewEnsureEverythingIsReferencedRequest generates requests for EnsureEverythingIsReferenced -func NewEnsureEverythingIsReferencedRequest(server string) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/ensure-everything-is-referenced") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -// NewIssue1051Request generates requests for Issue1051 -func NewIssue1051Request(server string) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/issues/1051") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -// NewIssue127Request generates requests for Issue127 -func NewIssue127Request(server string) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/issues/127") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -// NewIssue185Request calls the generic Issue185 builder with application/json body -func NewIssue185Request(server string, body Issue185JSONRequestBody) (*http.Request, error) { - var bodyReader io.Reader - buf, err := json.Marshal(body) - if err != nil { - return nil, err - } - bodyReader = bytes.NewReader(buf) - return NewIssue185RequestWithBody(server, "application/json", bodyReader) -} - -// NewIssue185RequestWithBody generates requests for Issue185 with any type of body -func NewIssue185RequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/issues/185") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), body) - if err != nil { - return nil, err - } - - req.Header.Add("Content-Type", contentType) - - return req, nil -} - -// NewIssue209Request generates requests for Issue209 -func NewIssue209Request(server string, str StringInPath) (*http.Request, error) { - var err error - - var pathParam0 string - - pathParam0, err = runtime.StyleParamWithOptions("simple", false, "str", str, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) - if err != nil { - return nil, err - } - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/issues/209/$%s", pathParam0) - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -// NewIssue30Request generates requests for Issue30 -func NewIssue30Request(server string, pFallthrough string) (*http.Request, error) { - var err error - - var pathParam0 string - - pathParam0, err = runtime.StyleParamWithOptions("simple", false, "fallthrough", pFallthrough, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) - if err != nil { - return nil, err - } - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/issues/30/%s", pathParam0) - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -// NewGetIssues375Request generates requests for GetIssues375 -func NewGetIssues375Request(server string) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/issues/375") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -// NewIssue41Request generates requests for Issue41 -func NewIssue41Request(server string, n1param N5StartsWithNumber) (*http.Request, error) { - var err error - - var pathParam0 string - - pathParam0, err = runtime.StyleParamWithOptions("simple", false, "1param", n1param, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "object", Format: ""}) - if err != nil { - return nil, err - } - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/issues/41/%s", pathParam0) - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -// NewIssue9Request calls the generic Issue9 builder with application/json body -func NewIssue9Request(server string, params *Issue9Params, body Issue9JSONRequestBody) (*http.Request, error) { - var bodyReader io.Reader - buf, err := json.Marshal(body) - if err != nil { - return nil, err - } - bodyReader = bytes.NewReader(buf) - return NewIssue9RequestWithBody(server, params, "application/json", bodyReader) -} - -// NewIssue9RequestWithBody generates requests for Issue9 with any type of body -func NewIssue9RequestWithBody(server string, params *Issue9Params, contentType string, body io.Reader) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/issues/9") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - if params != nil { - queryValues := queryURL.Query() - - if queryFrag, err := runtime.StyleParamWithOptions("form", true, "foo", params.Foo, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { - return nil, err - } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } - } - } - - queryURL.RawQuery = queryValues.Encode() - } - - req, err := http.NewRequest("GET", queryURL.String(), body) - if err != nil { - return nil, err - } - - req.Header.Add("Content-Type", contentType) - - return req, nil -} - -// NewIssue975Request generates requests for Issue975 -func NewIssue975Request(server string) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/issues/975") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -func (c *Client) applyEditors(ctx context.Context, req *http.Request, additionalEditors []RequestEditorFn) error { - for _, r := range c.RequestEditors { - if err := r(ctx, req); err != nil { - return err - } - } - for _, r := range additionalEditors { - if err := r(ctx, req); err != nil { - return err - } - } - return nil -} - -// ClientWithResponses builds on ClientInterface to offer response payloads -type ClientWithResponses struct { - ClientInterface -} - -// NewClientWithResponses creates a new ClientWithResponses, which wraps -// Client with return type handling -func NewClientWithResponses(server string, opts ...ClientOption) (*ClientWithResponses, error) { - client, err := NewClient(server, opts...) - if err != nil { - return nil, err - } - return &ClientWithResponses{client}, nil -} - -// WithBaseURL overrides the baseURL. -func WithBaseURL(baseURL string) ClientOption { - return func(c *Client) error { - newBaseURL, err := url.Parse(baseURL) - if err != nil { - return err - } - c.Server = newBaseURL.String() - return nil - } -} - -// ClientWithResponsesInterface is the interface specification for the client with responses above. -type ClientWithResponsesInterface interface { - // EnsureEverythingIsReferencedWithResponse request - EnsureEverythingIsReferencedWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*EnsureEverythingIsReferencedResponse, error) - - // Issue1051WithResponse request - Issue1051WithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*Issue1051Response, error) - - // Issue127WithResponse request - Issue127WithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*Issue127Response, error) - - // Issue185WithBodyWithResponse request with any body - Issue185WithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*Issue185Response, error) - - Issue185WithResponse(ctx context.Context, body Issue185JSONRequestBody, reqEditors ...RequestEditorFn) (*Issue185Response, error) - - // Issue209WithResponse request - Issue209WithResponse(ctx context.Context, str StringInPath, reqEditors ...RequestEditorFn) (*Issue209Response, error) - - // Issue30WithResponse request - Issue30WithResponse(ctx context.Context, pFallthrough string, reqEditors ...RequestEditorFn) (*Issue30Response, error) - - // GetIssues375WithResponse request - GetIssues375WithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*GetIssues375Response, error) - - // Issue41WithResponse request - Issue41WithResponse(ctx context.Context, n1param N5StartsWithNumber, reqEditors ...RequestEditorFn) (*Issue41Response, error) - - // Issue9WithBodyWithResponse request with any body - Issue9WithBodyWithResponse(ctx context.Context, params *Issue9Params, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*Issue9Response, error) - - Issue9WithResponse(ctx context.Context, params *Issue9Params, body Issue9JSONRequestBody, reqEditors ...RequestEditorFn) (*Issue9Response, error) - - // Issue975WithResponse request - Issue975WithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*Issue975Response, error) -} - -type EnsureEverythingIsReferencedResponse struct { - Body []byte - HTTPResponse *http.Response - JSON200 *struct { - AnyType1 *AnyType1 `json:"anyType1,omitempty"` - - // AnyType2 AnyType2 represents any type. - // - // This should be an interface{} - AnyType2 *AnyType2 `json:"anyType2,omitempty"` - CustomStringType *CustomStringType `foo:"bar" json:"customStringType,omitempty"` - } -} - -// Status returns HTTPResponse.Status -func (r EnsureEverythingIsReferencedResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r EnsureEverythingIsReferencedResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type Issue1051Response struct { - Body []byte - HTTPResponse *http.Response - JSON200 *map[string]interface{} - ApplicationvndSomethingV1JSON200 *map[string]interface{} -} - -// Status returns HTTPResponse.Status -func (r Issue1051Response) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r Issue1051Response) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type Issue127Response struct { - Body []byte - HTTPResponse *http.Response - JSON200 *GenericObject - XML200 *GenericObject - YAML200 *GenericObject - JSONDefault *GenericObject -} - -// Status returns HTTPResponse.Status -func (r Issue127Response) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r Issue127Response) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type Issue185Response struct { - Body []byte - HTTPResponse *http.Response -} - -// Status returns HTTPResponse.Status -func (r Issue185Response) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r Issue185Response) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type Issue209Response struct { - Body []byte - HTTPResponse *http.Response -} - -// Status returns HTTPResponse.Status -func (r Issue209Response) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r Issue209Response) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type Issue30Response struct { - Body []byte - HTTPResponse *http.Response -} - -// Status returns HTTPResponse.Status -func (r Issue30Response) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r Issue30Response) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type GetIssues375Response struct { - Body []byte - HTTPResponse *http.Response - JSON200 *EnumInObjInArray -} - -// Status returns HTTPResponse.Status -func (r GetIssues375Response) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r GetIssues375Response) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type Issue41Response struct { - Body []byte - HTTPResponse *http.Response -} - -// Status returns HTTPResponse.Status -func (r Issue41Response) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r Issue41Response) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type Issue9Response struct { - Body []byte - HTTPResponse *http.Response -} - -// Status returns HTTPResponse.Status -func (r Issue9Response) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r Issue9Response) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type Issue975Response struct { - Body []byte - HTTPResponse *http.Response - JSON200 *DeprecatedProperty -} - -// Status returns HTTPResponse.Status -func (r Issue975Response) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r Issue975Response) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -// EnsureEverythingIsReferencedWithResponse request returning *EnsureEverythingIsReferencedResponse -func (c *ClientWithResponses) EnsureEverythingIsReferencedWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*EnsureEverythingIsReferencedResponse, error) { - rsp, err := c.EnsureEverythingIsReferenced(ctx, reqEditors...) - if err != nil { - return nil, err - } - return ParseEnsureEverythingIsReferencedResponse(rsp) -} - -// Issue1051WithResponse request returning *Issue1051Response -func (c *ClientWithResponses) Issue1051WithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*Issue1051Response, error) { - rsp, err := c.Issue1051(ctx, reqEditors...) - if err != nil { - return nil, err - } - return ParseIssue1051Response(rsp) -} - -// Issue127WithResponse request returning *Issue127Response -func (c *ClientWithResponses) Issue127WithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*Issue127Response, error) { - rsp, err := c.Issue127(ctx, reqEditors...) - if err != nil { - return nil, err - } - return ParseIssue127Response(rsp) -} - -// Issue185WithBodyWithResponse request with arbitrary body returning *Issue185Response -func (c *ClientWithResponses) Issue185WithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*Issue185Response, error) { - rsp, err := c.Issue185WithBody(ctx, contentType, body, reqEditors...) - if err != nil { - return nil, err - } - return ParseIssue185Response(rsp) -} - -func (c *ClientWithResponses) Issue185WithResponse(ctx context.Context, body Issue185JSONRequestBody, reqEditors ...RequestEditorFn) (*Issue185Response, error) { - rsp, err := c.Issue185(ctx, body, reqEditors...) - if err != nil { - return nil, err - } - return ParseIssue185Response(rsp) -} - -// Issue209WithResponse request returning *Issue209Response -func (c *ClientWithResponses) Issue209WithResponse(ctx context.Context, str StringInPath, reqEditors ...RequestEditorFn) (*Issue209Response, error) { - rsp, err := c.Issue209(ctx, str, reqEditors...) - if err != nil { - return nil, err - } - return ParseIssue209Response(rsp) -} - -// Issue30WithResponse request returning *Issue30Response -func (c *ClientWithResponses) Issue30WithResponse(ctx context.Context, pFallthrough string, reqEditors ...RequestEditorFn) (*Issue30Response, error) { - rsp, err := c.Issue30(ctx, pFallthrough, reqEditors...) - if err != nil { - return nil, err - } - return ParseIssue30Response(rsp) -} - -// GetIssues375WithResponse request returning *GetIssues375Response -func (c *ClientWithResponses) GetIssues375WithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*GetIssues375Response, error) { - rsp, err := c.GetIssues375(ctx, reqEditors...) - if err != nil { - return nil, err - } - return ParseGetIssues375Response(rsp) -} - -// Issue41WithResponse request returning *Issue41Response -func (c *ClientWithResponses) Issue41WithResponse(ctx context.Context, n1param N5StartsWithNumber, reqEditors ...RequestEditorFn) (*Issue41Response, error) { - rsp, err := c.Issue41(ctx, n1param, reqEditors...) - if err != nil { - return nil, err - } - return ParseIssue41Response(rsp) -} - -// Issue9WithBodyWithResponse request with arbitrary body returning *Issue9Response -func (c *ClientWithResponses) Issue9WithBodyWithResponse(ctx context.Context, params *Issue9Params, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*Issue9Response, error) { - rsp, err := c.Issue9WithBody(ctx, params, contentType, body, reqEditors...) - if err != nil { - return nil, err - } - return ParseIssue9Response(rsp) -} - -func (c *ClientWithResponses) Issue9WithResponse(ctx context.Context, params *Issue9Params, body Issue9JSONRequestBody, reqEditors ...RequestEditorFn) (*Issue9Response, error) { - rsp, err := c.Issue9(ctx, params, body, reqEditors...) - if err != nil { - return nil, err - } - return ParseIssue9Response(rsp) -} - -// Issue975WithResponse request returning *Issue975Response -func (c *ClientWithResponses) Issue975WithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*Issue975Response, error) { - rsp, err := c.Issue975(ctx, reqEditors...) - if err != nil { - return nil, err - } - return ParseIssue975Response(rsp) -} - -// ParseEnsureEverythingIsReferencedResponse parses an HTTP response from a EnsureEverythingIsReferencedWithResponse call -func ParseEnsureEverythingIsReferencedResponse(rsp *http.Response) (*EnsureEverythingIsReferencedResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &EnsureEverythingIsReferencedResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest struct { - AnyType1 *AnyType1 `json:"anyType1,omitempty"` - - // AnyType2 AnyType2 represents any type. - // - // This should be an interface{} - AnyType2 *AnyType2 `json:"anyType2,omitempty"` - CustomStringType *CustomStringType `foo:"bar" json:"customStringType,omitempty"` - } - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON200 = &dest - - } - - return response, nil -} - -// ParseIssue1051Response parses an HTTP response from a Issue1051WithResponse call -func ParseIssue1051Response(rsp *http.Response) (*Issue1051Response, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &Issue1051Response{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - switch { - case rsp.Header.Get("Content-Type") == "application/json" && rsp.StatusCode == 200: - var dest map[string]interface{} - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON200 = &dest - - case rsp.Header.Get("Content-Type") == "application/vnd.something.v1+json" && rsp.StatusCode == 200: - var dest map[string]interface{} - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.ApplicationvndSomethingV1JSON200 = &dest - - } - - return response, nil -} - -// ParseIssue127Response parses an HTTP response from a Issue127WithResponse call -func ParseIssue127Response(rsp *http.Response) (*Issue127Response, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &Issue127Response{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest GenericObject - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON200 = &dest - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: - var dest GenericObject - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSONDefault = &dest - - case strings.Contains(rsp.Header.Get("Content-Type"), "xml") && rsp.StatusCode == 200: - var dest GenericObject - if err := xml.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.XML200 = &dest - - case strings.Contains(rsp.Header.Get("Content-Type"), "yaml") && rsp.StatusCode == 200: - var dest GenericObject - if err := yaml.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.YAML200 = &dest - - case rsp.StatusCode == 200: - // Content-type (text/markdown) unsupported - - case true: - // Content-type (text/markdown) unsupported - - } - - return response, nil -} - -// ParseIssue185Response parses an HTTP response from a Issue185WithResponse call -func ParseIssue185Response(rsp *http.Response) (*Issue185Response, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &Issue185Response{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - return response, nil -} - -// ParseIssue209Response parses an HTTP response from a Issue209WithResponse call -func ParseIssue209Response(rsp *http.Response) (*Issue209Response, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &Issue209Response{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - return response, nil -} - -// ParseIssue30Response parses an HTTP response from a Issue30WithResponse call -func ParseIssue30Response(rsp *http.Response) (*Issue30Response, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &Issue30Response{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - return response, nil -} - -// ParseGetIssues375Response parses an HTTP response from a GetIssues375WithResponse call -func ParseGetIssues375Response(rsp *http.Response) (*GetIssues375Response, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &GetIssues375Response{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest EnumInObjInArray - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON200 = &dest - - } - - return response, nil -} - -// ParseIssue41Response parses an HTTP response from a Issue41WithResponse call -func ParseIssue41Response(rsp *http.Response) (*Issue41Response, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &Issue41Response{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - return response, nil -} - -// ParseIssue9Response parses an HTTP response from a Issue9WithResponse call -func ParseIssue9Response(rsp *http.Response) (*Issue9Response, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &Issue9Response{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - return response, nil -} - -// ParseIssue975Response parses an HTTP response from a Issue975WithResponse call -func ParseIssue975Response(rsp *http.Response) (*Issue975Response, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &Issue975Response{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest DeprecatedProperty - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON200 = &dest - - } - - return response, nil -} - -// ServerInterface represents all server handlers. -type ServerInterface interface { - - // (GET /ensure-everything-is-referenced) - EnsureEverythingIsReferenced(ctx echo.Context) error - - // (GET /issues/1051) - Issue1051(ctx echo.Context) error - - // (GET /issues/127) - Issue127(ctx echo.Context) error - - // (GET /issues/185) - Issue185(ctx echo.Context) error - - // (GET /issues/209/${str}) - Issue209(ctx echo.Context, str StringInPath) error - - // (GET /issues/30/{fallthrough}) - Issue30(ctx echo.Context, pFallthrough string) error - - // (GET /issues/375) - GetIssues375(ctx echo.Context) error - - // (GET /issues/41/{1param}) - Issue41(ctx echo.Context, n1param N5StartsWithNumber) error - - // (GET /issues/9) - Issue9(ctx echo.Context, params Issue9Params) error - - // (GET /issues/975) - Issue975(ctx echo.Context) error -} - -// ServerInterfaceWrapper converts echo contexts to parameters. -type ServerInterfaceWrapper struct { - Handler ServerInterface -} - -// EnsureEverythingIsReferenced converts echo context to params. -func (w *ServerInterfaceWrapper) EnsureEverythingIsReferenced(ctx echo.Context) error { - var err error - - ctx.Set(Access_tokenScopes, []string{}) - - // Invoke the callback with all the unmarshaled arguments - err = w.Handler.EnsureEverythingIsReferenced(ctx) - return err -} - -// Issue1051 converts echo context to params. -func (w *ServerInterfaceWrapper) Issue1051(ctx echo.Context) error { - var err error - - ctx.Set(Access_tokenScopes, []string{}) - - // Invoke the callback with all the unmarshaled arguments - err = w.Handler.Issue1051(ctx) - return err -} - -// Issue127 converts echo context to params. -func (w *ServerInterfaceWrapper) Issue127(ctx echo.Context) error { - var err error - - ctx.Set(Access_tokenScopes, []string{}) - - // Invoke the callback with all the unmarshaled arguments - err = w.Handler.Issue127(ctx) - return err -} - -// Issue185 converts echo context to params. -func (w *ServerInterfaceWrapper) Issue185(ctx echo.Context) error { - var err error - - ctx.Set(Access_tokenScopes, []string{}) - - // Invoke the callback with all the unmarshaled arguments - err = w.Handler.Issue185(ctx) - return err -} - -// Issue209 converts echo context to params. -func (w *ServerInterfaceWrapper) Issue209(ctx echo.Context) error { - var err error - // ------------- Path parameter "str" ------------- - var str StringInPath - - err = runtime.BindStyledParameterWithOptions("simple", "str", ctx.Param("str"), &str, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) - if err != nil { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter str: %s", err)) - } - - ctx.Set(Access_tokenScopes, []string{}) - - // Invoke the callback with all the unmarshaled arguments - err = w.Handler.Issue209(ctx, str) - return err -} - -// Issue30 converts echo context to params. -func (w *ServerInterfaceWrapper) Issue30(ctx echo.Context) error { - var err error - // ------------- Path parameter "fallthrough" ------------- - var pFallthrough string - - err = runtime.BindStyledParameterWithOptions("simple", "fallthrough", ctx.Param("fallthrough"), &pFallthrough, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) - if err != nil { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter fallthrough: %s", err)) - } - - ctx.Set(Access_tokenScopes, []string{}) - - // Invoke the callback with all the unmarshaled arguments - err = w.Handler.Issue30(ctx, pFallthrough) - return err -} - -// GetIssues375 converts echo context to params. -func (w *ServerInterfaceWrapper) GetIssues375(ctx echo.Context) error { - var err error - - ctx.Set(Access_tokenScopes, []string{}) - - // Invoke the callback with all the unmarshaled arguments - err = w.Handler.GetIssues375(ctx) - return err -} - -// Issue41 converts echo context to params. -func (w *ServerInterfaceWrapper) Issue41(ctx echo.Context) error { - var err error - // ------------- Path parameter "1param" ------------- - var n1param N5StartsWithNumber - - err = runtime.BindStyledParameterWithOptions("simple", "1param", ctx.Param("1param"), &n1param, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "object", Format: ""}) - if err != nil { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter 1param: %s", err)) - } - - ctx.Set(Access_tokenScopes, []string{}) - - // Invoke the callback with all the unmarshaled arguments - err = w.Handler.Issue41(ctx, n1param) - return err -} - -// Issue9 converts echo context to params. -func (w *ServerInterfaceWrapper) Issue9(ctx echo.Context) error { - var err error - - ctx.Set(Access_tokenScopes, []string{}) - - // Parameter object where we will unmarshal all parameters from the context - var params Issue9Params - // ------------- Required query parameter "foo" ------------- - - err = runtime.BindQueryParameterWithOptions("form", true, true, "foo", ctx.QueryParams(), ¶ms.Foo, runtime.BindQueryParameterOptions{Type: "string", Format: ""}) - if err != nil { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter foo: %s", err)) - } - - // Invoke the callback with all the unmarshaled arguments - err = w.Handler.Issue9(ctx, params) - return err -} - -// Issue975 converts echo context to params. -func (w *ServerInterfaceWrapper) Issue975(ctx echo.Context) error { - var err error - - ctx.Set(Access_tokenScopes, []string{}) - - // Invoke the callback with all the unmarshaled arguments - err = w.Handler.Issue975(ctx) - return err -} - -// This is a simple interface which specifies echo.Route addition functions which -// are present on both echo.Echo and echo.Group, since we want to allow using -// either of them for path registration -type EchoRouter interface { - CONNECT(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - DELETE(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - GET(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - HEAD(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - OPTIONS(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - PATCH(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - POST(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - PUT(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - TRACE(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route -} - -// RegisterHandlers adds each server route to the EchoRouter. -func RegisterHandlers(router EchoRouter, si ServerInterface) { - RegisterHandlersWithBaseURL(router, si, "") -} - -// Registers handlers, and prepends BaseURL to the paths, so that the paths -// can be served under a prefix. -func RegisterHandlersWithBaseURL(router EchoRouter, si ServerInterface, baseURL string) { - - wrapper := ServerInterfaceWrapper{ - Handler: si, - } - - router.GET(baseURL+"/ensure-everything-is-referenced", wrapper.EnsureEverythingIsReferenced) - router.GET(baseURL+"/issues/1051", wrapper.Issue1051) - router.GET(baseURL+"/issues/127", wrapper.Issue127) - router.GET(baseURL+"/issues/185", wrapper.Issue185) - router.GET(baseURL+"/issues/209/$:str", wrapper.Issue209) - router.GET(baseURL+"/issues/30/:fallthrough", wrapper.Issue30) - router.GET(baseURL+"/issues/375", wrapper.GetIssues375) - router.GET(baseURL+"/issues/41/:1param", wrapper.Issue41) - router.GET(baseURL+"/issues/9", wrapper.Issue9) - router.GET(baseURL+"/issues/975", wrapper.Issue975) - -} - -// Base64 encoded, gzipped, json marshaled Swagger object -var swaggerSpec = []string{ - - "H4sIAAAAAAAC/7RYXW/buBL9Kyxvgftw/Z0GbfyW2+0WLrBJ0GTRhzoPtDi22EhDlaTsCIb++2JI2bIj", - "yW02bV5iiZzhmTPDM6S2PNJpphHQWT7d8kwYkYID459unVG4muGNcDE9S7CRUZlTGvmUXzLrx1kmXMz2", - "lrzHFQ3TW97jKFLgU24dDRj4nisDkk+dyaHHbRRDKsi1K7JqmsIVL8tyN+iBnN86YZz9olx8lacLME00", - "d7GyLJgwWpNZb8I2ysVMMAxmvd1CevENIsfLHr/E4q7IYMyn2/pp0hJuNcIMZAYsMcYEFowcDuY4x4Ag", - "1nki2QKYQKbQgVmKCLblHGmt97l1Og203nkgW77UJhWOT3nkB2uIFRc9/tjXIlP9SEtYAfbh0RnRd2Jl", - "g7nmU74QhhNnfxC2SDiQN0ZnYFzhsxp+K/AWCBsabEb4twXmKAjUm1cNHGWP68S7HQfT3Uq7ZHZNn7RP", - "P1575lhuQTKnmdQBhUDJXCzcCSRnP4OECKzn9A0Iuw/3KnDBFFoHQr468P3mV8N+Ho7ycLd83SdtD4/f", - "t9TyB8zTGV4vvs3w0hjhk68cpLZZBWuR0D/APCX/S2UsQbYQaZQHzvc7smW56oXwS5U9/hEQjIquw4R6", - "V9cWV3mSiEUCN0dYjpFpT26A10x8NXiJcufL1/T+d0ct1lxuuwef5/RJhva/2/21pes6d2BIB0jYLlFj", - "kerczhCDwB3TojpeH4ZEgrMC08CmZHN9KseV7tPLfiXSfuXPQE9yD+d6DzfM2v6ABz+rV8FtRl36GsuN", - "csUtqXWIQkQRWNt3+gGQnhcgDJg/d9L46ctdP+gkCzOZnzmYI6/6BC0RjOp9FzuXhVaicKlbWgZYxyJh", - "wbKlNmwtjNK5Zcra3L/KUTK9BsOcSmHAbhIQFpiQkgnmdrZkOkdqBIt8xZbqEWSA5ZSj0gmr3IJZe2hr", - "MDasPh6MBqNQ0oAiU3zKzwajwZj3fOv0tAwBbW6gD2swhYsVrvrK9g0swQBGoZpX4Dq6IaDMtELH4FFZ", - "Z5nVXphY3fJZJJB6VWSANIkp9Bo2R5tB5JUMtaMJmckRpI+Lik/QMjPJp/yDB/hhj29mP9foqDBsptGG", - "JE9GI/oXaXSAHrTIskRF3tvwm1fD7cGZ4LjQRd2n+WsDSz7l/xnWoQyr48Jw38/L3s5m8pM2E7KJWnr0", - "KdtGT2+RyvDX48NQW8Px6Hzcmbu/8sSpLAGWglTCny8sI9KEQvbp9vqqJQ0z8uu9vpDz5m49nL9GObA6", - "BZ/qwXr8vx87eBr55G134OIBGJUTy9HmWaYN1aSH/ugqHqTG/zqWGYA0c6ye5UcHncxM3r6UmFMlcNz3", - "npL2mCYvcUXBD1NhHqTe4IsdFeIlaMiNhKXIE/cbyftFET+tvHfn3XJZZMBWZO8jYJsYkO2OGsNdd2O1", - "IDFhgO3OB91l9+68Og2Adf/XsvhlpLWco0K0BzVO8A4JmIwuhq+31pmyk4f3MUQPlqllfZ0LoUqIElFT", - "kBTtAU9GF7yJoXd0rfzaHlk9ZXh07SzvD0I4Gw23S5EkLjY6X8VlM4LPYKnVSvYAxUYbeXgjywz4/kxt", - "jpo9EejvipVwVJS0xHU2+pmwWq69B2Cfdf09Cvptd+HSgb9KTlW5wu4KmVRxoyKgdLoYGB31/bhCupwG", - "hZ7jJlZRXL23SgLTSxr2h/q2yv4IznNiCddvFNXGXaaxo9+Mh9uxz0F3Rd/sUnTwUUDhKnwW2H8UaEn5", - "m3AQ+1GCw/onc3sqyOaHjbK8P7mLL7o3b6IAXdi51jdEpjDSxkDkkoJ+J7kE6c+6lSYFGhZaFnTYm2Md", - "b6emXXTQ8j0HUxwUvtbPK/h/rZNVUzpk4rpSbh8ZP62KFyd2V/01hS0VJLWYrMAxUWkhHadTQNdJ2O/d", - "Ji1ffFoY8d/q8qhKuGzE5V+vhSlobySwhoRkQOoop9A8Ll7tvt3tzaf++N729Z7y6AW4Ko3cJNVFbDoc", - "VhcdujoNJECWimwgFCn8PwEAAP//WUiKvIcUAAA=", -} - -// GetSwagger returns the content of the embedded swagger specification file -// or error if failed to decode -func decodeSpec() ([]byte, error) { - zipped, err := base64.StdEncoding.DecodeString(strings.Join(swaggerSpec, "")) - if err != nil { - return nil, fmt.Errorf("error base64 decoding spec: %w", err) - } - zr, err := gzip.NewReader(bytes.NewReader(zipped)) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - var buf bytes.Buffer - _, err = buf.ReadFrom(zr) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - - return buf.Bytes(), nil -} - -var rawSpec = decodeSpecCached() - -// a naive cached of a decoded swagger spec -func decodeSpecCached() func() ([]byte, error) { - data, err := decodeSpec() - return func() ([]byte, error) { - return data, err - } -} - -// Constructs a synthetic filesystem for resolving external references when loading openapi specifications. -func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { - res := make(map[string]func() ([]byte, error)) - if len(pathToFile) > 0 { - res[pathToFile] = rawSpec - } - - return res -} - -// GetSwagger returns the Swagger specification corresponding to the generated code -// in this file. The external references of Swagger specification are resolved. -// The logic of resolving external references is tightly connected to "import-mapping" feature. -// Externally referenced files must be embedded in the corresponding golang packages. -// Urls can be supported but this task was out of the scope. -func GetSwagger() (swagger *openapi3.T, err error) { - resolvePath := PathToRawSpec("") - - loader := openapi3.NewLoader() - loader.IsExternalRefsAllowed = true - loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() - pathToFile = path.Clean(pathToFile) - getSpec, ok := resolvePath[pathToFile] - if !ok { - err1 := fmt.Errorf("path not found: %s", pathToFile) - return nil, err1 - } - return getSpec() - } - var specData []byte - specData, err = rawSpec() - if err != nil { - return - } - swagger, err = loader.LoadFromData(specData) - if err != nil { - return - } - return -} diff --git a/internal/test/schemas/schemas.yaml b/internal/test/schemas/schemas.yaml deleted file mode 100644 index 2e094de126..0000000000 --- a/internal/test/schemas/schemas.yaml +++ /dev/null @@ -1,250 +0,0 @@ -openapi: "3.0.1" -info: - version: 1.0.0 - title: Test Server - description: | - Test cases for various issues found over time. Please add a test case for - any bug fixed. -servers: - - url: http://openapitest.deepmap.ai -paths: - /ensure-everything-is-referenced: - get: - operationId: ensureEverythingIsReferenced - description: | - This endpoint exists so that components can be created in this - spec and not be pruned - responses: - 200: - content: - application/json: - schema: - type: object - properties: - anyType1: - $ref: "#/components/schemas/AnyType1" - anyType2: - $ref: "#/components/schemas/AnyType2" - customStringType: - $ref: "#/components/schemas/CustomStringType" - /issues/9: - get: - operationId: Issue9 - description: | - Client params type incorrectly included for request with body and - parameters. - parameters: - - name: foo - in: query - required: true - schema: - type: string - requestBody: - description: Optional body - required: false - content: - application/json: - schema: { } - /issues/30/{fallthrough}: - get: - operationId: Issue30 - description: | - Reserved keywords should be prefixed in variable names. - parameters: - - name: fallthrough - in: path - required: true - schema: - type: string - /issues/41/{1param}: - get: - operationId: Issue41 - description: Parameter name starting with number - parameters: - - name: 1param - in: path - required: true - schema: - $ref: "#/components/schemas/5StartsWithNumber" - /issues/127: - get: - operationId: Issue127 - description: | - Make sure unsupported context types don't preempt supported types. - responses: - 200: - content: - application/json: - schema: - $ref: "#/components/schemas/GenericObject" - text/markdown: - schema: - $ref: "#/components/schemas/GenericObject" - text/yaml: - schema: - $ref: "#/components/schemas/GenericObject" - application/xml: - schema: - $ref: "#/components/schemas/GenericObject" - default: - content: - application/json: - schema: - $ref: "#/components/schemas/GenericObject" - text/markdown: - schema: - $ref: "#/components/schemas/GenericObject" - /issues/185: - get: - operationId: Issue185 - description: | - Type generation when optional/required properties are nullable. - requestBody: - content: - application/json: - schema: - $ref: "#/components/schemas/NullableProperties" - /issues/209/${str}: - parameters: - - $ref: '#/components/parameters/StringInPath' - get: - operationId: Issue209 - description: Checks if parameters are declared properly - /issues/375: - get: - description: | - Enum declaration was generated twice if the enum was in an object - which was inside of an array. - responses: - 200: - content: - application/json: - schema: - $ref: "#/components/schemas/EnumInObjInArray" - /issues/975: - get: - operationId: Issue975 - description: | - Deprecated fields should get a proper comment - responses: - 200: - description: A struct with deprecated fields with varying level of documentation - content: - application/json: - schema: - $ref: "#/components/schemas/DeprecatedProperty" - /issues/1051: - get: - operationId: Issue1051 - description: | - Multiple media types contain JSON - responses: - '200': - content: - application/vnd.something.v1+json: - schema: - type: object - application/json: - schema: - type: object -components: - schemas: - GenericObject: - type: object - AnyType1: { } - AnyType2: - description: | - AnyType2 represents any type. - - This should be an interface{} - CustomStringType: - type: string - format: custom - x-oapi-codegen-extra-tags: - foo: bar - NullableProperties: - type: object - properties: - optional: - type: string - nullable: false - optionalAndNullable: - type: string - nullable: true - required: - type: string - nullable: false - requiredAndNullable: - type: string - nullable: true - required: [ required, requiredAndNullable ] - 5StartsWithNumber: - type: object - description: This schema name starts with a number - EnumInObjInArray: - type: array - items: - type: object - properties: - val: - type: string - enum: - - first - - second - DeprecatedProperty: - type: object - required: - - newProp - - oldProp - properties: - newProp: - type: string - description: Use this now! - oldProp1: - type: string - deprecated: true - # description: No description on this one to test generation in that case - oldProp2: - type: string - deprecated: true - description: It used to do this and that - oldProp3: - type: string - deprecated: true - x-deprecated-reason: Use NewProp instead! - oldProp4: - type: string - deprecated: true - x-deprecated-reason: Use NewProp instead! - description: It used to do this and that - OuterTypeWithAnonymousInner: - type: object - properties: - name: - type: string - inner: - type: object - x-go-type-name: InnerRenamedAnonymousObject - properties: - id: - type: integer - required: [ id ] - required: [ name, inner ] - parameters: - StringInPath: - name: str - description: A string path parameter - in: path - required: true - schema: - type: string - securitySchemes: - # This security scheme has a - in it, we need to make sure the name gets - # remapped to a valid Go id. See bug - access-token: - type: http - scheme: bearer - bearerFormat: | - JWT-format access token. -security: - - access-token: [ ] diff --git a/internal/test/server/config.yaml b/internal/test/server/config.yaml deleted file mode 100644 index 4e8702b1f3..0000000000 --- a/internal/test/server/config.yaml +++ /dev/null @@ -1,6 +0,0 @@ -# yaml-language-server: $schema=../../../configuration-schema.json -package: server -generate: - chi-server: true - models: true -output: server.gen.go diff --git a/internal/test/server/doc.go b/internal/test/server/doc.go deleted file mode 100644 index f46abed62f..0000000000 --- a/internal/test/server/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -package server - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml ../test-schema.yaml diff --git a/internal/test/server/server.gen.go b/internal/test/server/server.gen.go deleted file mode 100644 index 67e89ff318..0000000000 --- a/internal/test/server/server.gen.go +++ /dev/null @@ -1,660 +0,0 @@ -// Package server provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package server - -import ( - "fmt" - "net/http" - "time" - - "github.com/go-chi/chi/v5" - "github.com/oapi-codegen/runtime" - openapi_types "github.com/oapi-codegen/runtime/types" -) - -// Defines values for GetWithContentTypeParamsContentType. -const ( - Json GetWithContentTypeParamsContentType = "json" - Text GetWithContentTypeParamsContentType = "text" -) - -// Valid indicates whether the value is a known member of the GetWithContentTypeParamsContentType enum. -func (e GetWithContentTypeParamsContentType) Valid() bool { - switch e { - case Json: - return true - case Text: - return true - default: - return false - } -} - -// EveryTypeOptional defines model for EveryTypeOptional. -type EveryTypeOptional struct { - ArrayInlineField *[]int `json:"array_inline_field,omitempty"` - ArrayReferencedField *[]SomeObject `json:"array_referenced_field,omitempty"` - BoolField *bool `json:"bool_field,omitempty"` - ByteField *[]byte `json:"byte_field,omitempty"` - DateField *openapi_types.Date `json:"date_field,omitempty"` - DateTimeField *time.Time `json:"date_time_field,omitempty"` - DoubleField *float64 `json:"double_field,omitempty"` - FloatField *float32 `json:"float_field,omitempty"` - InlineObjectField *struct { - Name string `json:"name"` - Number int `json:"number"` - } `json:"inline_object_field,omitempty"` - Int32Field *int32 `json:"int32_field,omitempty"` - Int64Field *int64 `json:"int64_field,omitempty"` - IntField *int `json:"int_field,omitempty"` - NumberField *float32 `json:"number_field,omitempty"` - ReferencedField *SomeObject `json:"referenced_field,omitempty"` - StringField *string `json:"string_field,omitempty"` -} - -// EveryTypeRequired defines model for EveryTypeRequired. -type EveryTypeRequired struct { - ArrayInlineField []int `json:"array_inline_field"` - ArrayReferencedField []SomeObject `json:"array_referenced_field"` - BoolField bool `json:"bool_field"` - ByteField []byte `json:"byte_field"` - DateField openapi_types.Date `json:"date_field"` - DateTimeField time.Time `json:"date_time_field"` - DoubleField float64 `json:"double_field"` - EmailField *openapi_types.Email `json:"email_field,omitempty"` - FloatField float32 `json:"float_field"` - InlineObjectField struct { - Name string `json:"name"` - Number int `json:"number"` - } `json:"inline_object_field"` - Int32Field int32 `json:"int32_field"` - Int64Field int64 `json:"int64_field"` - IntField int `json:"int_field"` - NumberField float32 `json:"number_field"` - ReferencedField SomeObject `json:"referenced_field"` - StringField string `json:"string_field"` -} - -// ReservedKeyword defines model for ReservedKeyword. -type ReservedKeyword struct { - Channel *string `json:"channel,omitempty"` -} - -// Resource defines model for Resource. -type Resource struct { - Name string `json:"name"` - Value float32 `json:"value"` -} - -// SomeObject defines model for some_object. -type SomeObject struct { - Name string `json:"name"` -} - -// Argument defines model for argument. -type Argument = string - -// ResponseWithReference defines model for ResponseWithReference. -type ResponseWithReference = SomeObject - -// SimpleResponse defines model for SimpleResponse. -type SimpleResponse struct { - Name string `json:"name"` -} - -// GetWithArgsParams defines parameters for GetWithArgs. -type GetWithArgsParams struct { - // OptionalArgument An optional query argument - OptionalArgument *int64 `form:"optional_argument,omitempty" json:"optional_argument,omitempty"` - - // RequiredArgument An optional query argument - RequiredArgument int64 `form:"required_argument" json:"required_argument"` - - // HeaderArgument An optional query argument - HeaderArgument *int32 `json:"header_argument,omitempty"` -} - -// GetWithContentTypeParamsContentType defines parameters for GetWithContentType. -type GetWithContentTypeParamsContentType string - -// CreateResource2Params defines parameters for CreateResource2. -type CreateResource2Params struct { - // InlineQueryArgument Some query argument - InlineQueryArgument *int `form:"inline_query_argument,omitempty" json:"inline_query_argument,omitempty"` -} - -// UpdateResource3JSONBody defines parameters for UpdateResource3. -type UpdateResource3JSONBody struct { - Id *int `json:"id,omitempty"` - Name *string `json:"name,omitempty"` -} - -// CreateResourceJSONRequestBody defines body for CreateResource for application/json ContentType. -type CreateResourceJSONRequestBody = EveryTypeRequired - -// CreateResource2JSONRequestBody defines body for CreateResource2 for application/json ContentType. -type CreateResource2JSONRequestBody = Resource - -// UpdateResource3JSONRequestBody defines body for UpdateResource3 for application/json ContentType. -type UpdateResource3JSONRequestBody UpdateResource3JSONBody - -// ServerInterface represents all server handlers. -type ServerInterface interface { - // get every type optional - // (GET /every-type-optional) - GetEveryTypeOptional(w http.ResponseWriter, r *http.Request) - // Get resource via simple path - // (GET /get-simple) - GetSimple(w http.ResponseWriter, r *http.Request) - // Getter with referenced parameter and referenced response - // (GET /get-with-args) - GetWithArgs(w http.ResponseWriter, r *http.Request, params GetWithArgsParams) - // Getter with referenced parameter and referenced response - // (GET /get-with-references/{global_argument}/{argument}) - GetWithReferences(w http.ResponseWriter, r *http.Request, globalArgument int64, argument Argument) - // Get an object by ID - // (GET /get-with-type/{content_type}) - GetWithContentType(w http.ResponseWriter, r *http.Request, contentType GetWithContentTypeParamsContentType) - // get with reserved keyword - // (GET /reserved-keyword) - GetReservedKeyword(w http.ResponseWriter, r *http.Request) - // Create a resource - // (POST /resource/{argument}) - CreateResource(w http.ResponseWriter, r *http.Request, argument Argument) - // Create a resource with inline parameter - // (POST /resource2/{inline_argument}) - CreateResource2(w http.ResponseWriter, r *http.Request, inlineArgument int, params CreateResource2Params) - // Update a resource with inline body. The parameter name is a reserved - // keyword, so make sure that gets prefixed to avoid syntax errors - // (PUT /resource3/{fallthrough}) - UpdateResource3(w http.ResponseWriter, r *http.Request, pFallthrough int) - // get response with reference - // (GET /response-with-reference) - GetResponseWithReference(w http.ResponseWriter, r *http.Request) -} - -// Unimplemented server implementation that returns http.StatusNotImplemented for each endpoint. - -type Unimplemented struct{} - -// get every type optional -// (GET /every-type-optional) -func (_ Unimplemented) GetEveryTypeOptional(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusNotImplemented) -} - -// Get resource via simple path -// (GET /get-simple) -func (_ Unimplemented) GetSimple(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusNotImplemented) -} - -// Getter with referenced parameter and referenced response -// (GET /get-with-args) -func (_ Unimplemented) GetWithArgs(w http.ResponseWriter, r *http.Request, params GetWithArgsParams) { - w.WriteHeader(http.StatusNotImplemented) -} - -// Getter with referenced parameter and referenced response -// (GET /get-with-references/{global_argument}/{argument}) -func (_ Unimplemented) GetWithReferences(w http.ResponseWriter, r *http.Request, globalArgument int64, argument Argument) { - w.WriteHeader(http.StatusNotImplemented) -} - -// Get an object by ID -// (GET /get-with-type/{content_type}) -func (_ Unimplemented) GetWithContentType(w http.ResponseWriter, r *http.Request, contentType GetWithContentTypeParamsContentType) { - w.WriteHeader(http.StatusNotImplemented) -} - -// get with reserved keyword -// (GET /reserved-keyword) -func (_ Unimplemented) GetReservedKeyword(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusNotImplemented) -} - -// Create a resource -// (POST /resource/{argument}) -func (_ Unimplemented) CreateResource(w http.ResponseWriter, r *http.Request, argument Argument) { - w.WriteHeader(http.StatusNotImplemented) -} - -// Create a resource with inline parameter -// (POST /resource2/{inline_argument}) -func (_ Unimplemented) CreateResource2(w http.ResponseWriter, r *http.Request, inlineArgument int, params CreateResource2Params) { - w.WriteHeader(http.StatusNotImplemented) -} - -// Update a resource with inline body. The parameter name is a reserved -// keyword, so make sure that gets prefixed to avoid syntax errors -// (PUT /resource3/{fallthrough}) -func (_ Unimplemented) UpdateResource3(w http.ResponseWriter, r *http.Request, pFallthrough int) { - w.WriteHeader(http.StatusNotImplemented) -} - -// get response with reference -// (GET /response-with-reference) -func (_ Unimplemented) GetResponseWithReference(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusNotImplemented) -} - -// ServerInterfaceWrapper converts contexts to parameters. -type ServerInterfaceWrapper struct { - Handler ServerInterface - HandlerMiddlewares []MiddlewareFunc - ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) -} - -type MiddlewareFunc func(http.Handler) http.Handler - -// GetEveryTypeOptional operation middleware -func (siw *ServerInterfaceWrapper) GetEveryTypeOptional(w http.ResponseWriter, r *http.Request) { - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.GetEveryTypeOptional(w, r) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -// GetSimple operation middleware -func (siw *ServerInterfaceWrapper) GetSimple(w http.ResponseWriter, r *http.Request) { - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.GetSimple(w, r) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -// GetWithArgs operation middleware -func (siw *ServerInterfaceWrapper) GetWithArgs(w http.ResponseWriter, r *http.Request) { - - var err error - - // Parameter object where we will unmarshal all parameters from the context - var params GetWithArgsParams - - // ------------- Optional query parameter "optional_argument" ------------- - - err = runtime.BindQueryParameterWithOptions("form", true, false, "optional_argument", r.URL.Query(), ¶ms.OptionalArgument, runtime.BindQueryParameterOptions{Type: "integer", Format: "int64"}) - if err != nil { - siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "optional_argument", Err: err}) - return - } - - // ------------- Required query parameter "required_argument" ------------- - - if paramValue := r.URL.Query().Get("required_argument"); paramValue != "" { - - } else { - siw.ErrorHandlerFunc(w, r, &RequiredParamError{ParamName: "required_argument"}) - return - } - - err = runtime.BindQueryParameterWithOptions("form", true, true, "required_argument", r.URL.Query(), ¶ms.RequiredArgument, runtime.BindQueryParameterOptions{Type: "integer", Format: "int64"}) - if err != nil { - siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "required_argument", Err: err}) - return - } - - headers := r.Header - - // ------------- Optional header parameter "header_argument" ------------- - if valueList, found := headers[http.CanonicalHeaderKey("header_argument")]; found { - var HeaderArgument int32 - n := len(valueList) - if n != 1 { - siw.ErrorHandlerFunc(w, r, &TooManyValuesForParamError{ParamName: "header_argument", Count: n}) - return - } - - err = runtime.BindStyledParameterWithOptions("simple", "header_argument", valueList[0], &HeaderArgument, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int32"}) - if err != nil { - siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "header_argument", Err: err}) - return - } - - params.HeaderArgument = &HeaderArgument - - } - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.GetWithArgs(w, r, params) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -// GetWithReferences operation middleware -func (siw *ServerInterfaceWrapper) GetWithReferences(w http.ResponseWriter, r *http.Request) { - - var err error - - // ------------- Path parameter "global_argument" ------------- - var globalArgument int64 - - err = runtime.BindStyledParameterWithOptions("simple", "global_argument", chi.URLParam(r, "global_argument"), &globalArgument, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "integer", Format: "int64"}) - if err != nil { - siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "global_argument", Err: err}) - return - } - - // ------------- Path parameter "argument" ------------- - var argument Argument - - err = runtime.BindStyledParameterWithOptions("simple", "argument", chi.URLParam(r, "argument"), &argument, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) - if err != nil { - siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "argument", Err: err}) - return - } - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.GetWithReferences(w, r, globalArgument, argument) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -// GetWithContentType operation middleware -func (siw *ServerInterfaceWrapper) GetWithContentType(w http.ResponseWriter, r *http.Request) { - - var err error - - // ------------- Path parameter "content_type" ------------- - var contentType GetWithContentTypeParamsContentType - - err = runtime.BindStyledParameterWithOptions("simple", "content_type", chi.URLParam(r, "content_type"), &contentType, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) - if err != nil { - siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "content_type", Err: err}) - return - } - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.GetWithContentType(w, r, contentType) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -// GetReservedKeyword operation middleware -func (siw *ServerInterfaceWrapper) GetReservedKeyword(w http.ResponseWriter, r *http.Request) { - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.GetReservedKeyword(w, r) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -// CreateResource operation middleware -func (siw *ServerInterfaceWrapper) CreateResource(w http.ResponseWriter, r *http.Request) { - - var err error - - // ------------- Path parameter "argument" ------------- - var argument Argument - - err = runtime.BindStyledParameterWithOptions("simple", "argument", chi.URLParam(r, "argument"), &argument, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) - if err != nil { - siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "argument", Err: err}) - return - } - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.CreateResource(w, r, argument) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -// CreateResource2 operation middleware -func (siw *ServerInterfaceWrapper) CreateResource2(w http.ResponseWriter, r *http.Request) { - - var err error - - // ------------- Path parameter "inline_argument" ------------- - var inlineArgument int - - err = runtime.BindStyledParameterWithOptions("simple", "inline_argument", chi.URLParam(r, "inline_argument"), &inlineArgument, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "integer", Format: ""}) - if err != nil { - siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "inline_argument", Err: err}) - return - } - - // Parameter object where we will unmarshal all parameters from the context - var params CreateResource2Params - - // ------------- Optional query parameter "inline_query_argument" ------------- - - err = runtime.BindQueryParameterWithOptions("form", true, false, "inline_query_argument", r.URL.Query(), ¶ms.InlineQueryArgument, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) - if err != nil { - siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "inline_query_argument", Err: err}) - return - } - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.CreateResource2(w, r, inlineArgument, params) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -// UpdateResource3 operation middleware -func (siw *ServerInterfaceWrapper) UpdateResource3(w http.ResponseWriter, r *http.Request) { - - var err error - - // ------------- Path parameter "fallthrough" ------------- - var pFallthrough int - - err = runtime.BindStyledParameterWithOptions("simple", "fallthrough", chi.URLParam(r, "fallthrough"), &pFallthrough, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "integer", Format: ""}) - if err != nil { - siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "fallthrough", Err: err}) - return - } - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.UpdateResource3(w, r, pFallthrough) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -// GetResponseWithReference operation middleware -func (siw *ServerInterfaceWrapper) GetResponseWithReference(w http.ResponseWriter, r *http.Request) { - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.GetResponseWithReference(w, r) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -type UnescapedCookieParamError struct { - ParamName string - Err error -} - -func (e *UnescapedCookieParamError) Error() string { - return fmt.Sprintf("error unescaping cookie parameter '%s'", e.ParamName) -} - -func (e *UnescapedCookieParamError) Unwrap() error { - return e.Err -} - -type UnmarshalingParamError struct { - ParamName string - Err error -} - -func (e *UnmarshalingParamError) Error() string { - return fmt.Sprintf("Error unmarshaling parameter %s as JSON: %s", e.ParamName, e.Err.Error()) -} - -func (e *UnmarshalingParamError) Unwrap() error { - return e.Err -} - -type RequiredParamError struct { - ParamName string -} - -func (e *RequiredParamError) Error() string { - return fmt.Sprintf("Query argument %s is required, but not found", e.ParamName) -} - -type RequiredHeaderError struct { - ParamName string - Err error -} - -func (e *RequiredHeaderError) Error() string { - return fmt.Sprintf("Header parameter %s is required, but not found", e.ParamName) -} - -func (e *RequiredHeaderError) Unwrap() error { - return e.Err -} - -type InvalidParamFormatError struct { - ParamName string - Err error -} - -func (e *InvalidParamFormatError) Error() string { - return fmt.Sprintf("Invalid format for parameter %s: %s", e.ParamName, e.Err.Error()) -} - -func (e *InvalidParamFormatError) Unwrap() error { - return e.Err -} - -type TooManyValuesForParamError struct { - ParamName string - Count int -} - -func (e *TooManyValuesForParamError) Error() string { - return fmt.Sprintf("Expected one value for %s, got %d", e.ParamName, e.Count) -} - -// Handler creates http.Handler with routing matching OpenAPI spec. -func Handler(si ServerInterface) http.Handler { - return HandlerWithOptions(si, ChiServerOptions{}) -} - -type ChiServerOptions struct { - BaseURL string - BaseRouter chi.Router - Middlewares []MiddlewareFunc - ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) -} - -// HandlerFromMux creates http.Handler with routing matching OpenAPI spec based on the provided mux. -func HandlerFromMux(si ServerInterface, r chi.Router) http.Handler { - return HandlerWithOptions(si, ChiServerOptions{ - BaseRouter: r, - }) -} - -func HandlerFromMuxWithBaseURL(si ServerInterface, r chi.Router, baseURL string) http.Handler { - return HandlerWithOptions(si, ChiServerOptions{ - BaseURL: baseURL, - BaseRouter: r, - }) -} - -// HandlerWithOptions creates http.Handler with additional options -func HandlerWithOptions(si ServerInterface, options ChiServerOptions) http.Handler { - r := options.BaseRouter - - if r == nil { - r = chi.NewRouter() - } - if options.ErrorHandlerFunc == nil { - options.ErrorHandlerFunc = func(w http.ResponseWriter, r *http.Request, err error) { - http.Error(w, err.Error(), http.StatusBadRequest) - } - } - wrapper := ServerInterfaceWrapper{ - Handler: si, - HandlerMiddlewares: options.Middlewares, - ErrorHandlerFunc: options.ErrorHandlerFunc, - } - - r.Group(func(r chi.Router) { - r.Get(options.BaseURL+"/every-type-optional", wrapper.GetEveryTypeOptional) - }) - r.Group(func(r chi.Router) { - r.Get(options.BaseURL+"/get-simple", wrapper.GetSimple) - }) - r.Group(func(r chi.Router) { - r.Get(options.BaseURL+"/get-with-args", wrapper.GetWithArgs) - }) - r.Group(func(r chi.Router) { - r.Get(options.BaseURL+"/get-with-references/{global_argument}/{argument}", wrapper.GetWithReferences) - }) - r.Group(func(r chi.Router) { - r.Get(options.BaseURL+"/get-with-type/{content_type}", wrapper.GetWithContentType) - }) - r.Group(func(r chi.Router) { - r.Get(options.BaseURL+"/reserved-keyword", wrapper.GetReservedKeyword) - }) - r.Group(func(r chi.Router) { - r.Post(options.BaseURL+"/resource/{argument}", wrapper.CreateResource) - }) - r.Group(func(r chi.Router) { - r.Post(options.BaseURL+"/resource2/{inline_argument}", wrapper.CreateResource2) - }) - r.Group(func(r chi.Router) { - r.Put(options.BaseURL+"/resource3/{fallthrough}", wrapper.UpdateResource3) - }) - r.Group(func(r chi.Router) { - r.Get(options.BaseURL+"/response-with-reference", wrapper.GetResponseWithReference) - }) - - return r -} diff --git a/internal/test/server/server_test.go b/internal/test/server/server_test.go deleted file mode 100644 index 386e3ddf5d..0000000000 --- a/internal/test/server/server_test.go +++ /dev/null @@ -1,136 +0,0 @@ -package server - -import ( - "errors" - "io" - "net/http" - "net/http/httptest" - "testing" - - "github.com/stretchr/testify/assert" -) - -type fakeServer struct { - t *testing.T - called bool -} - -// get every type optional -// (GET /every-type-optional) -func (s *fakeServer) GetEveryTypeOptional(w http.ResponseWriter, r *http.Request) { - // not implemented - w.WriteHeader(http.StatusTeapot) -} - -// Get resource via simple path -// (GET /get-simple) -func (s *fakeServer) GetSimple(w http.ResponseWriter, r *http.Request) { - // not implemented - w.WriteHeader(http.StatusTeapot) -} - -// Getter with referenced parameter and referenced response -// (GET /get-with-args) -func (s *fakeServer) GetWithArgs(w http.ResponseWriter, r *http.Request, params GetWithArgsParams) { - // not implemented - w.WriteHeader(http.StatusTeapot) -} - -// Getter with referenced parameter and referenced response -// (GET /get-with-references/{global_argument}/{argument}) -func (s *fakeServer) GetWithReferences(w http.ResponseWriter, r *http.Request, globalArgument int64, argument Argument) { - // not implemented - w.WriteHeader(http.StatusTeapot) -} - -// Get an object by ID -// (GET /get-with-type/{content_type}) -func (s *fakeServer) GetWithContentType(w http.ResponseWriter, r *http.Request, contentType GetWithContentTypeParamsContentType) { - // not implemented - w.WriteHeader(http.StatusTeapot) -} - -// get with reserved keyword -// (GET /reserved-keyword) -func (s *fakeServer) GetReservedKeyword(w http.ResponseWriter, r *http.Request) { - // not implemented - w.WriteHeader(http.StatusTeapot) -} - -// Create a resource -// (POST /resource/{argument}) -func (s *fakeServer) CreateResource(w http.ResponseWriter, r *http.Request, argument Argument) { - // not implemented - w.WriteHeader(http.StatusTeapot) -} - -// Create a resource with inline parameter -// (POST /resource2/{inline_argument}) -func (s *fakeServer) CreateResource2(w http.ResponseWriter, r *http.Request, inlineArgument int, params CreateResource2Params) { - assert.Equal(s.t, 99, *params.InlineQueryArgument) - assert.Equal(s.t, 1, inlineArgument) - s.called = true -} - -// Update a resource with inline body. The parameter name is a reserved -// keyword, so make sure that gets prefixed to avoid syntax errors -// (PUT /resource3/{fallthrough}) -func (s *fakeServer) UpdateResource3(w http.ResponseWriter, r *http.Request, pFallthrough int) { - // not implemented - w.WriteHeader(http.StatusTeapot) -} - -// get response with reference -// (GET /response-with-reference) -func (s *fakeServer) GetResponseWithReference(w http.ResponseWriter, r *http.Request) { - // not implemented - w.WriteHeader(http.StatusTeapot) -} - -func TestParameters(t *testing.T) { - m := fakeServer{ - t: t, - } - - h := Handler(&m) - - req := httptest.NewRequest("POST", "http://openapitest.deepmap.ai/resource2/1?inline_query_argument=99", nil) - rr := httptest.NewRecorder() - h.ServeHTTP(rr, req) - - assert.True(t, m.called) -} - -func TestErrorHandlerFunc(t *testing.T) { - m := fakeServer{} - - h := HandlerWithOptions(&m, ChiServerOptions{ - ErrorHandlerFunc: func(w http.ResponseWriter, r *http.Request, err error) { - w.Header().Set("Content-Type", "application/json") - var requiredParamError *RequiredParamError - assert.True(t, errors.As(err, &requiredParamError)) - }, - }) - - s := httptest.NewServer(h) - defer s.Close() - - req, err := http.DefaultClient.Get(s.URL + "/get-with-args") - assert.Nil(t, err) - assert.Equal(t, "application/json", req.Header.Get("Content-Type")) -} - -func TestErrorHandlerFuncBackwardsCompatible(t *testing.T) { - m := fakeServer{} - - h := HandlerWithOptions(&m, ChiServerOptions{}) - - s := httptest.NewServer(h) - defer s.Close() - - req, err := http.DefaultClient.Get(s.URL + "/get-with-args") - b, _ := io.ReadAll(req.Body) - assert.Nil(t, err) - assert.Equal(t, "text/plain; charset=utf-8", req.Header.Get("Content-Type")) - assert.Equal(t, "Query argument required_argument is required, but not found\n", string(b)) -} diff --git a/internal/test/strict-server/chi/server.cfg.yaml b/internal/test/strict-server/chi/server.cfg.yaml deleted file mode 100644 index 35425d6ec7..0000000000 --- a/internal/test/strict-server/chi/server.cfg.yaml +++ /dev/null @@ -1,7 +0,0 @@ -# yaml-language-server: $schema=../../../../configuration-schema.json -package: api -generate: - chi-server: true - strict-server: true - embedded-spec: true -output: server.gen.go diff --git a/internal/test/strict-server/chi/server.gen.go b/internal/test/strict-server/chi/server.gen.go deleted file mode 100644 index a7c569b2c5..0000000000 --- a/internal/test/strict-server/chi/server.gen.go +++ /dev/null @@ -1,1824 +0,0 @@ -// Package api provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package api - -import ( - "bytes" - "compress/gzip" - "context" - "encoding/base64" - "encoding/json" - "errors" - "fmt" - "io" - "mime" - "mime/multipart" - "net/http" - "net/url" - "path" - "strings" - - "github.com/getkin/kin-openapi/openapi3" - "github.com/go-chi/chi/v5" - "github.com/oapi-codegen/runtime" - strictnethttp "github.com/oapi-codegen/runtime/strictmiddleware/nethttp" -) - -// ServerInterface represents all server handlers. -type ServerInterface interface { - - // (POST /json) - JSONExample(w http.ResponseWriter, r *http.Request) - - // (POST /multipart) - MultipartExample(w http.ResponseWriter, r *http.Request) - - // (POST /multipart-related) - MultipartRelatedExample(w http.ResponseWriter, r *http.Request) - - // (POST /multiple) - MultipleRequestAndResponseTypes(w http.ResponseWriter, r *http.Request) - - // (POST /required-json-body) - RequiredJSONBody(w http.ResponseWriter, r *http.Request) - - // (POST /required-text-body) - RequiredTextBody(w http.ResponseWriter, r *http.Request) - - // (GET /reserved-go-keyword-parameters/{type}) - ReservedGoKeywordParameters(w http.ResponseWriter, r *http.Request, pType string) - - // (POST /reusable-responses) - ReusableResponses(w http.ResponseWriter, r *http.Request) - - // (POST /text) - TextExample(w http.ResponseWriter, r *http.Request) - - // (POST /unknown) - UnknownExample(w http.ResponseWriter, r *http.Request) - - // (POST /unspecified-content-type) - UnspecifiedContentType(w http.ResponseWriter, r *http.Request) - - // (POST /urlencoded) - URLEncodedExample(w http.ResponseWriter, r *http.Request) - - // (POST /with-headers) - HeadersExample(w http.ResponseWriter, r *http.Request, params HeadersExampleParams) - - // (POST /with-union) - UnionExample(w http.ResponseWriter, r *http.Request) -} - -// Unimplemented server implementation that returns http.StatusNotImplemented for each endpoint. - -type Unimplemented struct{} - -// (POST /json) -func (_ Unimplemented) JSONExample(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusNotImplemented) -} - -// (POST /multipart) -func (_ Unimplemented) MultipartExample(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusNotImplemented) -} - -// (POST /multipart-related) -func (_ Unimplemented) MultipartRelatedExample(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusNotImplemented) -} - -// (POST /multiple) -func (_ Unimplemented) MultipleRequestAndResponseTypes(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusNotImplemented) -} - -// (POST /required-json-body) -func (_ Unimplemented) RequiredJSONBody(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusNotImplemented) -} - -// (POST /required-text-body) -func (_ Unimplemented) RequiredTextBody(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusNotImplemented) -} - -// (GET /reserved-go-keyword-parameters/{type}) -func (_ Unimplemented) ReservedGoKeywordParameters(w http.ResponseWriter, r *http.Request, pType string) { - w.WriteHeader(http.StatusNotImplemented) -} - -// (POST /reusable-responses) -func (_ Unimplemented) ReusableResponses(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusNotImplemented) -} - -// (POST /text) -func (_ Unimplemented) TextExample(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusNotImplemented) -} - -// (POST /unknown) -func (_ Unimplemented) UnknownExample(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusNotImplemented) -} - -// (POST /unspecified-content-type) -func (_ Unimplemented) UnspecifiedContentType(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusNotImplemented) -} - -// (POST /urlencoded) -func (_ Unimplemented) URLEncodedExample(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusNotImplemented) -} - -// (POST /with-headers) -func (_ Unimplemented) HeadersExample(w http.ResponseWriter, r *http.Request, params HeadersExampleParams) { - w.WriteHeader(http.StatusNotImplemented) -} - -// (POST /with-union) -func (_ Unimplemented) UnionExample(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusNotImplemented) -} - -// ServerInterfaceWrapper converts contexts to parameters. -type ServerInterfaceWrapper struct { - Handler ServerInterface - HandlerMiddlewares []MiddlewareFunc - ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) -} - -type MiddlewareFunc func(http.Handler) http.Handler - -// JSONExample operation middleware -func (siw *ServerInterfaceWrapper) JSONExample(w http.ResponseWriter, r *http.Request) { - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.JSONExample(w, r) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -// MultipartExample operation middleware -func (siw *ServerInterfaceWrapper) MultipartExample(w http.ResponseWriter, r *http.Request) { - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.MultipartExample(w, r) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -// MultipartRelatedExample operation middleware -func (siw *ServerInterfaceWrapper) MultipartRelatedExample(w http.ResponseWriter, r *http.Request) { - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.MultipartRelatedExample(w, r) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -// MultipleRequestAndResponseTypes operation middleware -func (siw *ServerInterfaceWrapper) MultipleRequestAndResponseTypes(w http.ResponseWriter, r *http.Request) { - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.MultipleRequestAndResponseTypes(w, r) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -// RequiredJSONBody operation middleware -func (siw *ServerInterfaceWrapper) RequiredJSONBody(w http.ResponseWriter, r *http.Request) { - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.RequiredJSONBody(w, r) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -// RequiredTextBody operation middleware -func (siw *ServerInterfaceWrapper) RequiredTextBody(w http.ResponseWriter, r *http.Request) { - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.RequiredTextBody(w, r) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -// ReservedGoKeywordParameters operation middleware -func (siw *ServerInterfaceWrapper) ReservedGoKeywordParameters(w http.ResponseWriter, r *http.Request) { - - var err error - - // ------------- Path parameter "type" ------------- - var pType string - - err = runtime.BindStyledParameterWithOptions("simple", "type", chi.URLParam(r, "type"), &pType, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) - if err != nil { - siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "type", Err: err}) - return - } - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.ReservedGoKeywordParameters(w, r, pType) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -// ReusableResponses operation middleware -func (siw *ServerInterfaceWrapper) ReusableResponses(w http.ResponseWriter, r *http.Request) { - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.ReusableResponses(w, r) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -// TextExample operation middleware -func (siw *ServerInterfaceWrapper) TextExample(w http.ResponseWriter, r *http.Request) { - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.TextExample(w, r) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -// UnknownExample operation middleware -func (siw *ServerInterfaceWrapper) UnknownExample(w http.ResponseWriter, r *http.Request) { - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.UnknownExample(w, r) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -// UnspecifiedContentType operation middleware -func (siw *ServerInterfaceWrapper) UnspecifiedContentType(w http.ResponseWriter, r *http.Request) { - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.UnspecifiedContentType(w, r) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -// URLEncodedExample operation middleware -func (siw *ServerInterfaceWrapper) URLEncodedExample(w http.ResponseWriter, r *http.Request) { - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.URLEncodedExample(w, r) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -// HeadersExample operation middleware -func (siw *ServerInterfaceWrapper) HeadersExample(w http.ResponseWriter, r *http.Request) { - - var err error - - // Parameter object where we will unmarshal all parameters from the context - var params HeadersExampleParams - - headers := r.Header - - // ------------- Required header parameter "header1" ------------- - if valueList, found := headers[http.CanonicalHeaderKey("header1")]; found { - var Header1 string - n := len(valueList) - if n != 1 { - siw.ErrorHandlerFunc(w, r, &TooManyValuesForParamError{ParamName: "header1", Count: n}) - return - } - - err = runtime.BindStyledParameterWithOptions("simple", "header1", valueList[0], &Header1, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: true, Type: "string", Format: ""}) - if err != nil { - siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "header1", Err: err}) - return - } - - params.Header1 = Header1 - - } else { - err := fmt.Errorf("Header parameter header1 is required, but not found") - siw.ErrorHandlerFunc(w, r, &RequiredHeaderError{ParamName: "header1", Err: err}) - return - } - - // ------------- Optional header parameter "header2" ------------- - if valueList, found := headers[http.CanonicalHeaderKey("header2")]; found { - var Header2 int - n := len(valueList) - if n != 1 { - siw.ErrorHandlerFunc(w, r, &TooManyValuesForParamError{ParamName: "header2", Count: n}) - return - } - - err = runtime.BindStyledParameterWithOptions("simple", "header2", valueList[0], &Header2, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: ""}) - if err != nil { - siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "header2", Err: err}) - return - } - - params.Header2 = &Header2 - - } - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.HeadersExample(w, r, params) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -// UnionExample operation middleware -func (siw *ServerInterfaceWrapper) UnionExample(w http.ResponseWriter, r *http.Request) { - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.UnionExample(w, r) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -type UnescapedCookieParamError struct { - ParamName string - Err error -} - -func (e *UnescapedCookieParamError) Error() string { - return fmt.Sprintf("error unescaping cookie parameter '%s'", e.ParamName) -} - -func (e *UnescapedCookieParamError) Unwrap() error { - return e.Err -} - -type UnmarshalingParamError struct { - ParamName string - Err error -} - -func (e *UnmarshalingParamError) Error() string { - return fmt.Sprintf("Error unmarshaling parameter %s as JSON: %s", e.ParamName, e.Err.Error()) -} - -func (e *UnmarshalingParamError) Unwrap() error { - return e.Err -} - -type RequiredParamError struct { - ParamName string -} - -func (e *RequiredParamError) Error() string { - return fmt.Sprintf("Query argument %s is required, but not found", e.ParamName) -} - -type RequiredHeaderError struct { - ParamName string - Err error -} - -func (e *RequiredHeaderError) Error() string { - return fmt.Sprintf("Header parameter %s is required, but not found", e.ParamName) -} - -func (e *RequiredHeaderError) Unwrap() error { - return e.Err -} - -type InvalidParamFormatError struct { - ParamName string - Err error -} - -func (e *InvalidParamFormatError) Error() string { - return fmt.Sprintf("Invalid format for parameter %s: %s", e.ParamName, e.Err.Error()) -} - -func (e *InvalidParamFormatError) Unwrap() error { - return e.Err -} - -type TooManyValuesForParamError struct { - ParamName string - Count int -} - -func (e *TooManyValuesForParamError) Error() string { - return fmt.Sprintf("Expected one value for %s, got %d", e.ParamName, e.Count) -} - -// Handler creates http.Handler with routing matching OpenAPI spec. -func Handler(si ServerInterface) http.Handler { - return HandlerWithOptions(si, ChiServerOptions{}) -} - -type ChiServerOptions struct { - BaseURL string - BaseRouter chi.Router - Middlewares []MiddlewareFunc - ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) -} - -// HandlerFromMux creates http.Handler with routing matching OpenAPI spec based on the provided mux. -func HandlerFromMux(si ServerInterface, r chi.Router) http.Handler { - return HandlerWithOptions(si, ChiServerOptions{ - BaseRouter: r, - }) -} - -func HandlerFromMuxWithBaseURL(si ServerInterface, r chi.Router, baseURL string) http.Handler { - return HandlerWithOptions(si, ChiServerOptions{ - BaseURL: baseURL, - BaseRouter: r, - }) -} - -// HandlerWithOptions creates http.Handler with additional options -func HandlerWithOptions(si ServerInterface, options ChiServerOptions) http.Handler { - r := options.BaseRouter - - if r == nil { - r = chi.NewRouter() - } - if options.ErrorHandlerFunc == nil { - options.ErrorHandlerFunc = func(w http.ResponseWriter, r *http.Request, err error) { - http.Error(w, err.Error(), http.StatusBadRequest) - } - } - wrapper := ServerInterfaceWrapper{ - Handler: si, - HandlerMiddlewares: options.Middlewares, - ErrorHandlerFunc: options.ErrorHandlerFunc, - } - - r.Group(func(r chi.Router) { - r.Post(options.BaseURL+"/json", wrapper.JSONExample) - }) - r.Group(func(r chi.Router) { - r.Post(options.BaseURL+"/multipart", wrapper.MultipartExample) - }) - r.Group(func(r chi.Router) { - r.Post(options.BaseURL+"/multipart-related", wrapper.MultipartRelatedExample) - }) - r.Group(func(r chi.Router) { - r.Post(options.BaseURL+"/multiple", wrapper.MultipleRequestAndResponseTypes) - }) - r.Group(func(r chi.Router) { - r.Post(options.BaseURL+"/required-json-body", wrapper.RequiredJSONBody) - }) - r.Group(func(r chi.Router) { - r.Post(options.BaseURL+"/required-text-body", wrapper.RequiredTextBody) - }) - r.Group(func(r chi.Router) { - r.Get(options.BaseURL+"/reserved-go-keyword-parameters/{type}", wrapper.ReservedGoKeywordParameters) - }) - r.Group(func(r chi.Router) { - r.Post(options.BaseURL+"/reusable-responses", wrapper.ReusableResponses) - }) - r.Group(func(r chi.Router) { - r.Post(options.BaseURL+"/text", wrapper.TextExample) - }) - r.Group(func(r chi.Router) { - r.Post(options.BaseURL+"/unknown", wrapper.UnknownExample) - }) - r.Group(func(r chi.Router) { - r.Post(options.BaseURL+"/unspecified-content-type", wrapper.UnspecifiedContentType) - }) - r.Group(func(r chi.Router) { - r.Post(options.BaseURL+"/urlencoded", wrapper.URLEncodedExample) - }) - r.Group(func(r chi.Router) { - r.Post(options.BaseURL+"/with-headers", wrapper.HeadersExample) - }) - r.Group(func(r chi.Router) { - r.Post(options.BaseURL+"/with-union", wrapper.UnionExample) - }) - - return r -} - -type BadrequestResponse struct { -} - -type ReusableresponseResponseHeaders struct { - Header1 string - Header2 int -} -type ReusableresponseJSONResponse struct { - Body Example - - Headers ReusableresponseResponseHeaders -} - -type JSONExampleRequestObject struct { - Body *JSONExampleJSONRequestBody -} - -type JSONExampleResponseObject interface { - VisitJSONExampleResponse(w http.ResponseWriter) error -} - -type JSONExample200JSONResponse Example - -func (response JSONExample200JSONResponse) VisitJSONExampleResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(200) - - return json.NewEncoder(w).Encode(response) -} - -type JSONExample400Response = BadrequestResponse - -func (response JSONExample400Response) VisitJSONExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type JSONExampledefaultResponse struct { - StatusCode int -} - -func (response JSONExampledefaultResponse) VisitJSONExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -type MultipartExampleRequestObject struct { - Body *multipart.Reader -} - -type MultipartExampleResponseObject interface { - VisitMultipartExampleResponse(w http.ResponseWriter) error -} - -type MultipartExample200MultipartResponse func(writer *multipart.Writer) error - -func (response MultipartExample200MultipartResponse) VisitMultipartExampleResponse(w http.ResponseWriter) error { - writer := multipart.NewWriter(w) - w.Header().Set("Content-Type", writer.FormDataContentType()) - w.WriteHeader(200) - - defer writer.Close() - return response(writer) -} - -type MultipartExample400Response = BadrequestResponse - -func (response MultipartExample400Response) VisitMultipartExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type MultipartExampledefaultResponse struct { - StatusCode int -} - -func (response MultipartExampledefaultResponse) VisitMultipartExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -type MultipartRelatedExampleRequestObject struct { - Body *multipart.Reader -} - -type MultipartRelatedExampleResponseObject interface { - VisitMultipartRelatedExampleResponse(w http.ResponseWriter) error -} - -type MultipartRelatedExample200MultipartResponse func(writer *multipart.Writer) error - -func (response MultipartRelatedExample200MultipartResponse) VisitMultipartRelatedExampleResponse(w http.ResponseWriter) error { - writer := multipart.NewWriter(w) - w.Header().Set("Content-Type", mime.FormatMediaType("multipart/related", map[string]string{"boundary": writer.Boundary()})) - w.WriteHeader(200) - - defer writer.Close() - return response(writer) -} - -type MultipartRelatedExample400Response = BadrequestResponse - -func (response MultipartRelatedExample400Response) VisitMultipartRelatedExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type MultipartRelatedExampledefaultResponse struct { - StatusCode int -} - -func (response MultipartRelatedExampledefaultResponse) VisitMultipartRelatedExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -type MultipleRequestAndResponseTypesRequestObject struct { - JSONBody *MultipleRequestAndResponseTypesJSONRequestBody - FormdataBody *MultipleRequestAndResponseTypesFormdataRequestBody - Body io.Reader - MultipartBody *multipart.Reader - TextBody *MultipleRequestAndResponseTypesTextRequestBody -} - -type MultipleRequestAndResponseTypesResponseObject interface { - VisitMultipleRequestAndResponseTypesResponse(w http.ResponseWriter) error -} - -type MultipleRequestAndResponseTypes200JSONResponse Example - -func (response MultipleRequestAndResponseTypes200JSONResponse) VisitMultipleRequestAndResponseTypesResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(200) - - return json.NewEncoder(w).Encode(response) -} - -type MultipleRequestAndResponseTypes200FormdataResponse Example - -func (response MultipleRequestAndResponseTypes200FormdataResponse) VisitMultipleRequestAndResponseTypesResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/x-www-form-urlencoded") - w.WriteHeader(200) - - if form, err := runtime.MarshalForm(response, nil); err != nil { - return err - } else { - _, err := w.Write([]byte(form.Encode())) - return err - } -} - -type MultipleRequestAndResponseTypes200ImagepngResponse struct { - Body io.Reader - ContentLength int64 -} - -func (response MultipleRequestAndResponseTypes200ImagepngResponse) VisitMultipleRequestAndResponseTypesResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "image/png") - if response.ContentLength != 0 { - w.Header().Set("Content-Length", fmt.Sprint(response.ContentLength)) - } - w.WriteHeader(200) - - if closer, ok := response.Body.(io.ReadCloser); ok { - defer closer.Close() - } - _, err := io.Copy(w, response.Body) - return err -} - -type MultipleRequestAndResponseTypes200MultipartResponse func(writer *multipart.Writer) error - -func (response MultipleRequestAndResponseTypes200MultipartResponse) VisitMultipleRequestAndResponseTypesResponse(w http.ResponseWriter) error { - writer := multipart.NewWriter(w) - w.Header().Set("Content-Type", writer.FormDataContentType()) - w.WriteHeader(200) - - defer writer.Close() - return response(writer) -} - -type MultipleRequestAndResponseTypes200TextResponse string - -func (response MultipleRequestAndResponseTypes200TextResponse) VisitMultipleRequestAndResponseTypesResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "text/plain") - w.WriteHeader(200) - - _, err := w.Write([]byte(response)) - return err -} - -type MultipleRequestAndResponseTypes400Response = BadrequestResponse - -func (response MultipleRequestAndResponseTypes400Response) VisitMultipleRequestAndResponseTypesResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type RequiredJSONBodyRequestObject struct { - Body *RequiredJSONBodyJSONRequestBody -} - -type RequiredJSONBodyResponseObject interface { - VisitRequiredJSONBodyResponse(w http.ResponseWriter) error -} - -type RequiredJSONBody200JSONResponse Example - -func (response RequiredJSONBody200JSONResponse) VisitRequiredJSONBodyResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(200) - - return json.NewEncoder(w).Encode(response) -} - -type RequiredJSONBody400Response = BadrequestResponse - -func (response RequiredJSONBody400Response) VisitRequiredJSONBodyResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type RequiredJSONBodydefaultResponse struct { - StatusCode int -} - -func (response RequiredJSONBodydefaultResponse) VisitRequiredJSONBodyResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -type RequiredTextBodyRequestObject struct { - Body *RequiredTextBodyTextRequestBody -} - -type RequiredTextBodyResponseObject interface { - VisitRequiredTextBodyResponse(w http.ResponseWriter) error -} - -type RequiredTextBody200TextResponse string - -func (response RequiredTextBody200TextResponse) VisitRequiredTextBodyResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "text/plain") - w.WriteHeader(200) - - _, err := w.Write([]byte(response)) - return err -} - -type RequiredTextBody400Response = BadrequestResponse - -func (response RequiredTextBody400Response) VisitRequiredTextBodyResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type RequiredTextBodydefaultResponse struct { - StatusCode int -} - -func (response RequiredTextBodydefaultResponse) VisitRequiredTextBodyResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -type ReservedGoKeywordParametersRequestObject struct { - Type string `json:"type"` -} - -type ReservedGoKeywordParametersResponseObject interface { - VisitReservedGoKeywordParametersResponse(w http.ResponseWriter) error -} - -type ReservedGoKeywordParameters200TextResponse string - -func (response ReservedGoKeywordParameters200TextResponse) VisitReservedGoKeywordParametersResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "text/plain") - w.WriteHeader(200) - - _, err := w.Write([]byte(response)) - return err -} - -type ReusableResponsesRequestObject struct { - Body *ReusableResponsesJSONRequestBody -} - -type ReusableResponsesResponseObject interface { - VisitReusableResponsesResponse(w http.ResponseWriter) error -} - -type ReusableResponses200JSONResponse struct{ ReusableresponseJSONResponse } - -func (response ReusableResponses200JSONResponse) VisitReusableResponsesResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/json") - w.Header().Set("header1", fmt.Sprint(response.Headers.Header1)) - w.Header().Set("header2", fmt.Sprint(response.Headers.Header2)) - w.WriteHeader(200) - - return json.NewEncoder(w).Encode(response.Body) -} - -type ReusableResponses400Response = BadrequestResponse - -func (response ReusableResponses400Response) VisitReusableResponsesResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type ReusableResponsesdefaultResponse struct { - StatusCode int -} - -func (response ReusableResponsesdefaultResponse) VisitReusableResponsesResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -type TextExampleRequestObject struct { - Body *TextExampleTextRequestBody -} - -type TextExampleResponseObject interface { - VisitTextExampleResponse(w http.ResponseWriter) error -} - -type TextExample200TextResponse string - -func (response TextExample200TextResponse) VisitTextExampleResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "text/plain") - w.WriteHeader(200) - - _, err := w.Write([]byte(response)) - return err -} - -type TextExample400Response = BadrequestResponse - -func (response TextExample400Response) VisitTextExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type TextExampledefaultResponse struct { - StatusCode int -} - -func (response TextExampledefaultResponse) VisitTextExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -type UnknownExampleRequestObject struct { - Body io.Reader -} - -type UnknownExampleResponseObject interface { - VisitUnknownExampleResponse(w http.ResponseWriter) error -} - -type UnknownExample200Videomp4Response struct { - Body io.Reader - ContentLength int64 -} - -func (response UnknownExample200Videomp4Response) VisitUnknownExampleResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "video/mp4") - if response.ContentLength != 0 { - w.Header().Set("Content-Length", fmt.Sprint(response.ContentLength)) - } - w.WriteHeader(200) - - if closer, ok := response.Body.(io.ReadCloser); ok { - defer closer.Close() - } - _, err := io.Copy(w, response.Body) - return err -} - -type UnknownExample400Response = BadrequestResponse - -func (response UnknownExample400Response) VisitUnknownExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type UnknownExampledefaultResponse struct { - StatusCode int -} - -func (response UnknownExampledefaultResponse) VisitUnknownExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -type UnspecifiedContentTypeRequestObject struct { - ContentType string - Body io.Reader -} - -type UnspecifiedContentTypeResponseObject interface { - VisitUnspecifiedContentTypeResponse(w http.ResponseWriter) error -} - -type UnspecifiedContentType200VideoResponse struct { - Body io.Reader - ContentType string - ContentLength int64 -} - -func (response UnspecifiedContentType200VideoResponse) VisitUnspecifiedContentTypeResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", response.ContentType) - if response.ContentLength != 0 { - w.Header().Set("Content-Length", fmt.Sprint(response.ContentLength)) - } - w.WriteHeader(200) - - if closer, ok := response.Body.(io.ReadCloser); ok { - defer closer.Close() - } - _, err := io.Copy(w, response.Body) - return err -} - -type UnspecifiedContentType400Response = BadrequestResponse - -func (response UnspecifiedContentType400Response) VisitUnspecifiedContentTypeResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type UnspecifiedContentType401Response struct { -} - -func (response UnspecifiedContentType401Response) VisitUnspecifiedContentTypeResponse(w http.ResponseWriter) error { - w.WriteHeader(401) - return nil -} - -type UnspecifiedContentType403Response struct { -} - -func (response UnspecifiedContentType403Response) VisitUnspecifiedContentTypeResponse(w http.ResponseWriter) error { - w.WriteHeader(403) - return nil -} - -type UnspecifiedContentTypedefaultResponse struct { - StatusCode int -} - -func (response UnspecifiedContentTypedefaultResponse) VisitUnspecifiedContentTypeResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -type URLEncodedExampleRequestObject struct { - Body *URLEncodedExampleFormdataRequestBody -} - -type URLEncodedExampleResponseObject interface { - VisitURLEncodedExampleResponse(w http.ResponseWriter) error -} - -type URLEncodedExample200FormdataResponse Example - -func (response URLEncodedExample200FormdataResponse) VisitURLEncodedExampleResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/x-www-form-urlencoded") - w.WriteHeader(200) - - if form, err := runtime.MarshalForm(response, nil); err != nil { - return err - } else { - _, err := w.Write([]byte(form.Encode())) - return err - } -} - -type URLEncodedExample400Response = BadrequestResponse - -func (response URLEncodedExample400Response) VisitURLEncodedExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type URLEncodedExampledefaultResponse struct { - StatusCode int -} - -func (response URLEncodedExampledefaultResponse) VisitURLEncodedExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -type HeadersExampleRequestObject struct { - Params HeadersExampleParams - Body *HeadersExampleJSONRequestBody -} - -type HeadersExampleResponseObject interface { - VisitHeadersExampleResponse(w http.ResponseWriter) error -} - -type HeadersExample200ResponseHeaders struct { - Header1 string - Header2 int -} - -type HeadersExample200JSONResponse struct { - Body Example - Headers HeadersExample200ResponseHeaders -} - -func (response HeadersExample200JSONResponse) VisitHeadersExampleResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/json") - w.Header().Set("header1", fmt.Sprint(response.Headers.Header1)) - w.Header().Set("header2", fmt.Sprint(response.Headers.Header2)) - w.WriteHeader(200) - - return json.NewEncoder(w).Encode(response.Body) -} - -type HeadersExample400Response = BadrequestResponse - -func (response HeadersExample400Response) VisitHeadersExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type HeadersExampledefaultResponse struct { - StatusCode int -} - -func (response HeadersExampledefaultResponse) VisitHeadersExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -type UnionExampleRequestObject struct { - Body *UnionExampleJSONRequestBody -} - -type UnionExampleResponseObject interface { - VisitUnionExampleResponse(w http.ResponseWriter) error -} - -type UnionExample200ResponseHeaders struct { - Header1 string - Header2 int -} - -type UnionExample200ApplicationAlternativePlusJSONResponse struct { - Body Example - Headers UnionExample200ResponseHeaders -} - -func (response UnionExample200ApplicationAlternativePlusJSONResponse) VisitUnionExampleResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/alternative+json") - w.Header().Set("header1", fmt.Sprint(response.Headers.Header1)) - w.Header().Set("header2", fmt.Sprint(response.Headers.Header2)) - w.WriteHeader(200) - - return json.NewEncoder(w).Encode(response.Body) -} - -type UnionExample200JSONResponse struct { - Body struct { - union json.RawMessage - } - Headers UnionExample200ResponseHeaders -} - -func (response UnionExample200JSONResponse) VisitUnionExampleResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/json") - w.Header().Set("header1", fmt.Sprint(response.Headers.Header1)) - w.Header().Set("header2", fmt.Sprint(response.Headers.Header2)) - w.WriteHeader(200) - - return json.NewEncoder(w).Encode(response.Body.union) -} - -type UnionExample400Response = BadrequestResponse - -func (response UnionExample400Response) VisitUnionExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type UnionExampledefaultResponse struct { - StatusCode int -} - -func (response UnionExampledefaultResponse) VisitUnionExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -// StrictServerInterface represents all server handlers. -type StrictServerInterface interface { - - // (POST /json) - JSONExample(ctx context.Context, request JSONExampleRequestObject) (JSONExampleResponseObject, error) - - // (POST /multipart) - MultipartExample(ctx context.Context, request MultipartExampleRequestObject) (MultipartExampleResponseObject, error) - - // (POST /multipart-related) - MultipartRelatedExample(ctx context.Context, request MultipartRelatedExampleRequestObject) (MultipartRelatedExampleResponseObject, error) - - // (POST /multiple) - MultipleRequestAndResponseTypes(ctx context.Context, request MultipleRequestAndResponseTypesRequestObject) (MultipleRequestAndResponseTypesResponseObject, error) - - // (POST /required-json-body) - RequiredJSONBody(ctx context.Context, request RequiredJSONBodyRequestObject) (RequiredJSONBodyResponseObject, error) - - // (POST /required-text-body) - RequiredTextBody(ctx context.Context, request RequiredTextBodyRequestObject) (RequiredTextBodyResponseObject, error) - - // (GET /reserved-go-keyword-parameters/{type}) - ReservedGoKeywordParameters(ctx context.Context, request ReservedGoKeywordParametersRequestObject) (ReservedGoKeywordParametersResponseObject, error) - - // (POST /reusable-responses) - ReusableResponses(ctx context.Context, request ReusableResponsesRequestObject) (ReusableResponsesResponseObject, error) - - // (POST /text) - TextExample(ctx context.Context, request TextExampleRequestObject) (TextExampleResponseObject, error) - - // (POST /unknown) - UnknownExample(ctx context.Context, request UnknownExampleRequestObject) (UnknownExampleResponseObject, error) - - // (POST /unspecified-content-type) - UnspecifiedContentType(ctx context.Context, request UnspecifiedContentTypeRequestObject) (UnspecifiedContentTypeResponseObject, error) - - // (POST /urlencoded) - URLEncodedExample(ctx context.Context, request URLEncodedExampleRequestObject) (URLEncodedExampleResponseObject, error) - - // (POST /with-headers) - HeadersExample(ctx context.Context, request HeadersExampleRequestObject) (HeadersExampleResponseObject, error) - - // (POST /with-union) - UnionExample(ctx context.Context, request UnionExampleRequestObject) (UnionExampleResponseObject, error) -} - -type StrictHandlerFunc = strictnethttp.StrictHTTPHandlerFunc -type StrictMiddlewareFunc = strictnethttp.StrictHTTPMiddlewareFunc - -type StrictHTTPServerOptions struct { - RequestErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) - ResponseErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) -} - -func NewStrictHandler(ssi StrictServerInterface, middlewares []StrictMiddlewareFunc) ServerInterface { - return &strictHandler{ssi: ssi, middlewares: middlewares, options: StrictHTTPServerOptions{ - RequestErrorHandlerFunc: func(w http.ResponseWriter, r *http.Request, err error) { - http.Error(w, err.Error(), http.StatusBadRequest) - }, - ResponseErrorHandlerFunc: func(w http.ResponseWriter, r *http.Request, err error) { - http.Error(w, err.Error(), http.StatusInternalServerError) - }, - }} -} - -func NewStrictHandlerWithOptions(ssi StrictServerInterface, middlewares []StrictMiddlewareFunc, options StrictHTTPServerOptions) ServerInterface { - return &strictHandler{ssi: ssi, middlewares: middlewares, options: options} -} - -type strictHandler struct { - ssi StrictServerInterface - middlewares []StrictMiddlewareFunc - options StrictHTTPServerOptions -} - -// JSONExample operation middleware -func (sh *strictHandler) JSONExample(w http.ResponseWriter, r *http.Request) { - var request JSONExampleRequestObject - - var body JSONExampleJSONRequestBody - if err := json.NewDecoder(r.Body).Decode(&body); err != nil { - if !errors.Is(err, io.EOF) { - sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't decode JSON body: %w", err)) - return - } - } else { - request.Body = &body - } - - handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { - return sh.ssi.JSONExample(ctx, request.(JSONExampleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "JSONExample") - } - - response, err := handler(r.Context(), w, r, request) - - if err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } else if validResponse, ok := response.(JSONExampleResponseObject); ok { - if err := validResponse.VisitJSONExampleResponse(w); err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } - } else if response != nil { - sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) - } -} - -// MultipartExample operation middleware -func (sh *strictHandler) MultipartExample(w http.ResponseWriter, r *http.Request) { - var request MultipartExampleRequestObject - - if reader, err := r.MultipartReader(); err != nil { - sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't decode multipart body: %w", err)) - return - } else { - request.Body = reader - } - - handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { - return sh.ssi.MultipartExample(ctx, request.(MultipartExampleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "MultipartExample") - } - - response, err := handler(r.Context(), w, r, request) - - if err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } else if validResponse, ok := response.(MultipartExampleResponseObject); ok { - if err := validResponse.VisitMultipartExampleResponse(w); err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } - } else if response != nil { - sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) - } -} - -// MultipartRelatedExample operation middleware -func (sh *strictHandler) MultipartRelatedExample(w http.ResponseWriter, r *http.Request) { - var request MultipartRelatedExampleRequestObject - - if _, params, err := mime.ParseMediaType(r.Header.Get("Content-Type")); err != nil { - sh.options.RequestErrorHandlerFunc(w, r, err) - return - } else if boundary := params["boundary"]; boundary == "" { - sh.options.RequestErrorHandlerFunc(w, r, http.ErrMissingBoundary) - return - } else { - request.Body = multipart.NewReader(r.Body, boundary) - } - - handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { - return sh.ssi.MultipartRelatedExample(ctx, request.(MultipartRelatedExampleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "MultipartRelatedExample") - } - - response, err := handler(r.Context(), w, r, request) - - if err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } else if validResponse, ok := response.(MultipartRelatedExampleResponseObject); ok { - if err := validResponse.VisitMultipartRelatedExampleResponse(w); err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } - } else if response != nil { - sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) - } -} - -// MultipleRequestAndResponseTypes operation middleware -func (sh *strictHandler) MultipleRequestAndResponseTypes(w http.ResponseWriter, r *http.Request) { - var request MultipleRequestAndResponseTypesRequestObject - - if strings.HasPrefix(r.Header.Get("Content-Type"), "application/json") { - - var body MultipleRequestAndResponseTypesJSONRequestBody - if err := json.NewDecoder(r.Body).Decode(&body); err != nil { - if !errors.Is(err, io.EOF) { - sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't decode JSON body: %w", err)) - return - } - } else { - request.JSONBody = &body - } - } - if strings.HasPrefix(r.Header.Get("Content-Type"), "application/x-www-form-urlencoded") { - if err := r.ParseForm(); err != nil { - sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't decode formdata: %w", err)) - return - } - var body MultipleRequestAndResponseTypesFormdataRequestBody - if err := runtime.BindForm(&body, r.Form, nil, nil); err != nil { - sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't bind formdata: %w", err)) - return - } - request.FormdataBody = &body - } - if strings.HasPrefix(r.Header.Get("Content-Type"), "image/png") { - request.Body = r.Body - } - if strings.HasPrefix(r.Header.Get("Content-Type"), "multipart/form-data") { - if reader, err := r.MultipartReader(); err != nil { - sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't decode multipart body: %w", err)) - return - } else { - request.MultipartBody = reader - } - } - if strings.HasPrefix(r.Header.Get("Content-Type"), "text/plain") { - data, err := io.ReadAll(r.Body) - if err != nil { - sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't read body: %w", err)) - return - } - if len(data) > 0 { - body := MultipleRequestAndResponseTypesTextRequestBody(data) - request.TextBody = &body - } - } - - handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { - return sh.ssi.MultipleRequestAndResponseTypes(ctx, request.(MultipleRequestAndResponseTypesRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "MultipleRequestAndResponseTypes") - } - - response, err := handler(r.Context(), w, r, request) - - if err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } else if validResponse, ok := response.(MultipleRequestAndResponseTypesResponseObject); ok { - if err := validResponse.VisitMultipleRequestAndResponseTypesResponse(w); err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } - } else if response != nil { - sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) - } -} - -// RequiredJSONBody operation middleware -func (sh *strictHandler) RequiredJSONBody(w http.ResponseWriter, r *http.Request) { - var request RequiredJSONBodyRequestObject - - var body RequiredJSONBodyJSONRequestBody - if err := json.NewDecoder(r.Body).Decode(&body); err != nil { - sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't decode JSON body: %w", err)) - return - } - request.Body = &body - - handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { - return sh.ssi.RequiredJSONBody(ctx, request.(RequiredJSONBodyRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "RequiredJSONBody") - } - - response, err := handler(r.Context(), w, r, request) - - if err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } else if validResponse, ok := response.(RequiredJSONBodyResponseObject); ok { - if err := validResponse.VisitRequiredJSONBodyResponse(w); err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } - } else if response != nil { - sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) - } -} - -// RequiredTextBody operation middleware -func (sh *strictHandler) RequiredTextBody(w http.ResponseWriter, r *http.Request) { - var request RequiredTextBodyRequestObject - - data, err := io.ReadAll(r.Body) - if err != nil { - sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't read body: %w", err)) - return - } - body := RequiredTextBodyTextRequestBody(data) - request.Body = &body - - handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { - return sh.ssi.RequiredTextBody(ctx, request.(RequiredTextBodyRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "RequiredTextBody") - } - - response, err := handler(r.Context(), w, r, request) - - if err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } else if validResponse, ok := response.(RequiredTextBodyResponseObject); ok { - if err := validResponse.VisitRequiredTextBodyResponse(w); err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } - } else if response != nil { - sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) - } -} - -// ReservedGoKeywordParameters operation middleware -func (sh *strictHandler) ReservedGoKeywordParameters(w http.ResponseWriter, r *http.Request, pType string) { - var request ReservedGoKeywordParametersRequestObject - - request.Type = pType - - handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { - return sh.ssi.ReservedGoKeywordParameters(ctx, request.(ReservedGoKeywordParametersRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "ReservedGoKeywordParameters") - } - - response, err := handler(r.Context(), w, r, request) - - if err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } else if validResponse, ok := response.(ReservedGoKeywordParametersResponseObject); ok { - if err := validResponse.VisitReservedGoKeywordParametersResponse(w); err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } - } else if response != nil { - sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) - } -} - -// ReusableResponses operation middleware -func (sh *strictHandler) ReusableResponses(w http.ResponseWriter, r *http.Request) { - var request ReusableResponsesRequestObject - - var body ReusableResponsesJSONRequestBody - if err := json.NewDecoder(r.Body).Decode(&body); err != nil { - if !errors.Is(err, io.EOF) { - sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't decode JSON body: %w", err)) - return - } - } else { - request.Body = &body - } - - handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { - return sh.ssi.ReusableResponses(ctx, request.(ReusableResponsesRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "ReusableResponses") - } - - response, err := handler(r.Context(), w, r, request) - - if err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } else if validResponse, ok := response.(ReusableResponsesResponseObject); ok { - if err := validResponse.VisitReusableResponsesResponse(w); err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } - } else if response != nil { - sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) - } -} - -// TextExample operation middleware -func (sh *strictHandler) TextExample(w http.ResponseWriter, r *http.Request) { - var request TextExampleRequestObject - - data, err := io.ReadAll(r.Body) - if err != nil { - sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't read body: %w", err)) - return - } - if len(data) > 0 { - body := TextExampleTextRequestBody(data) - request.Body = &body - } - - handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { - return sh.ssi.TextExample(ctx, request.(TextExampleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "TextExample") - } - - response, err := handler(r.Context(), w, r, request) - - if err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } else if validResponse, ok := response.(TextExampleResponseObject); ok { - if err := validResponse.VisitTextExampleResponse(w); err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } - } else if response != nil { - sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) - } -} - -// UnknownExample operation middleware -func (sh *strictHandler) UnknownExample(w http.ResponseWriter, r *http.Request) { - var request UnknownExampleRequestObject - - request.Body = r.Body - - handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { - return sh.ssi.UnknownExample(ctx, request.(UnknownExampleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "UnknownExample") - } - - response, err := handler(r.Context(), w, r, request) - - if err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } else if validResponse, ok := response.(UnknownExampleResponseObject); ok { - if err := validResponse.VisitUnknownExampleResponse(w); err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } - } else if response != nil { - sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) - } -} - -// UnspecifiedContentType operation middleware -func (sh *strictHandler) UnspecifiedContentType(w http.ResponseWriter, r *http.Request) { - var request UnspecifiedContentTypeRequestObject - - request.ContentType = r.Header.Get("Content-Type") - - request.Body = r.Body - - handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { - return sh.ssi.UnspecifiedContentType(ctx, request.(UnspecifiedContentTypeRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "UnspecifiedContentType") - } - - response, err := handler(r.Context(), w, r, request) - - if err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } else if validResponse, ok := response.(UnspecifiedContentTypeResponseObject); ok { - if err := validResponse.VisitUnspecifiedContentTypeResponse(w); err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } - } else if response != nil { - sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) - } -} - -// URLEncodedExample operation middleware -func (sh *strictHandler) URLEncodedExample(w http.ResponseWriter, r *http.Request) { - var request URLEncodedExampleRequestObject - - if err := r.ParseForm(); err != nil { - sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't decode formdata: %w", err)) - return - } - var body URLEncodedExampleFormdataRequestBody - if err := runtime.BindForm(&body, r.Form, nil, nil); err != nil { - sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't bind formdata: %w", err)) - return - } - request.Body = &body - - handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { - return sh.ssi.URLEncodedExample(ctx, request.(URLEncodedExampleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "URLEncodedExample") - } - - response, err := handler(r.Context(), w, r, request) - - if err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } else if validResponse, ok := response.(URLEncodedExampleResponseObject); ok { - if err := validResponse.VisitURLEncodedExampleResponse(w); err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } - } else if response != nil { - sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) - } -} - -// HeadersExample operation middleware -func (sh *strictHandler) HeadersExample(w http.ResponseWriter, r *http.Request, params HeadersExampleParams) { - var request HeadersExampleRequestObject - - request.Params = params - - var body HeadersExampleJSONRequestBody - if err := json.NewDecoder(r.Body).Decode(&body); err != nil { - if !errors.Is(err, io.EOF) { - sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't decode JSON body: %w", err)) - return - } - } else { - request.Body = &body - } - - handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { - return sh.ssi.HeadersExample(ctx, request.(HeadersExampleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "HeadersExample") - } - - response, err := handler(r.Context(), w, r, request) - - if err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } else if validResponse, ok := response.(HeadersExampleResponseObject); ok { - if err := validResponse.VisitHeadersExampleResponse(w); err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } - } else if response != nil { - sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) - } -} - -// UnionExample operation middleware -func (sh *strictHandler) UnionExample(w http.ResponseWriter, r *http.Request) { - var request UnionExampleRequestObject - - var body UnionExampleJSONRequestBody - if err := json.NewDecoder(r.Body).Decode(&body); err != nil { - if !errors.Is(err, io.EOF) { - sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't decode JSON body: %w", err)) - return - } - } else { - request.Body = &body - } - - handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { - return sh.ssi.UnionExample(ctx, request.(UnionExampleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "UnionExample") - } - - response, err := handler(r.Context(), w, r, request) - - if err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } else if validResponse, ok := response.(UnionExampleResponseObject); ok { - if err := validResponse.VisitUnionExampleResponse(w); err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } - } else if response != nil { - sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) - } -} - -// Base64 encoded, gzipped, json marshaled Swagger object -var swaggerSpec = []string{ - - "H4sIAAAAAAAC/+xZTXPbNhP+Kzt431NKmrbjE2+NJ5O2aeuObJ86PkDESkJCAiiwFK3R6L93QEBfFq1K", - "qT4ynt5Ecr/wPLuLBTRlha6MVqjIsXzKLDqjlcP2oc+Fxb9qdOSfBLrCSkNSK5azD1z04rdZwizWjvdL", - "nKt7+UIrQtWqcmNKWXCvmn1xXn/KXDHCivtf/7c4YDn7X7YMJQtfXYbPvDIlstlslryI4O4zS9gIuUDb", - "Rht+Xq3bpolBljNHVqoh80aC2HWnmFSEQ7TemxeNQXiBeRz5lBmrDVqSAaMxL2vs9hTf6P4XLCisQKqB", - "3sTyViviUjkQcjBAi4ogggfehgNXG6MtoYD+BLyHgsChHaNlCSNJPjB2v/oeYsCOJWyM1gVHVxeXF5ee", - "L21QcSNZzt63rxJmOI3aBS0IMrqL91/u734H6YDXpCtOsuBlOYGKWzfiJQqQirQPsS7IXbDWk22J/1lE", - "7Y8RSp81bQJ90GJyjIRp83Ilna8vL0+Ul7OE3QRnXTYWQWUrBdaaGfC67MD8UX1VulGA1mobV5ZVdUnS", - "cEurXK2j/dtcZBfIF/aygbZVKjjxI6F+KE/nBj61WHJCsQMBvSC5Hw8r5o/Kwr/xc1YOYj/u7FP3I904", - "GOkGSINAXkIjaQRzxRcNVirg4KQalgjzoJJOMkuM296PSvTiWh68jaP3s2TNynPaNE3aFlBtS1SFFt9G", - "YcJkxYeYGTVcV/e2ObGc9SfkU3ZzgztQISeM8JkyU3Kptu/eJ2rp/yF9sMIO5eofpUWRekbSfqyP7sKN", - "5QVeyg8ac90EnIZKOl+l4aMb6boUwMuGT1zoD5sTRy+q+8mjLcyjjx3BgffJcrI1vu0xZEGtz6zzUPuA", - "z/SP1O6R+PvSd+qa2p+i9kwg0qFOv+Kk0VakhlteIaF12dTHOfO2hthh8o+FJBRcQR9B8QoF8AGhhU8a", - "oknXwU/w+0l/DiJLU+2BY/GQ/zllHrz2EMIS5h2wPOD3ko5kC8BPx6VqjmY46qZrrl5L+Cgyh87iwPmB", - "pIvjDvyCp96KxHmOTNtzc+Pwf4qk9ky+Pnj7lrDLsH3AweN77wJ1ePk6ZlFrF9i+cY7ZAcWxFKizytzs", - "aflsoDqDhRxIFGlcRRpie60l3GpVWKT1A4jfDJUmWBiD/gRohBAQaPfHBqGqHYHhzoGktouUMtwVCdxo", - "Ho/LyG6Dp4dlO93G6rsjcfruXIzeXF7tr/L+yHmzdpB4pR57v34MMvvemB3sxLLneetwfs9Uzo2kUbpy", - "pdxdwj8FgeWeXqAc+4lICbBItVUoYCz5/Bp0ozajgSWtXbNQCGM5Dc2vt/cZiJKttq5Zsu0K/OkNX9Ae", - "84+DU+VpreS2i/pH/xniDP1yb5BafafX8LwktIqTHOMPh7m/2bSiFd4N2kp7wXKyo4ent5dVs4SFf45C", - "C6pt6fsEkcmzLPzjdOEaPhyivZA640Z6FP4OAAD//0nTejA+HAAA", -} - -// GetSwagger returns the content of the embedded swagger specification file -// or error if failed to decode -func decodeSpec() ([]byte, error) { - zipped, err := base64.StdEncoding.DecodeString(strings.Join(swaggerSpec, "")) - if err != nil { - return nil, fmt.Errorf("error base64 decoding spec: %w", err) - } - zr, err := gzip.NewReader(bytes.NewReader(zipped)) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - var buf bytes.Buffer - _, err = buf.ReadFrom(zr) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - - return buf.Bytes(), nil -} - -var rawSpec = decodeSpecCached() - -// a naive cached of a decoded swagger spec -func decodeSpecCached() func() ([]byte, error) { - data, err := decodeSpec() - return func() ([]byte, error) { - return data, err - } -} - -// Constructs a synthetic filesystem for resolving external references when loading openapi specifications. -func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { - res := make(map[string]func() ([]byte, error)) - if len(pathToFile) > 0 { - res[pathToFile] = rawSpec - } - - return res -} - -// GetSwagger returns the Swagger specification corresponding to the generated code -// in this file. The external references of Swagger specification are resolved. -// The logic of resolving external references is tightly connected to "import-mapping" feature. -// Externally referenced files must be embedded in the corresponding golang packages. -// Urls can be supported but this task was out of the scope. -func GetSwagger() (swagger *openapi3.T, err error) { - resolvePath := PathToRawSpec("") - - loader := openapi3.NewLoader() - loader.IsExternalRefsAllowed = true - loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() - pathToFile = path.Clean(pathToFile) - getSpec, ok := resolvePath[pathToFile] - if !ok { - err1 := fmt.Errorf("path not found: %s", pathToFile) - return nil, err1 - } - return getSpec() - } - var specData []byte - specData, err = rawSpec() - if err != nil { - return - } - swagger, err = loader.LoadFromData(specData) - if err != nil { - return - } - return -} diff --git a/internal/test/strict-server/chi/server.go b/internal/test/strict-server/chi/server.go deleted file mode 100644 index 914f967268..0000000000 --- a/internal/test/strict-server/chi/server.go +++ /dev/null @@ -1,152 +0,0 @@ -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=server.cfg.yaml ../strict-schema.yaml -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=types.cfg.yaml ../strict-schema.yaml - -package api - -import ( - "context" - "encoding/json" - "io" - "mime/multipart" -) - -type StrictServer struct { -} - -func (s StrictServer) JSONExample(ctx context.Context, request JSONExampleRequestObject) (JSONExampleResponseObject, error) { - return JSONExample200JSONResponse(*request.Body), nil -} - -func (s StrictServer) MultipartExample(ctx context.Context, request MultipartExampleRequestObject) (MultipartExampleResponseObject, error) { - return MultipartExample200MultipartResponse(func(writer *multipart.Writer) error { - for { - part, err := request.Body.NextPart() - if err == io.EOF { - return nil - } else if err != nil { - return err - } - w, err := writer.CreatePart(part.Header) - if err != nil { - return err - } - _, err = io.Copy(w, part) - if err != nil { - return err - } - if err = part.Close(); err != nil { - return err - } - } - }), nil -} - -func (s StrictServer) MultipartRelatedExample(ctx context.Context, request MultipartRelatedExampleRequestObject) (MultipartRelatedExampleResponseObject, error) { - return MultipartRelatedExample200MultipartResponse(func(writer *multipart.Writer) error { - for { - part, err := request.Body.NextPart() - if err == io.EOF { - return nil - } else if err != nil { - return err - } - w, err := writer.CreatePart(part.Header) - if err != nil { - return err - } - _, err = io.Copy(w, part) - if err != nil { - return err - } - if err = part.Close(); err != nil { - return err - } - } - }), nil -} - -func (s StrictServer) MultipleRequestAndResponseTypes(ctx context.Context, request MultipleRequestAndResponseTypesRequestObject) (MultipleRequestAndResponseTypesResponseObject, error) { - switch { - case request.Body != nil: - return MultipleRequestAndResponseTypes200ImagepngResponse{Body: request.Body}, nil - case request.JSONBody != nil: - return MultipleRequestAndResponseTypes200JSONResponse(*request.JSONBody), nil - case request.FormdataBody != nil: - return MultipleRequestAndResponseTypes200FormdataResponse(*request.FormdataBody), nil - case request.TextBody != nil: - return MultipleRequestAndResponseTypes200TextResponse(*request.TextBody), nil - case request.MultipartBody != nil: - return MultipleRequestAndResponseTypes200MultipartResponse(func(writer *multipart.Writer) error { - for { - part, err := request.MultipartBody.NextPart() - if err == io.EOF { - return nil - } else if err != nil { - return err - } - w, err := writer.CreatePart(part.Header) - if err != nil { - return err - } - _, err = io.Copy(w, part) - if err != nil { - return err - } - if err = part.Close(); err != nil { - return err - } - } - }), nil - default: - return MultipleRequestAndResponseTypes400Response{}, nil - } -} - -func (s StrictServer) TextExample(ctx context.Context, request TextExampleRequestObject) (TextExampleResponseObject, error) { - return TextExample200TextResponse(*request.Body), nil -} - -func (s StrictServer) UnknownExample(ctx context.Context, request UnknownExampleRequestObject) (UnknownExampleResponseObject, error) { - return UnknownExample200Videomp4Response{Body: request.Body}, nil -} - -func (s StrictServer) UnspecifiedContentType(ctx context.Context, request UnspecifiedContentTypeRequestObject) (UnspecifiedContentTypeResponseObject, error) { - return UnspecifiedContentType200VideoResponse{Body: request.Body, ContentType: request.ContentType}, nil -} - -func (s StrictServer) URLEncodedExample(ctx context.Context, request URLEncodedExampleRequestObject) (URLEncodedExampleResponseObject, error) { - return URLEncodedExample200FormdataResponse(*request.Body), nil -} - -func (s StrictServer) HeadersExample(ctx context.Context, request HeadersExampleRequestObject) (HeadersExampleResponseObject, error) { - return HeadersExample200JSONResponse{Body: *request.Body, Headers: HeadersExample200ResponseHeaders{Header1: request.Params.Header1, Header2: *request.Params.Header2}}, nil -} - -func (s StrictServer) ReusableResponses(ctx context.Context, request ReusableResponsesRequestObject) (ReusableResponsesResponseObject, error) { - return ReusableResponses200JSONResponse{ReusableresponseJSONResponse: ReusableresponseJSONResponse{Body: *request.Body}}, nil -} - -func (s StrictServer) RequiredJSONBody(ctx context.Context, request RequiredJSONBodyRequestObject) (RequiredJSONBodyResponseObject, error) { - return RequiredJSONBody200JSONResponse(*request.Body), nil -} - -func (s StrictServer) RequiredTextBody(ctx context.Context, request RequiredTextBodyRequestObject) (RequiredTextBodyResponseObject, error) { - return RequiredTextBody200TextResponse(*request.Body), nil -} - -func (s StrictServer) ReservedGoKeywordParameters(ctx context.Context, request ReservedGoKeywordParametersRequestObject) (ReservedGoKeywordParametersResponseObject, error) { - return ReservedGoKeywordParameters200TextResponse(""), nil -} - -func (s StrictServer) UnionExample(ctx context.Context, request UnionExampleRequestObject) (UnionExampleResponseObject, error) { - union, err := json.Marshal(*request.Body) - if err != nil { - return nil, err - } - - return UnionExample200JSONResponse{ - Body: struct{ union json.RawMessage }{ - union: union, - }, - }, nil -} diff --git a/internal/test/strict-server/chi/types.gen.go b/internal/test/strict-server/chi/types.gen.go deleted file mode 100644 index fac014c4bb..0000000000 --- a/internal/test/strict-server/chi/types.gen.go +++ /dev/null @@ -1,69 +0,0 @@ -// Package api provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package api - -// Example defines model for example. -type Example struct { - Value *string `json:"value,omitempty"` -} - -// Reusableresponse defines model for reusableresponse. -type Reusableresponse = Example - -// MultipleRequestAndResponseTypesTextBody defines parameters for MultipleRequestAndResponseTypes. -type MultipleRequestAndResponseTypesTextBody = string - -// RequiredTextBodyTextBody defines parameters for RequiredTextBody. -type RequiredTextBodyTextBody = string - -// TextExampleTextBody defines parameters for TextExample. -type TextExampleTextBody = string - -// HeadersExampleParams defines parameters for HeadersExample. -type HeadersExampleParams struct { - Header1 string `json:"header1"` - Header2 *int `json:"header2,omitempty"` -} - -// JSONExampleJSONRequestBody defines body for JSONExample for application/json ContentType. -type JSONExampleJSONRequestBody = Example - -// MultipartExampleMultipartRequestBody defines body for MultipartExample for multipart/form-data ContentType. -type MultipartExampleMultipartRequestBody = Example - -// MultipartRelatedExampleMultipartRequestBody defines body for MultipartRelatedExample for multipart/related ContentType. -type MultipartRelatedExampleMultipartRequestBody = Example - -// MultipleRequestAndResponseTypesJSONRequestBody defines body for MultipleRequestAndResponseTypes for application/json ContentType. -type MultipleRequestAndResponseTypesJSONRequestBody = Example - -// MultipleRequestAndResponseTypesFormdataRequestBody defines body for MultipleRequestAndResponseTypes for application/x-www-form-urlencoded ContentType. -type MultipleRequestAndResponseTypesFormdataRequestBody = Example - -// MultipleRequestAndResponseTypesMultipartRequestBody defines body for MultipleRequestAndResponseTypes for multipart/form-data ContentType. -type MultipleRequestAndResponseTypesMultipartRequestBody = Example - -// MultipleRequestAndResponseTypesTextRequestBody defines body for MultipleRequestAndResponseTypes for text/plain ContentType. -type MultipleRequestAndResponseTypesTextRequestBody = MultipleRequestAndResponseTypesTextBody - -// RequiredJSONBodyJSONRequestBody defines body for RequiredJSONBody for application/json ContentType. -type RequiredJSONBodyJSONRequestBody = Example - -// RequiredTextBodyTextRequestBody defines body for RequiredTextBody for text/plain ContentType. -type RequiredTextBodyTextRequestBody = RequiredTextBodyTextBody - -// ReusableResponsesJSONRequestBody defines body for ReusableResponses for application/json ContentType. -type ReusableResponsesJSONRequestBody = Example - -// TextExampleTextRequestBody defines body for TextExample for text/plain ContentType. -type TextExampleTextRequestBody = TextExampleTextBody - -// URLEncodedExampleFormdataRequestBody defines body for URLEncodedExample for application/x-www-form-urlencoded ContentType. -type URLEncodedExampleFormdataRequestBody = Example - -// HeadersExampleJSONRequestBody defines body for HeadersExample for application/json ContentType. -type HeadersExampleJSONRequestBody = Example - -// UnionExampleJSONRequestBody defines body for UnionExample for application/json ContentType. -type UnionExampleJSONRequestBody = Example diff --git a/internal/test/strict-server/client/client.cfg.yaml b/internal/test/strict-server/client/client.cfg.yaml deleted file mode 100644 index 8437bde142..0000000000 --- a/internal/test/strict-server/client/client.cfg.yaml +++ /dev/null @@ -1,6 +0,0 @@ -# yaml-language-server: $schema=../../../../configuration-schema.json -package: api -generate: - models: true - client: true -output: client.gen.go diff --git a/internal/test/strict-server/client/client.gen.go b/internal/test/strict-server/client/client.gen.go deleted file mode 100644 index b189ff5adf..0000000000 --- a/internal/test/strict-server/client/client.gen.go +++ /dev/null @@ -1,1986 +0,0 @@ -// Package api provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package api - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "io" - "net/http" - "net/url" - "strings" - - "github.com/oapi-codegen/runtime" -) - -// Example defines model for example. -type Example struct { - Value *string `json:"value,omitempty"` -} - -// Reusableresponse defines model for reusableresponse. -type Reusableresponse = Example - -// MultipleRequestAndResponseTypesTextBody defines parameters for MultipleRequestAndResponseTypes. -type MultipleRequestAndResponseTypesTextBody = string - -// RequiredTextBodyTextBody defines parameters for RequiredTextBody. -type RequiredTextBodyTextBody = string - -// TextExampleTextBody defines parameters for TextExample. -type TextExampleTextBody = string - -// HeadersExampleParams defines parameters for HeadersExample. -type HeadersExampleParams struct { - Header1 string `json:"header1"` - Header2 *int `json:"header2,omitempty"` -} - -// JSONExampleJSONRequestBody defines body for JSONExample for application/json ContentType. -type JSONExampleJSONRequestBody = Example - -// MultipartExampleMultipartRequestBody defines body for MultipartExample for multipart/form-data ContentType. -type MultipartExampleMultipartRequestBody = Example - -// MultipartRelatedExampleMultipartRequestBody defines body for MultipartRelatedExample for multipart/related ContentType. -type MultipartRelatedExampleMultipartRequestBody = Example - -// MultipleRequestAndResponseTypesJSONRequestBody defines body for MultipleRequestAndResponseTypes for application/json ContentType. -type MultipleRequestAndResponseTypesJSONRequestBody = Example - -// MultipleRequestAndResponseTypesFormdataRequestBody defines body for MultipleRequestAndResponseTypes for application/x-www-form-urlencoded ContentType. -type MultipleRequestAndResponseTypesFormdataRequestBody = Example - -// MultipleRequestAndResponseTypesMultipartRequestBody defines body for MultipleRequestAndResponseTypes for multipart/form-data ContentType. -type MultipleRequestAndResponseTypesMultipartRequestBody = Example - -// MultipleRequestAndResponseTypesTextRequestBody defines body for MultipleRequestAndResponseTypes for text/plain ContentType. -type MultipleRequestAndResponseTypesTextRequestBody = MultipleRequestAndResponseTypesTextBody - -// RequiredJSONBodyJSONRequestBody defines body for RequiredJSONBody for application/json ContentType. -type RequiredJSONBodyJSONRequestBody = Example - -// RequiredTextBodyTextRequestBody defines body for RequiredTextBody for text/plain ContentType. -type RequiredTextBodyTextRequestBody = RequiredTextBodyTextBody - -// ReusableResponsesJSONRequestBody defines body for ReusableResponses for application/json ContentType. -type ReusableResponsesJSONRequestBody = Example - -// TextExampleTextRequestBody defines body for TextExample for text/plain ContentType. -type TextExampleTextRequestBody = TextExampleTextBody - -// URLEncodedExampleFormdataRequestBody defines body for URLEncodedExample for application/x-www-form-urlencoded ContentType. -type URLEncodedExampleFormdataRequestBody = Example - -// HeadersExampleJSONRequestBody defines body for HeadersExample for application/json ContentType. -type HeadersExampleJSONRequestBody = Example - -// UnionExampleJSONRequestBody defines body for UnionExample for application/json ContentType. -type UnionExampleJSONRequestBody = Example - -// RequestEditorFn is the function signature for the RequestEditor callback function -type RequestEditorFn func(ctx context.Context, req *http.Request) error - -// Doer performs HTTP requests. -// -// The standard http.Client implements this interface. -type HttpRequestDoer interface { - Do(req *http.Request) (*http.Response, error) -} - -// Client which conforms to the OpenAPI3 specification for this service. -type Client struct { - // The endpoint of the server conforming to this interface, with scheme, - // https://api.deepmap.com for example. This can contain a path relative - // to the server, such as https://api.deepmap.com/dev-test, and all the - // paths in the swagger spec will be appended to the server. - Server string - - // Doer for performing requests, typically a *http.Client with any - // customized settings, such as certificate chains. - Client HttpRequestDoer - - // A list of callbacks for modifying requests which are generated before sending over - // the network. - RequestEditors []RequestEditorFn -} - -// ClientOption allows setting custom parameters during construction -type ClientOption func(*Client) error - -// Creates a new Client, with reasonable defaults -func NewClient(server string, opts ...ClientOption) (*Client, error) { - // create a client with sane default values - client := Client{ - Server: server, - } - // mutate client and add all optional params - for _, o := range opts { - if err := o(&client); err != nil { - return nil, err - } - } - // ensure the server URL always has a trailing slash - if !strings.HasSuffix(client.Server, "/") { - client.Server += "/" - } - // create httpClient, if not already present - if client.Client == nil { - client.Client = &http.Client{} - } - return &client, nil -} - -// WithHTTPClient allows overriding the default Doer, which is -// automatically created using http.Client. This is useful for tests. -func WithHTTPClient(doer HttpRequestDoer) ClientOption { - return func(c *Client) error { - c.Client = doer - return nil - } -} - -// WithRequestEditorFn allows setting up a callback function, which will be -// called right before sending the request. This can be used to mutate the request. -func WithRequestEditorFn(fn RequestEditorFn) ClientOption { - return func(c *Client) error { - c.RequestEditors = append(c.RequestEditors, fn) - return nil - } -} - -// The interface specification for the client above. -type ClientInterface interface { - // JSONExampleWithBody request with any body - JSONExampleWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) - - JSONExample(ctx context.Context, body JSONExampleJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) - - // MultipartExampleWithBody request with any body - MultipartExampleWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) - - // MultipartRelatedExampleWithBody request with any body - MultipartRelatedExampleWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) - - // MultipleRequestAndResponseTypesWithBody request with any body - MultipleRequestAndResponseTypesWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) - - MultipleRequestAndResponseTypes(ctx context.Context, body MultipleRequestAndResponseTypesJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) - - MultipleRequestAndResponseTypesWithFormdataBody(ctx context.Context, body MultipleRequestAndResponseTypesFormdataRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) - - MultipleRequestAndResponseTypesWithTextBody(ctx context.Context, body MultipleRequestAndResponseTypesTextRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) - - // RequiredJSONBodyWithBody request with any body - RequiredJSONBodyWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) - - RequiredJSONBody(ctx context.Context, body RequiredJSONBodyJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) - - // RequiredTextBodyWithBody request with any body - RequiredTextBodyWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) - - RequiredTextBodyWithTextBody(ctx context.Context, body RequiredTextBodyTextRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) - - // ReservedGoKeywordParameters request - ReservedGoKeywordParameters(ctx context.Context, pType string, reqEditors ...RequestEditorFn) (*http.Response, error) - - // ReusableResponsesWithBody request with any body - ReusableResponsesWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) - - ReusableResponses(ctx context.Context, body ReusableResponsesJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) - - // TextExampleWithBody request with any body - TextExampleWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) - - TextExampleWithTextBody(ctx context.Context, body TextExampleTextRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) - - // UnknownExampleWithBody request with any body - UnknownExampleWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) - - // UnspecifiedContentTypeWithBody request with any body - UnspecifiedContentTypeWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) - - // URLEncodedExampleWithBody request with any body - URLEncodedExampleWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) - - URLEncodedExampleWithFormdataBody(ctx context.Context, body URLEncodedExampleFormdataRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) - - // HeadersExampleWithBody request with any body - HeadersExampleWithBody(ctx context.Context, params *HeadersExampleParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) - - HeadersExample(ctx context.Context, params *HeadersExampleParams, body HeadersExampleJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) - - // UnionExampleWithBody request with any body - UnionExampleWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) - - UnionExample(ctx context.Context, body UnionExampleJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) -} - -func (c *Client) JSONExampleWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewJSONExampleRequestWithBody(c.Server, contentType, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) JSONExample(ctx context.Context, body JSONExampleJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewJSONExampleRequest(c.Server, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) MultipartExampleWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewMultipartExampleRequestWithBody(c.Server, contentType, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) MultipartRelatedExampleWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewMultipartRelatedExampleRequestWithBody(c.Server, contentType, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) MultipleRequestAndResponseTypesWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewMultipleRequestAndResponseTypesRequestWithBody(c.Server, contentType, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) MultipleRequestAndResponseTypes(ctx context.Context, body MultipleRequestAndResponseTypesJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewMultipleRequestAndResponseTypesRequest(c.Server, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) MultipleRequestAndResponseTypesWithFormdataBody(ctx context.Context, body MultipleRequestAndResponseTypesFormdataRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewMultipleRequestAndResponseTypesRequestWithFormdataBody(c.Server, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) MultipleRequestAndResponseTypesWithTextBody(ctx context.Context, body MultipleRequestAndResponseTypesTextRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewMultipleRequestAndResponseTypesRequestWithTextBody(c.Server, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) RequiredJSONBodyWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewRequiredJSONBodyRequestWithBody(c.Server, contentType, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) RequiredJSONBody(ctx context.Context, body RequiredJSONBodyJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewRequiredJSONBodyRequest(c.Server, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) RequiredTextBodyWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewRequiredTextBodyRequestWithBody(c.Server, contentType, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) RequiredTextBodyWithTextBody(ctx context.Context, body RequiredTextBodyTextRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewRequiredTextBodyRequestWithTextBody(c.Server, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) ReservedGoKeywordParameters(ctx context.Context, pType string, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewReservedGoKeywordParametersRequest(c.Server, pType) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) ReusableResponsesWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewReusableResponsesRequestWithBody(c.Server, contentType, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) ReusableResponses(ctx context.Context, body ReusableResponsesJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewReusableResponsesRequest(c.Server, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) TextExampleWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewTextExampleRequestWithBody(c.Server, contentType, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) TextExampleWithTextBody(ctx context.Context, body TextExampleTextRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewTextExampleRequestWithTextBody(c.Server, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) UnknownExampleWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewUnknownExampleRequestWithBody(c.Server, contentType, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) UnspecifiedContentTypeWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewUnspecifiedContentTypeRequestWithBody(c.Server, contentType, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) URLEncodedExampleWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewURLEncodedExampleRequestWithBody(c.Server, contentType, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) URLEncodedExampleWithFormdataBody(ctx context.Context, body URLEncodedExampleFormdataRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewURLEncodedExampleRequestWithFormdataBody(c.Server, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) HeadersExampleWithBody(ctx context.Context, params *HeadersExampleParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewHeadersExampleRequestWithBody(c.Server, params, contentType, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) HeadersExample(ctx context.Context, params *HeadersExampleParams, body HeadersExampleJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewHeadersExampleRequest(c.Server, params, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) UnionExampleWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewUnionExampleRequestWithBody(c.Server, contentType, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) UnionExample(ctx context.Context, body UnionExampleJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewUnionExampleRequest(c.Server, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -// NewJSONExampleRequest calls the generic JSONExample builder with application/json body -func NewJSONExampleRequest(server string, body JSONExampleJSONRequestBody) (*http.Request, error) { - var bodyReader io.Reader - buf, err := json.Marshal(body) - if err != nil { - return nil, err - } - bodyReader = bytes.NewReader(buf) - return NewJSONExampleRequestWithBody(server, "application/json", bodyReader) -} - -// NewJSONExampleRequestWithBody generates requests for JSONExample with any type of body -func NewJSONExampleRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/json") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("POST", queryURL.String(), body) - if err != nil { - return nil, err - } - - req.Header.Add("Content-Type", contentType) - - return req, nil -} - -// NewMultipartExampleRequestWithBody generates requests for MultipartExample with any type of body -func NewMultipartExampleRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/multipart") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("POST", queryURL.String(), body) - if err != nil { - return nil, err - } - - req.Header.Add("Content-Type", contentType) - - return req, nil -} - -// NewMultipartRelatedExampleRequestWithBody generates requests for MultipartRelatedExample with any type of body -func NewMultipartRelatedExampleRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/multipart-related") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("POST", queryURL.String(), body) - if err != nil { - return nil, err - } - - req.Header.Add("Content-Type", contentType) - - return req, nil -} - -// NewMultipleRequestAndResponseTypesRequest calls the generic MultipleRequestAndResponseTypes builder with application/json body -func NewMultipleRequestAndResponseTypesRequest(server string, body MultipleRequestAndResponseTypesJSONRequestBody) (*http.Request, error) { - var bodyReader io.Reader - buf, err := json.Marshal(body) - if err != nil { - return nil, err - } - bodyReader = bytes.NewReader(buf) - return NewMultipleRequestAndResponseTypesRequestWithBody(server, "application/json", bodyReader) -} - -// NewMultipleRequestAndResponseTypesRequestWithFormdataBody calls the generic MultipleRequestAndResponseTypes builder with application/x-www-form-urlencoded body -func NewMultipleRequestAndResponseTypesRequestWithFormdataBody(server string, body MultipleRequestAndResponseTypesFormdataRequestBody) (*http.Request, error) { - var bodyReader io.Reader - bodyStr, err := runtime.MarshalForm(body, nil) - if err != nil { - return nil, err - } - bodyReader = strings.NewReader(bodyStr.Encode()) - return NewMultipleRequestAndResponseTypesRequestWithBody(server, "application/x-www-form-urlencoded", bodyReader) -} - -// NewMultipleRequestAndResponseTypesRequestWithTextBody calls the generic MultipleRequestAndResponseTypes builder with text/plain body -func NewMultipleRequestAndResponseTypesRequestWithTextBody(server string, body MultipleRequestAndResponseTypesTextRequestBody) (*http.Request, error) { - var bodyReader io.Reader - bodyReader = strings.NewReader(string(body)) - return NewMultipleRequestAndResponseTypesRequestWithBody(server, "text/plain", bodyReader) -} - -// NewMultipleRequestAndResponseTypesRequestWithBody generates requests for MultipleRequestAndResponseTypes with any type of body -func NewMultipleRequestAndResponseTypesRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/multiple") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("POST", queryURL.String(), body) - if err != nil { - return nil, err - } - - req.Header.Add("Content-Type", contentType) - - return req, nil -} - -// NewRequiredJSONBodyRequest calls the generic RequiredJSONBody builder with application/json body -func NewRequiredJSONBodyRequest(server string, body RequiredJSONBodyJSONRequestBody) (*http.Request, error) { - var bodyReader io.Reader - buf, err := json.Marshal(body) - if err != nil { - return nil, err - } - bodyReader = bytes.NewReader(buf) - return NewRequiredJSONBodyRequestWithBody(server, "application/json", bodyReader) -} - -// NewRequiredJSONBodyRequestWithBody generates requests for RequiredJSONBody with any type of body -func NewRequiredJSONBodyRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/required-json-body") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("POST", queryURL.String(), body) - if err != nil { - return nil, err - } - - req.Header.Add("Content-Type", contentType) - - return req, nil -} - -// NewRequiredTextBodyRequestWithTextBody calls the generic RequiredTextBody builder with text/plain body -func NewRequiredTextBodyRequestWithTextBody(server string, body RequiredTextBodyTextRequestBody) (*http.Request, error) { - var bodyReader io.Reader - bodyReader = strings.NewReader(string(body)) - return NewRequiredTextBodyRequestWithBody(server, "text/plain", bodyReader) -} - -// NewRequiredTextBodyRequestWithBody generates requests for RequiredTextBody with any type of body -func NewRequiredTextBodyRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/required-text-body") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("POST", queryURL.String(), body) - if err != nil { - return nil, err - } - - req.Header.Add("Content-Type", contentType) - - return req, nil -} - -// NewReservedGoKeywordParametersRequest generates requests for ReservedGoKeywordParameters -func NewReservedGoKeywordParametersRequest(server string, pType string) (*http.Request, error) { - var err error - - var pathParam0 string - - pathParam0, err = runtime.StyleParamWithOptions("simple", false, "type", pType, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) - if err != nil { - return nil, err - } - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/reserved-go-keyword-parameters/%s", pathParam0) - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -// NewReusableResponsesRequest calls the generic ReusableResponses builder with application/json body -func NewReusableResponsesRequest(server string, body ReusableResponsesJSONRequestBody) (*http.Request, error) { - var bodyReader io.Reader - buf, err := json.Marshal(body) - if err != nil { - return nil, err - } - bodyReader = bytes.NewReader(buf) - return NewReusableResponsesRequestWithBody(server, "application/json", bodyReader) -} - -// NewReusableResponsesRequestWithBody generates requests for ReusableResponses with any type of body -func NewReusableResponsesRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/reusable-responses") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("POST", queryURL.String(), body) - if err != nil { - return nil, err - } - - req.Header.Add("Content-Type", contentType) - - return req, nil -} - -// NewTextExampleRequestWithTextBody calls the generic TextExample builder with text/plain body -func NewTextExampleRequestWithTextBody(server string, body TextExampleTextRequestBody) (*http.Request, error) { - var bodyReader io.Reader - bodyReader = strings.NewReader(string(body)) - return NewTextExampleRequestWithBody(server, "text/plain", bodyReader) -} - -// NewTextExampleRequestWithBody generates requests for TextExample with any type of body -func NewTextExampleRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/text") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("POST", queryURL.String(), body) - if err != nil { - return nil, err - } - - req.Header.Add("Content-Type", contentType) - - return req, nil -} - -// NewUnknownExampleRequestWithBody generates requests for UnknownExample with any type of body -func NewUnknownExampleRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/unknown") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("POST", queryURL.String(), body) - if err != nil { - return nil, err - } - - req.Header.Add("Content-Type", contentType) - - return req, nil -} - -// NewUnspecifiedContentTypeRequestWithBody generates requests for UnspecifiedContentType with any type of body -func NewUnspecifiedContentTypeRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/unspecified-content-type") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("POST", queryURL.String(), body) - if err != nil { - return nil, err - } - - req.Header.Add("Content-Type", contentType) - - return req, nil -} - -// NewURLEncodedExampleRequestWithFormdataBody calls the generic URLEncodedExample builder with application/x-www-form-urlencoded body -func NewURLEncodedExampleRequestWithFormdataBody(server string, body URLEncodedExampleFormdataRequestBody) (*http.Request, error) { - var bodyReader io.Reader - bodyStr, err := runtime.MarshalForm(body, nil) - if err != nil { - return nil, err - } - bodyReader = strings.NewReader(bodyStr.Encode()) - return NewURLEncodedExampleRequestWithBody(server, "application/x-www-form-urlencoded", bodyReader) -} - -// NewURLEncodedExampleRequestWithBody generates requests for URLEncodedExample with any type of body -func NewURLEncodedExampleRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/urlencoded") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("POST", queryURL.String(), body) - if err != nil { - return nil, err - } - - req.Header.Add("Content-Type", contentType) - - return req, nil -} - -// NewHeadersExampleRequest calls the generic HeadersExample builder with application/json body -func NewHeadersExampleRequest(server string, params *HeadersExampleParams, body HeadersExampleJSONRequestBody) (*http.Request, error) { - var bodyReader io.Reader - buf, err := json.Marshal(body) - if err != nil { - return nil, err - } - bodyReader = bytes.NewReader(buf) - return NewHeadersExampleRequestWithBody(server, params, "application/json", bodyReader) -} - -// NewHeadersExampleRequestWithBody generates requests for HeadersExample with any type of body -func NewHeadersExampleRequestWithBody(server string, params *HeadersExampleParams, contentType string, body io.Reader) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/with-headers") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("POST", queryURL.String(), body) - if err != nil { - return nil, err - } - - req.Header.Add("Content-Type", contentType) - - if params != nil { - - var headerParam0 string - - headerParam0, err = runtime.StyleParamWithOptions("simple", false, "header1", params.Header1, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "string", Format: ""}) - if err != nil { - return nil, err - } - - req.Header.Set("header1", headerParam0) - - if params.Header2 != nil { - var headerParam1 string - - headerParam1, err = runtime.StyleParamWithOptions("simple", false, "header2", *params.Header2, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "integer", Format: ""}) - if err != nil { - return nil, err - } - - req.Header.Set("header2", headerParam1) - } - - } - - return req, nil -} - -// NewUnionExampleRequest calls the generic UnionExample builder with application/json body -func NewUnionExampleRequest(server string, body UnionExampleJSONRequestBody) (*http.Request, error) { - var bodyReader io.Reader - buf, err := json.Marshal(body) - if err != nil { - return nil, err - } - bodyReader = bytes.NewReader(buf) - return NewUnionExampleRequestWithBody(server, "application/json", bodyReader) -} - -// NewUnionExampleRequestWithBody generates requests for UnionExample with any type of body -func NewUnionExampleRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/with-union") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("POST", queryURL.String(), body) - if err != nil { - return nil, err - } - - req.Header.Add("Content-Type", contentType) - - return req, nil -} - -func (c *Client) applyEditors(ctx context.Context, req *http.Request, additionalEditors []RequestEditorFn) error { - for _, r := range c.RequestEditors { - if err := r(ctx, req); err != nil { - return err - } - } - for _, r := range additionalEditors { - if err := r(ctx, req); err != nil { - return err - } - } - return nil -} - -// ClientWithResponses builds on ClientInterface to offer response payloads -type ClientWithResponses struct { - ClientInterface -} - -// NewClientWithResponses creates a new ClientWithResponses, which wraps -// Client with return type handling -func NewClientWithResponses(server string, opts ...ClientOption) (*ClientWithResponses, error) { - client, err := NewClient(server, opts...) - if err != nil { - return nil, err - } - return &ClientWithResponses{client}, nil -} - -// WithBaseURL overrides the baseURL. -func WithBaseURL(baseURL string) ClientOption { - return func(c *Client) error { - newBaseURL, err := url.Parse(baseURL) - if err != nil { - return err - } - c.Server = newBaseURL.String() - return nil - } -} - -// ClientWithResponsesInterface is the interface specification for the client with responses above. -type ClientWithResponsesInterface interface { - // JSONExampleWithBodyWithResponse request with any body - JSONExampleWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*JSONExampleResponse, error) - - JSONExampleWithResponse(ctx context.Context, body JSONExampleJSONRequestBody, reqEditors ...RequestEditorFn) (*JSONExampleResponse, error) - - // MultipartExampleWithBodyWithResponse request with any body - MultipartExampleWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*MultipartExampleResponse, error) - - // MultipartRelatedExampleWithBodyWithResponse request with any body - MultipartRelatedExampleWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*MultipartRelatedExampleResponse, error) - - // MultipleRequestAndResponseTypesWithBodyWithResponse request with any body - MultipleRequestAndResponseTypesWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*MultipleRequestAndResponseTypesResponse, error) - - MultipleRequestAndResponseTypesWithResponse(ctx context.Context, body MultipleRequestAndResponseTypesJSONRequestBody, reqEditors ...RequestEditorFn) (*MultipleRequestAndResponseTypesResponse, error) - - MultipleRequestAndResponseTypesWithFormdataBodyWithResponse(ctx context.Context, body MultipleRequestAndResponseTypesFormdataRequestBody, reqEditors ...RequestEditorFn) (*MultipleRequestAndResponseTypesResponse, error) - - MultipleRequestAndResponseTypesWithTextBodyWithResponse(ctx context.Context, body MultipleRequestAndResponseTypesTextRequestBody, reqEditors ...RequestEditorFn) (*MultipleRequestAndResponseTypesResponse, error) - - // RequiredJSONBodyWithBodyWithResponse request with any body - RequiredJSONBodyWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*RequiredJSONBodyResponse, error) - - RequiredJSONBodyWithResponse(ctx context.Context, body RequiredJSONBodyJSONRequestBody, reqEditors ...RequestEditorFn) (*RequiredJSONBodyResponse, error) - - // RequiredTextBodyWithBodyWithResponse request with any body - RequiredTextBodyWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*RequiredTextBodyResponse, error) - - RequiredTextBodyWithTextBodyWithResponse(ctx context.Context, body RequiredTextBodyTextRequestBody, reqEditors ...RequestEditorFn) (*RequiredTextBodyResponse, error) - - // ReservedGoKeywordParametersWithResponse request - ReservedGoKeywordParametersWithResponse(ctx context.Context, pType string, reqEditors ...RequestEditorFn) (*ReservedGoKeywordParametersResponse, error) - - // ReusableResponsesWithBodyWithResponse request with any body - ReusableResponsesWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*ReusableResponsesResponse, error) - - ReusableResponsesWithResponse(ctx context.Context, body ReusableResponsesJSONRequestBody, reqEditors ...RequestEditorFn) (*ReusableResponsesResponse, error) - - // TextExampleWithBodyWithResponse request with any body - TextExampleWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*TextExampleResponse, error) - - TextExampleWithTextBodyWithResponse(ctx context.Context, body TextExampleTextRequestBody, reqEditors ...RequestEditorFn) (*TextExampleResponse, error) - - // UnknownExampleWithBodyWithResponse request with any body - UnknownExampleWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*UnknownExampleResponse, error) - - // UnspecifiedContentTypeWithBodyWithResponse request with any body - UnspecifiedContentTypeWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*UnspecifiedContentTypeResponse, error) - - // URLEncodedExampleWithBodyWithResponse request with any body - URLEncodedExampleWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*URLEncodedExampleResponse, error) - - URLEncodedExampleWithFormdataBodyWithResponse(ctx context.Context, body URLEncodedExampleFormdataRequestBody, reqEditors ...RequestEditorFn) (*URLEncodedExampleResponse, error) - - // HeadersExampleWithBodyWithResponse request with any body - HeadersExampleWithBodyWithResponse(ctx context.Context, params *HeadersExampleParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*HeadersExampleResponse, error) - - HeadersExampleWithResponse(ctx context.Context, params *HeadersExampleParams, body HeadersExampleJSONRequestBody, reqEditors ...RequestEditorFn) (*HeadersExampleResponse, error) - - // UnionExampleWithBodyWithResponse request with any body - UnionExampleWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*UnionExampleResponse, error) - - UnionExampleWithResponse(ctx context.Context, body UnionExampleJSONRequestBody, reqEditors ...RequestEditorFn) (*UnionExampleResponse, error) -} - -type JSONExampleResponse struct { - Body []byte - HTTPResponse *http.Response - JSON200 *Example -} - -// Status returns HTTPResponse.Status -func (r JSONExampleResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r JSONExampleResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type MultipartExampleResponse struct { - Body []byte - HTTPResponse *http.Response -} - -// Status returns HTTPResponse.Status -func (r MultipartExampleResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r MultipartExampleResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type MultipartRelatedExampleResponse struct { - Body []byte - HTTPResponse *http.Response -} - -// Status returns HTTPResponse.Status -func (r MultipartRelatedExampleResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r MultipartRelatedExampleResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type MultipleRequestAndResponseTypesResponse struct { - Body []byte - HTTPResponse *http.Response - JSON200 *Example -} - -// Status returns HTTPResponse.Status -func (r MultipleRequestAndResponseTypesResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r MultipleRequestAndResponseTypesResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type RequiredJSONBodyResponse struct { - Body []byte - HTTPResponse *http.Response - JSON200 *Example -} - -// Status returns HTTPResponse.Status -func (r RequiredJSONBodyResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r RequiredJSONBodyResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type RequiredTextBodyResponse struct { - Body []byte - HTTPResponse *http.Response -} - -// Status returns HTTPResponse.Status -func (r RequiredTextBodyResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r RequiredTextBodyResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type ReservedGoKeywordParametersResponse struct { - Body []byte - HTTPResponse *http.Response -} - -// Status returns HTTPResponse.Status -func (r ReservedGoKeywordParametersResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r ReservedGoKeywordParametersResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type ReusableResponsesResponse struct { - Body []byte - HTTPResponse *http.Response - JSON200 *Reusableresponse -} - -// Status returns HTTPResponse.Status -func (r ReusableResponsesResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r ReusableResponsesResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type TextExampleResponse struct { - Body []byte - HTTPResponse *http.Response -} - -// Status returns HTTPResponse.Status -func (r TextExampleResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r TextExampleResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type UnknownExampleResponse struct { - Body []byte - HTTPResponse *http.Response -} - -// Status returns HTTPResponse.Status -func (r UnknownExampleResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r UnknownExampleResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type UnspecifiedContentTypeResponse struct { - Body []byte - HTTPResponse *http.Response -} - -// Status returns HTTPResponse.Status -func (r UnspecifiedContentTypeResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r UnspecifiedContentTypeResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type URLEncodedExampleResponse struct { - Body []byte - HTTPResponse *http.Response -} - -// Status returns HTTPResponse.Status -func (r URLEncodedExampleResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r URLEncodedExampleResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type HeadersExampleResponse struct { - Body []byte - HTTPResponse *http.Response - JSON200 *Example -} - -// Status returns HTTPResponse.Status -func (r HeadersExampleResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r HeadersExampleResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type UnionExampleResponse struct { - Body []byte - HTTPResponse *http.Response - ApplicationalternativeJSON200 *Example - JSON200 *struct { - union json.RawMessage - } -} -type UnionExample2000 = string - -// Status returns HTTPResponse.Status -func (r UnionExampleResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r UnionExampleResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -// JSONExampleWithBodyWithResponse request with arbitrary body returning *JSONExampleResponse -func (c *ClientWithResponses) JSONExampleWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*JSONExampleResponse, error) { - rsp, err := c.JSONExampleWithBody(ctx, contentType, body, reqEditors...) - if err != nil { - return nil, err - } - return ParseJSONExampleResponse(rsp) -} - -func (c *ClientWithResponses) JSONExampleWithResponse(ctx context.Context, body JSONExampleJSONRequestBody, reqEditors ...RequestEditorFn) (*JSONExampleResponse, error) { - rsp, err := c.JSONExample(ctx, body, reqEditors...) - if err != nil { - return nil, err - } - return ParseJSONExampleResponse(rsp) -} - -// MultipartExampleWithBodyWithResponse request with arbitrary body returning *MultipartExampleResponse -func (c *ClientWithResponses) MultipartExampleWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*MultipartExampleResponse, error) { - rsp, err := c.MultipartExampleWithBody(ctx, contentType, body, reqEditors...) - if err != nil { - return nil, err - } - return ParseMultipartExampleResponse(rsp) -} - -// MultipartRelatedExampleWithBodyWithResponse request with arbitrary body returning *MultipartRelatedExampleResponse -func (c *ClientWithResponses) MultipartRelatedExampleWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*MultipartRelatedExampleResponse, error) { - rsp, err := c.MultipartRelatedExampleWithBody(ctx, contentType, body, reqEditors...) - if err != nil { - return nil, err - } - return ParseMultipartRelatedExampleResponse(rsp) -} - -// MultipleRequestAndResponseTypesWithBodyWithResponse request with arbitrary body returning *MultipleRequestAndResponseTypesResponse -func (c *ClientWithResponses) MultipleRequestAndResponseTypesWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*MultipleRequestAndResponseTypesResponse, error) { - rsp, err := c.MultipleRequestAndResponseTypesWithBody(ctx, contentType, body, reqEditors...) - if err != nil { - return nil, err - } - return ParseMultipleRequestAndResponseTypesResponse(rsp) -} - -func (c *ClientWithResponses) MultipleRequestAndResponseTypesWithResponse(ctx context.Context, body MultipleRequestAndResponseTypesJSONRequestBody, reqEditors ...RequestEditorFn) (*MultipleRequestAndResponseTypesResponse, error) { - rsp, err := c.MultipleRequestAndResponseTypes(ctx, body, reqEditors...) - if err != nil { - return nil, err - } - return ParseMultipleRequestAndResponseTypesResponse(rsp) -} - -func (c *ClientWithResponses) MultipleRequestAndResponseTypesWithFormdataBodyWithResponse(ctx context.Context, body MultipleRequestAndResponseTypesFormdataRequestBody, reqEditors ...RequestEditorFn) (*MultipleRequestAndResponseTypesResponse, error) { - rsp, err := c.MultipleRequestAndResponseTypesWithFormdataBody(ctx, body, reqEditors...) - if err != nil { - return nil, err - } - return ParseMultipleRequestAndResponseTypesResponse(rsp) -} - -func (c *ClientWithResponses) MultipleRequestAndResponseTypesWithTextBodyWithResponse(ctx context.Context, body MultipleRequestAndResponseTypesTextRequestBody, reqEditors ...RequestEditorFn) (*MultipleRequestAndResponseTypesResponse, error) { - rsp, err := c.MultipleRequestAndResponseTypesWithTextBody(ctx, body, reqEditors...) - if err != nil { - return nil, err - } - return ParseMultipleRequestAndResponseTypesResponse(rsp) -} - -// RequiredJSONBodyWithBodyWithResponse request with arbitrary body returning *RequiredJSONBodyResponse -func (c *ClientWithResponses) RequiredJSONBodyWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*RequiredJSONBodyResponse, error) { - rsp, err := c.RequiredJSONBodyWithBody(ctx, contentType, body, reqEditors...) - if err != nil { - return nil, err - } - return ParseRequiredJSONBodyResponse(rsp) -} - -func (c *ClientWithResponses) RequiredJSONBodyWithResponse(ctx context.Context, body RequiredJSONBodyJSONRequestBody, reqEditors ...RequestEditorFn) (*RequiredJSONBodyResponse, error) { - rsp, err := c.RequiredJSONBody(ctx, body, reqEditors...) - if err != nil { - return nil, err - } - return ParseRequiredJSONBodyResponse(rsp) -} - -// RequiredTextBodyWithBodyWithResponse request with arbitrary body returning *RequiredTextBodyResponse -func (c *ClientWithResponses) RequiredTextBodyWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*RequiredTextBodyResponse, error) { - rsp, err := c.RequiredTextBodyWithBody(ctx, contentType, body, reqEditors...) - if err != nil { - return nil, err - } - return ParseRequiredTextBodyResponse(rsp) -} - -func (c *ClientWithResponses) RequiredTextBodyWithTextBodyWithResponse(ctx context.Context, body RequiredTextBodyTextRequestBody, reqEditors ...RequestEditorFn) (*RequiredTextBodyResponse, error) { - rsp, err := c.RequiredTextBodyWithTextBody(ctx, body, reqEditors...) - if err != nil { - return nil, err - } - return ParseRequiredTextBodyResponse(rsp) -} - -// ReservedGoKeywordParametersWithResponse request returning *ReservedGoKeywordParametersResponse -func (c *ClientWithResponses) ReservedGoKeywordParametersWithResponse(ctx context.Context, pType string, reqEditors ...RequestEditorFn) (*ReservedGoKeywordParametersResponse, error) { - rsp, err := c.ReservedGoKeywordParameters(ctx, pType, reqEditors...) - if err != nil { - return nil, err - } - return ParseReservedGoKeywordParametersResponse(rsp) -} - -// ReusableResponsesWithBodyWithResponse request with arbitrary body returning *ReusableResponsesResponse -func (c *ClientWithResponses) ReusableResponsesWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*ReusableResponsesResponse, error) { - rsp, err := c.ReusableResponsesWithBody(ctx, contentType, body, reqEditors...) - if err != nil { - return nil, err - } - return ParseReusableResponsesResponse(rsp) -} - -func (c *ClientWithResponses) ReusableResponsesWithResponse(ctx context.Context, body ReusableResponsesJSONRequestBody, reqEditors ...RequestEditorFn) (*ReusableResponsesResponse, error) { - rsp, err := c.ReusableResponses(ctx, body, reqEditors...) - if err != nil { - return nil, err - } - return ParseReusableResponsesResponse(rsp) -} - -// TextExampleWithBodyWithResponse request with arbitrary body returning *TextExampleResponse -func (c *ClientWithResponses) TextExampleWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*TextExampleResponse, error) { - rsp, err := c.TextExampleWithBody(ctx, contentType, body, reqEditors...) - if err != nil { - return nil, err - } - return ParseTextExampleResponse(rsp) -} - -func (c *ClientWithResponses) TextExampleWithTextBodyWithResponse(ctx context.Context, body TextExampleTextRequestBody, reqEditors ...RequestEditorFn) (*TextExampleResponse, error) { - rsp, err := c.TextExampleWithTextBody(ctx, body, reqEditors...) - if err != nil { - return nil, err - } - return ParseTextExampleResponse(rsp) -} - -// UnknownExampleWithBodyWithResponse request with arbitrary body returning *UnknownExampleResponse -func (c *ClientWithResponses) UnknownExampleWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*UnknownExampleResponse, error) { - rsp, err := c.UnknownExampleWithBody(ctx, contentType, body, reqEditors...) - if err != nil { - return nil, err - } - return ParseUnknownExampleResponse(rsp) -} - -// UnspecifiedContentTypeWithBodyWithResponse request with arbitrary body returning *UnspecifiedContentTypeResponse -func (c *ClientWithResponses) UnspecifiedContentTypeWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*UnspecifiedContentTypeResponse, error) { - rsp, err := c.UnspecifiedContentTypeWithBody(ctx, contentType, body, reqEditors...) - if err != nil { - return nil, err - } - return ParseUnspecifiedContentTypeResponse(rsp) -} - -// URLEncodedExampleWithBodyWithResponse request with arbitrary body returning *URLEncodedExampleResponse -func (c *ClientWithResponses) URLEncodedExampleWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*URLEncodedExampleResponse, error) { - rsp, err := c.URLEncodedExampleWithBody(ctx, contentType, body, reqEditors...) - if err != nil { - return nil, err - } - return ParseURLEncodedExampleResponse(rsp) -} - -func (c *ClientWithResponses) URLEncodedExampleWithFormdataBodyWithResponse(ctx context.Context, body URLEncodedExampleFormdataRequestBody, reqEditors ...RequestEditorFn) (*URLEncodedExampleResponse, error) { - rsp, err := c.URLEncodedExampleWithFormdataBody(ctx, body, reqEditors...) - if err != nil { - return nil, err - } - return ParseURLEncodedExampleResponse(rsp) -} - -// HeadersExampleWithBodyWithResponse request with arbitrary body returning *HeadersExampleResponse -func (c *ClientWithResponses) HeadersExampleWithBodyWithResponse(ctx context.Context, params *HeadersExampleParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*HeadersExampleResponse, error) { - rsp, err := c.HeadersExampleWithBody(ctx, params, contentType, body, reqEditors...) - if err != nil { - return nil, err - } - return ParseHeadersExampleResponse(rsp) -} - -func (c *ClientWithResponses) HeadersExampleWithResponse(ctx context.Context, params *HeadersExampleParams, body HeadersExampleJSONRequestBody, reqEditors ...RequestEditorFn) (*HeadersExampleResponse, error) { - rsp, err := c.HeadersExample(ctx, params, body, reqEditors...) - if err != nil { - return nil, err - } - return ParseHeadersExampleResponse(rsp) -} - -// UnionExampleWithBodyWithResponse request with arbitrary body returning *UnionExampleResponse -func (c *ClientWithResponses) UnionExampleWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*UnionExampleResponse, error) { - rsp, err := c.UnionExampleWithBody(ctx, contentType, body, reqEditors...) - if err != nil { - return nil, err - } - return ParseUnionExampleResponse(rsp) -} - -func (c *ClientWithResponses) UnionExampleWithResponse(ctx context.Context, body UnionExampleJSONRequestBody, reqEditors ...RequestEditorFn) (*UnionExampleResponse, error) { - rsp, err := c.UnionExample(ctx, body, reqEditors...) - if err != nil { - return nil, err - } - return ParseUnionExampleResponse(rsp) -} - -// ParseJSONExampleResponse parses an HTTP response from a JSONExampleWithResponse call -func ParseJSONExampleResponse(rsp *http.Response) (*JSONExampleResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &JSONExampleResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest Example - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON200 = &dest - - } - - return response, nil -} - -// ParseMultipartExampleResponse parses an HTTP response from a MultipartExampleWithResponse call -func ParseMultipartExampleResponse(rsp *http.Response) (*MultipartExampleResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &MultipartExampleResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - return response, nil -} - -// ParseMultipartRelatedExampleResponse parses an HTTP response from a MultipartRelatedExampleWithResponse call -func ParseMultipartRelatedExampleResponse(rsp *http.Response) (*MultipartRelatedExampleResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &MultipartRelatedExampleResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - return response, nil -} - -// ParseMultipleRequestAndResponseTypesResponse parses an HTTP response from a MultipleRequestAndResponseTypesWithResponse call -func ParseMultipleRequestAndResponseTypesResponse(rsp *http.Response) (*MultipleRequestAndResponseTypesResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &MultipleRequestAndResponseTypesResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest Example - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON200 = &dest - - case rsp.StatusCode == 200: - // Content-type (text/plain) unsupported - - } - - return response, nil -} - -// ParseRequiredJSONBodyResponse parses an HTTP response from a RequiredJSONBodyWithResponse call -func ParseRequiredJSONBodyResponse(rsp *http.Response) (*RequiredJSONBodyResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &RequiredJSONBodyResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest Example - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON200 = &dest - - } - - return response, nil -} - -// ParseRequiredTextBodyResponse parses an HTTP response from a RequiredTextBodyWithResponse call -func ParseRequiredTextBodyResponse(rsp *http.Response) (*RequiredTextBodyResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &RequiredTextBodyResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - return response, nil -} - -// ParseReservedGoKeywordParametersResponse parses an HTTP response from a ReservedGoKeywordParametersWithResponse call -func ParseReservedGoKeywordParametersResponse(rsp *http.Response) (*ReservedGoKeywordParametersResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &ReservedGoKeywordParametersResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - return response, nil -} - -// ParseReusableResponsesResponse parses an HTTP response from a ReusableResponsesWithResponse call -func ParseReusableResponsesResponse(rsp *http.Response) (*ReusableResponsesResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &ReusableResponsesResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest Reusableresponse - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON200 = &dest - - } - - return response, nil -} - -// ParseTextExampleResponse parses an HTTP response from a TextExampleWithResponse call -func ParseTextExampleResponse(rsp *http.Response) (*TextExampleResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &TextExampleResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - return response, nil -} - -// ParseUnknownExampleResponse parses an HTTP response from a UnknownExampleWithResponse call -func ParseUnknownExampleResponse(rsp *http.Response) (*UnknownExampleResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &UnknownExampleResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - return response, nil -} - -// ParseUnspecifiedContentTypeResponse parses an HTTP response from a UnspecifiedContentTypeWithResponse call -func ParseUnspecifiedContentTypeResponse(rsp *http.Response) (*UnspecifiedContentTypeResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &UnspecifiedContentTypeResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - return response, nil -} - -// ParseURLEncodedExampleResponse parses an HTTP response from a URLEncodedExampleWithResponse call -func ParseURLEncodedExampleResponse(rsp *http.Response) (*URLEncodedExampleResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &URLEncodedExampleResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - return response, nil -} - -// ParseHeadersExampleResponse parses an HTTP response from a HeadersExampleWithResponse call -func ParseHeadersExampleResponse(rsp *http.Response) (*HeadersExampleResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &HeadersExampleResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest Example - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON200 = &dest - - } - - return response, nil -} - -// ParseUnionExampleResponse parses an HTTP response from a UnionExampleWithResponse call -func ParseUnionExampleResponse(rsp *http.Response) (*UnionExampleResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &UnionExampleResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - switch { - case rsp.Header.Get("Content-Type") == "application/alternative+json" && rsp.StatusCode == 200: - var dest Example - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.ApplicationalternativeJSON200 = &dest - - case rsp.Header.Get("Content-Type") == "application/json" && rsp.StatusCode == 200: - var dest struct { - union json.RawMessage - } - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON200 = &dest - - } - - return response, nil -} diff --git a/internal/test/strict-server/client/client.go b/internal/test/strict-server/client/client.go deleted file mode 100644 index 5b350a4884..0000000000 --- a/internal/test/strict-server/client/client.go +++ /dev/null @@ -1,3 +0,0 @@ -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=client.cfg.yaml ../strict-schema.yaml - -package api diff --git a/internal/test/strict-server/echo/server.cfg.yaml b/internal/test/strict-server/echo/server.cfg.yaml deleted file mode 100644 index 143f57f078..0000000000 --- a/internal/test/strict-server/echo/server.cfg.yaml +++ /dev/null @@ -1,7 +0,0 @@ -# yaml-language-server: $schema=../../../../configuration-schema.json -package: api -generate: - echo-server: true - strict-server: true - embedded-spec: true -output: server.gen.go diff --git a/internal/test/strict-server/echo/server.gen.go b/internal/test/strict-server/echo/server.gen.go deleted file mode 100644 index e8e335c74a..0000000000 --- a/internal/test/strict-server/echo/server.gen.go +++ /dev/null @@ -1,1499 +0,0 @@ -// Package api provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package api - -import ( - "bytes" - "compress/gzip" - "context" - "encoding/base64" - "encoding/json" - "errors" - "fmt" - "io" - "mime" - "mime/multipart" - "net/http" - "net/url" - "path" - "strings" - - "github.com/getkin/kin-openapi/openapi3" - "github.com/labstack/echo/v4" - "github.com/oapi-codegen/runtime" - strictecho "github.com/oapi-codegen/runtime/strictmiddleware/echo" -) - -// ServerInterface represents all server handlers. -type ServerInterface interface { - - // (POST /json) - JSONExample(ctx echo.Context) error - - // (POST /multipart) - MultipartExample(ctx echo.Context) error - - // (POST /multipart-related) - MultipartRelatedExample(ctx echo.Context) error - - // (POST /multiple) - MultipleRequestAndResponseTypes(ctx echo.Context) error - - // (POST /required-json-body) - RequiredJSONBody(ctx echo.Context) error - - // (POST /required-text-body) - RequiredTextBody(ctx echo.Context) error - - // (GET /reserved-go-keyword-parameters/{type}) - ReservedGoKeywordParameters(ctx echo.Context, pType string) error - - // (POST /reusable-responses) - ReusableResponses(ctx echo.Context) error - - // (POST /text) - TextExample(ctx echo.Context) error - - // (POST /unknown) - UnknownExample(ctx echo.Context) error - - // (POST /unspecified-content-type) - UnspecifiedContentType(ctx echo.Context) error - - // (POST /urlencoded) - URLEncodedExample(ctx echo.Context) error - - // (POST /with-headers) - HeadersExample(ctx echo.Context, params HeadersExampleParams) error - - // (POST /with-union) - UnionExample(ctx echo.Context) error -} - -// ServerInterfaceWrapper converts echo contexts to parameters. -type ServerInterfaceWrapper struct { - Handler ServerInterface -} - -// JSONExample converts echo context to params. -func (w *ServerInterfaceWrapper) JSONExample(ctx echo.Context) error { - var err error - - // Invoke the callback with all the unmarshaled arguments - err = w.Handler.JSONExample(ctx) - return err -} - -// MultipartExample converts echo context to params. -func (w *ServerInterfaceWrapper) MultipartExample(ctx echo.Context) error { - var err error - - // Invoke the callback with all the unmarshaled arguments - err = w.Handler.MultipartExample(ctx) - return err -} - -// MultipartRelatedExample converts echo context to params. -func (w *ServerInterfaceWrapper) MultipartRelatedExample(ctx echo.Context) error { - var err error - - // Invoke the callback with all the unmarshaled arguments - err = w.Handler.MultipartRelatedExample(ctx) - return err -} - -// MultipleRequestAndResponseTypes converts echo context to params. -func (w *ServerInterfaceWrapper) MultipleRequestAndResponseTypes(ctx echo.Context) error { - var err error - - // Invoke the callback with all the unmarshaled arguments - err = w.Handler.MultipleRequestAndResponseTypes(ctx) - return err -} - -// RequiredJSONBody converts echo context to params. -func (w *ServerInterfaceWrapper) RequiredJSONBody(ctx echo.Context) error { - var err error - - // Invoke the callback with all the unmarshaled arguments - err = w.Handler.RequiredJSONBody(ctx) - return err -} - -// RequiredTextBody converts echo context to params. -func (w *ServerInterfaceWrapper) RequiredTextBody(ctx echo.Context) error { - var err error - - // Invoke the callback with all the unmarshaled arguments - err = w.Handler.RequiredTextBody(ctx) - return err -} - -// ReservedGoKeywordParameters converts echo context to params. -func (w *ServerInterfaceWrapper) ReservedGoKeywordParameters(ctx echo.Context) error { - var err error - // ------------- Path parameter "type" ------------- - var pType string - - err = runtime.BindStyledParameterWithOptions("simple", "type", ctx.Param("type"), &pType, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) - if err != nil { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter type: %s", err)) - } - - // Invoke the callback with all the unmarshaled arguments - err = w.Handler.ReservedGoKeywordParameters(ctx, pType) - return err -} - -// ReusableResponses converts echo context to params. -func (w *ServerInterfaceWrapper) ReusableResponses(ctx echo.Context) error { - var err error - - // Invoke the callback with all the unmarshaled arguments - err = w.Handler.ReusableResponses(ctx) - return err -} - -// TextExample converts echo context to params. -func (w *ServerInterfaceWrapper) TextExample(ctx echo.Context) error { - var err error - - // Invoke the callback with all the unmarshaled arguments - err = w.Handler.TextExample(ctx) - return err -} - -// UnknownExample converts echo context to params. -func (w *ServerInterfaceWrapper) UnknownExample(ctx echo.Context) error { - var err error - - // Invoke the callback with all the unmarshaled arguments - err = w.Handler.UnknownExample(ctx) - return err -} - -// UnspecifiedContentType converts echo context to params. -func (w *ServerInterfaceWrapper) UnspecifiedContentType(ctx echo.Context) error { - var err error - - // Invoke the callback with all the unmarshaled arguments - err = w.Handler.UnspecifiedContentType(ctx) - return err -} - -// URLEncodedExample converts echo context to params. -func (w *ServerInterfaceWrapper) URLEncodedExample(ctx echo.Context) error { - var err error - - // Invoke the callback with all the unmarshaled arguments - err = w.Handler.URLEncodedExample(ctx) - return err -} - -// HeadersExample converts echo context to params. -func (w *ServerInterfaceWrapper) HeadersExample(ctx echo.Context) error { - var err error - - // Parameter object where we will unmarshal all parameters from the context - var params HeadersExampleParams - - headers := ctx.Request().Header - // ------------- Required header parameter "header1" ------------- - if valueList, found := headers[http.CanonicalHeaderKey("header1")]; found { - var Header1 string - n := len(valueList) - if n != 1 { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Expected one value for header1, got %d", n)) - } - - err = runtime.BindStyledParameterWithOptions("simple", "header1", valueList[0], &Header1, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: true, Type: "string", Format: ""}) - if err != nil { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter header1: %s", err)) - } - - params.Header1 = Header1 - } else { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Header parameter header1 is required, but not found")) - } - // ------------- Optional header parameter "header2" ------------- - if valueList, found := headers[http.CanonicalHeaderKey("header2")]; found { - var Header2 int - n := len(valueList) - if n != 1 { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Expected one value for header2, got %d", n)) - } - - err = runtime.BindStyledParameterWithOptions("simple", "header2", valueList[0], &Header2, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: ""}) - if err != nil { - return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter header2: %s", err)) - } - - params.Header2 = &Header2 - } - - // Invoke the callback with all the unmarshaled arguments - err = w.Handler.HeadersExample(ctx, params) - return err -} - -// UnionExample converts echo context to params. -func (w *ServerInterfaceWrapper) UnionExample(ctx echo.Context) error { - var err error - - // Invoke the callback with all the unmarshaled arguments - err = w.Handler.UnionExample(ctx) - return err -} - -// This is a simple interface which specifies echo.Route addition functions which -// are present on both echo.Echo and echo.Group, since we want to allow using -// either of them for path registration -type EchoRouter interface { - CONNECT(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - DELETE(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - GET(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - HEAD(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - OPTIONS(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - PATCH(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - POST(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - PUT(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route - TRACE(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route -} - -// RegisterHandlers adds each server route to the EchoRouter. -func RegisterHandlers(router EchoRouter, si ServerInterface) { - RegisterHandlersWithBaseURL(router, si, "") -} - -// Registers handlers, and prepends BaseURL to the paths, so that the paths -// can be served under a prefix. -func RegisterHandlersWithBaseURL(router EchoRouter, si ServerInterface, baseURL string) { - - wrapper := ServerInterfaceWrapper{ - Handler: si, - } - - router.POST(baseURL+"/json", wrapper.JSONExample) - router.POST(baseURL+"/multipart", wrapper.MultipartExample) - router.POST(baseURL+"/multipart-related", wrapper.MultipartRelatedExample) - router.POST(baseURL+"/multiple", wrapper.MultipleRequestAndResponseTypes) - router.POST(baseURL+"/required-json-body", wrapper.RequiredJSONBody) - router.POST(baseURL+"/required-text-body", wrapper.RequiredTextBody) - router.GET(baseURL+"/reserved-go-keyword-parameters/:type", wrapper.ReservedGoKeywordParameters) - router.POST(baseURL+"/reusable-responses", wrapper.ReusableResponses) - router.POST(baseURL+"/text", wrapper.TextExample) - router.POST(baseURL+"/unknown", wrapper.UnknownExample) - router.POST(baseURL+"/unspecified-content-type", wrapper.UnspecifiedContentType) - router.POST(baseURL+"/urlencoded", wrapper.URLEncodedExample) - router.POST(baseURL+"/with-headers", wrapper.HeadersExample) - router.POST(baseURL+"/with-union", wrapper.UnionExample) - -} - -type BadrequestResponse struct { -} - -type ReusableresponseResponseHeaders struct { - Header1 string - Header2 int -} -type ReusableresponseJSONResponse struct { - Body Example - - Headers ReusableresponseResponseHeaders -} - -type JSONExampleRequestObject struct { - Body *JSONExampleJSONRequestBody -} - -type JSONExampleResponseObject interface { - VisitJSONExampleResponse(w http.ResponseWriter) error -} - -type JSONExample200JSONResponse Example - -func (response JSONExample200JSONResponse) VisitJSONExampleResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(200) - - return json.NewEncoder(w).Encode(response) -} - -type JSONExample400Response = BadrequestResponse - -func (response JSONExample400Response) VisitJSONExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type JSONExampledefaultResponse struct { - StatusCode int -} - -func (response JSONExampledefaultResponse) VisitJSONExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -type MultipartExampleRequestObject struct { - Body *multipart.Reader -} - -type MultipartExampleResponseObject interface { - VisitMultipartExampleResponse(w http.ResponseWriter) error -} - -type MultipartExample200MultipartResponse func(writer *multipart.Writer) error - -func (response MultipartExample200MultipartResponse) VisitMultipartExampleResponse(w http.ResponseWriter) error { - writer := multipart.NewWriter(w) - w.Header().Set("Content-Type", writer.FormDataContentType()) - w.WriteHeader(200) - - defer writer.Close() - return response(writer) -} - -type MultipartExample400Response = BadrequestResponse - -func (response MultipartExample400Response) VisitMultipartExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type MultipartExampledefaultResponse struct { - StatusCode int -} - -func (response MultipartExampledefaultResponse) VisitMultipartExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -type MultipartRelatedExampleRequestObject struct { - Body *multipart.Reader -} - -type MultipartRelatedExampleResponseObject interface { - VisitMultipartRelatedExampleResponse(w http.ResponseWriter) error -} - -type MultipartRelatedExample200MultipartResponse func(writer *multipart.Writer) error - -func (response MultipartRelatedExample200MultipartResponse) VisitMultipartRelatedExampleResponse(w http.ResponseWriter) error { - writer := multipart.NewWriter(w) - w.Header().Set("Content-Type", mime.FormatMediaType("multipart/related", map[string]string{"boundary": writer.Boundary()})) - w.WriteHeader(200) - - defer writer.Close() - return response(writer) -} - -type MultipartRelatedExample400Response = BadrequestResponse - -func (response MultipartRelatedExample400Response) VisitMultipartRelatedExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type MultipartRelatedExampledefaultResponse struct { - StatusCode int -} - -func (response MultipartRelatedExampledefaultResponse) VisitMultipartRelatedExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -type MultipleRequestAndResponseTypesRequestObject struct { - JSONBody *MultipleRequestAndResponseTypesJSONRequestBody - FormdataBody *MultipleRequestAndResponseTypesFormdataRequestBody - Body io.Reader - MultipartBody *multipart.Reader - TextBody *MultipleRequestAndResponseTypesTextRequestBody -} - -type MultipleRequestAndResponseTypesResponseObject interface { - VisitMultipleRequestAndResponseTypesResponse(w http.ResponseWriter) error -} - -type MultipleRequestAndResponseTypes200JSONResponse Example - -func (response MultipleRequestAndResponseTypes200JSONResponse) VisitMultipleRequestAndResponseTypesResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(200) - - return json.NewEncoder(w).Encode(response) -} - -type MultipleRequestAndResponseTypes200FormdataResponse Example - -func (response MultipleRequestAndResponseTypes200FormdataResponse) VisitMultipleRequestAndResponseTypesResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/x-www-form-urlencoded") - w.WriteHeader(200) - - if form, err := runtime.MarshalForm(response, nil); err != nil { - return err - } else { - _, err := w.Write([]byte(form.Encode())) - return err - } -} - -type MultipleRequestAndResponseTypes200ImagepngResponse struct { - Body io.Reader - ContentLength int64 -} - -func (response MultipleRequestAndResponseTypes200ImagepngResponse) VisitMultipleRequestAndResponseTypesResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "image/png") - if response.ContentLength != 0 { - w.Header().Set("Content-Length", fmt.Sprint(response.ContentLength)) - } - w.WriteHeader(200) - - if closer, ok := response.Body.(io.ReadCloser); ok { - defer closer.Close() - } - _, err := io.Copy(w, response.Body) - return err -} - -type MultipleRequestAndResponseTypes200MultipartResponse func(writer *multipart.Writer) error - -func (response MultipleRequestAndResponseTypes200MultipartResponse) VisitMultipleRequestAndResponseTypesResponse(w http.ResponseWriter) error { - writer := multipart.NewWriter(w) - w.Header().Set("Content-Type", writer.FormDataContentType()) - w.WriteHeader(200) - - defer writer.Close() - return response(writer) -} - -type MultipleRequestAndResponseTypes200TextResponse string - -func (response MultipleRequestAndResponseTypes200TextResponse) VisitMultipleRequestAndResponseTypesResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "text/plain") - w.WriteHeader(200) - - _, err := w.Write([]byte(response)) - return err -} - -type MultipleRequestAndResponseTypes400Response = BadrequestResponse - -func (response MultipleRequestAndResponseTypes400Response) VisitMultipleRequestAndResponseTypesResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type RequiredJSONBodyRequestObject struct { - Body *RequiredJSONBodyJSONRequestBody -} - -type RequiredJSONBodyResponseObject interface { - VisitRequiredJSONBodyResponse(w http.ResponseWriter) error -} - -type RequiredJSONBody200JSONResponse Example - -func (response RequiredJSONBody200JSONResponse) VisitRequiredJSONBodyResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(200) - - return json.NewEncoder(w).Encode(response) -} - -type RequiredJSONBody400Response = BadrequestResponse - -func (response RequiredJSONBody400Response) VisitRequiredJSONBodyResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type RequiredJSONBodydefaultResponse struct { - StatusCode int -} - -func (response RequiredJSONBodydefaultResponse) VisitRequiredJSONBodyResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -type RequiredTextBodyRequestObject struct { - Body *RequiredTextBodyTextRequestBody -} - -type RequiredTextBodyResponseObject interface { - VisitRequiredTextBodyResponse(w http.ResponseWriter) error -} - -type RequiredTextBody200TextResponse string - -func (response RequiredTextBody200TextResponse) VisitRequiredTextBodyResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "text/plain") - w.WriteHeader(200) - - _, err := w.Write([]byte(response)) - return err -} - -type RequiredTextBody400Response = BadrequestResponse - -func (response RequiredTextBody400Response) VisitRequiredTextBodyResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type RequiredTextBodydefaultResponse struct { - StatusCode int -} - -func (response RequiredTextBodydefaultResponse) VisitRequiredTextBodyResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -type ReservedGoKeywordParametersRequestObject struct { - Type string `json:"type"` -} - -type ReservedGoKeywordParametersResponseObject interface { - VisitReservedGoKeywordParametersResponse(w http.ResponseWriter) error -} - -type ReservedGoKeywordParameters200TextResponse string - -func (response ReservedGoKeywordParameters200TextResponse) VisitReservedGoKeywordParametersResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "text/plain") - w.WriteHeader(200) - - _, err := w.Write([]byte(response)) - return err -} - -type ReusableResponsesRequestObject struct { - Body *ReusableResponsesJSONRequestBody -} - -type ReusableResponsesResponseObject interface { - VisitReusableResponsesResponse(w http.ResponseWriter) error -} - -type ReusableResponses200JSONResponse struct{ ReusableresponseJSONResponse } - -func (response ReusableResponses200JSONResponse) VisitReusableResponsesResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/json") - w.Header().Set("header1", fmt.Sprint(response.Headers.Header1)) - w.Header().Set("header2", fmt.Sprint(response.Headers.Header2)) - w.WriteHeader(200) - - return json.NewEncoder(w).Encode(response.Body) -} - -type ReusableResponses400Response = BadrequestResponse - -func (response ReusableResponses400Response) VisitReusableResponsesResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type ReusableResponsesdefaultResponse struct { - StatusCode int -} - -func (response ReusableResponsesdefaultResponse) VisitReusableResponsesResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -type TextExampleRequestObject struct { - Body *TextExampleTextRequestBody -} - -type TextExampleResponseObject interface { - VisitTextExampleResponse(w http.ResponseWriter) error -} - -type TextExample200TextResponse string - -func (response TextExample200TextResponse) VisitTextExampleResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "text/plain") - w.WriteHeader(200) - - _, err := w.Write([]byte(response)) - return err -} - -type TextExample400Response = BadrequestResponse - -func (response TextExample400Response) VisitTextExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type TextExampledefaultResponse struct { - StatusCode int -} - -func (response TextExampledefaultResponse) VisitTextExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -type UnknownExampleRequestObject struct { - Body io.Reader -} - -type UnknownExampleResponseObject interface { - VisitUnknownExampleResponse(w http.ResponseWriter) error -} - -type UnknownExample200Videomp4Response struct { - Body io.Reader - ContentLength int64 -} - -func (response UnknownExample200Videomp4Response) VisitUnknownExampleResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "video/mp4") - if response.ContentLength != 0 { - w.Header().Set("Content-Length", fmt.Sprint(response.ContentLength)) - } - w.WriteHeader(200) - - if closer, ok := response.Body.(io.ReadCloser); ok { - defer closer.Close() - } - _, err := io.Copy(w, response.Body) - return err -} - -type UnknownExample400Response = BadrequestResponse - -func (response UnknownExample400Response) VisitUnknownExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type UnknownExampledefaultResponse struct { - StatusCode int -} - -func (response UnknownExampledefaultResponse) VisitUnknownExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -type UnspecifiedContentTypeRequestObject struct { - ContentType string - Body io.Reader -} - -type UnspecifiedContentTypeResponseObject interface { - VisitUnspecifiedContentTypeResponse(w http.ResponseWriter) error -} - -type UnspecifiedContentType200VideoResponse struct { - Body io.Reader - ContentType string - ContentLength int64 -} - -func (response UnspecifiedContentType200VideoResponse) VisitUnspecifiedContentTypeResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", response.ContentType) - if response.ContentLength != 0 { - w.Header().Set("Content-Length", fmt.Sprint(response.ContentLength)) - } - w.WriteHeader(200) - - if closer, ok := response.Body.(io.ReadCloser); ok { - defer closer.Close() - } - _, err := io.Copy(w, response.Body) - return err -} - -type UnspecifiedContentType400Response = BadrequestResponse - -func (response UnspecifiedContentType400Response) VisitUnspecifiedContentTypeResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type UnspecifiedContentType401Response struct { -} - -func (response UnspecifiedContentType401Response) VisitUnspecifiedContentTypeResponse(w http.ResponseWriter) error { - w.WriteHeader(401) - return nil -} - -type UnspecifiedContentType403Response struct { -} - -func (response UnspecifiedContentType403Response) VisitUnspecifiedContentTypeResponse(w http.ResponseWriter) error { - w.WriteHeader(403) - return nil -} - -type UnspecifiedContentTypedefaultResponse struct { - StatusCode int -} - -func (response UnspecifiedContentTypedefaultResponse) VisitUnspecifiedContentTypeResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -type URLEncodedExampleRequestObject struct { - Body *URLEncodedExampleFormdataRequestBody -} - -type URLEncodedExampleResponseObject interface { - VisitURLEncodedExampleResponse(w http.ResponseWriter) error -} - -type URLEncodedExample200FormdataResponse Example - -func (response URLEncodedExample200FormdataResponse) VisitURLEncodedExampleResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/x-www-form-urlencoded") - w.WriteHeader(200) - - if form, err := runtime.MarshalForm(response, nil); err != nil { - return err - } else { - _, err := w.Write([]byte(form.Encode())) - return err - } -} - -type URLEncodedExample400Response = BadrequestResponse - -func (response URLEncodedExample400Response) VisitURLEncodedExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type URLEncodedExampledefaultResponse struct { - StatusCode int -} - -func (response URLEncodedExampledefaultResponse) VisitURLEncodedExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -type HeadersExampleRequestObject struct { - Params HeadersExampleParams - Body *HeadersExampleJSONRequestBody -} - -type HeadersExampleResponseObject interface { - VisitHeadersExampleResponse(w http.ResponseWriter) error -} - -type HeadersExample200ResponseHeaders struct { - Header1 string - Header2 int -} - -type HeadersExample200JSONResponse struct { - Body Example - Headers HeadersExample200ResponseHeaders -} - -func (response HeadersExample200JSONResponse) VisitHeadersExampleResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/json") - w.Header().Set("header1", fmt.Sprint(response.Headers.Header1)) - w.Header().Set("header2", fmt.Sprint(response.Headers.Header2)) - w.WriteHeader(200) - - return json.NewEncoder(w).Encode(response.Body) -} - -type HeadersExample400Response = BadrequestResponse - -func (response HeadersExample400Response) VisitHeadersExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type HeadersExampledefaultResponse struct { - StatusCode int -} - -func (response HeadersExampledefaultResponse) VisitHeadersExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -type UnionExampleRequestObject struct { - Body *UnionExampleJSONRequestBody -} - -type UnionExampleResponseObject interface { - VisitUnionExampleResponse(w http.ResponseWriter) error -} - -type UnionExample200ResponseHeaders struct { - Header1 string - Header2 int -} - -type UnionExample200ApplicationAlternativePlusJSONResponse struct { - Body Example - Headers UnionExample200ResponseHeaders -} - -func (response UnionExample200ApplicationAlternativePlusJSONResponse) VisitUnionExampleResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/alternative+json") - w.Header().Set("header1", fmt.Sprint(response.Headers.Header1)) - w.Header().Set("header2", fmt.Sprint(response.Headers.Header2)) - w.WriteHeader(200) - - return json.NewEncoder(w).Encode(response.Body) -} - -type UnionExample200JSONResponse struct { - Body struct { - union json.RawMessage - } - Headers UnionExample200ResponseHeaders -} - -func (response UnionExample200JSONResponse) VisitUnionExampleResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/json") - w.Header().Set("header1", fmt.Sprint(response.Headers.Header1)) - w.Header().Set("header2", fmt.Sprint(response.Headers.Header2)) - w.WriteHeader(200) - - return json.NewEncoder(w).Encode(response.Body.union) -} - -type UnionExample400Response = BadrequestResponse - -func (response UnionExample400Response) VisitUnionExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type UnionExampledefaultResponse struct { - StatusCode int -} - -func (response UnionExampledefaultResponse) VisitUnionExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -// StrictServerInterface represents all server handlers. -type StrictServerInterface interface { - - // (POST /json) - JSONExample(ctx context.Context, request JSONExampleRequestObject) (JSONExampleResponseObject, error) - - // (POST /multipart) - MultipartExample(ctx context.Context, request MultipartExampleRequestObject) (MultipartExampleResponseObject, error) - - // (POST /multipart-related) - MultipartRelatedExample(ctx context.Context, request MultipartRelatedExampleRequestObject) (MultipartRelatedExampleResponseObject, error) - - // (POST /multiple) - MultipleRequestAndResponseTypes(ctx context.Context, request MultipleRequestAndResponseTypesRequestObject) (MultipleRequestAndResponseTypesResponseObject, error) - - // (POST /required-json-body) - RequiredJSONBody(ctx context.Context, request RequiredJSONBodyRequestObject) (RequiredJSONBodyResponseObject, error) - - // (POST /required-text-body) - RequiredTextBody(ctx context.Context, request RequiredTextBodyRequestObject) (RequiredTextBodyResponseObject, error) - - // (GET /reserved-go-keyword-parameters/{type}) - ReservedGoKeywordParameters(ctx context.Context, request ReservedGoKeywordParametersRequestObject) (ReservedGoKeywordParametersResponseObject, error) - - // (POST /reusable-responses) - ReusableResponses(ctx context.Context, request ReusableResponsesRequestObject) (ReusableResponsesResponseObject, error) - - // (POST /text) - TextExample(ctx context.Context, request TextExampleRequestObject) (TextExampleResponseObject, error) - - // (POST /unknown) - UnknownExample(ctx context.Context, request UnknownExampleRequestObject) (UnknownExampleResponseObject, error) - - // (POST /unspecified-content-type) - UnspecifiedContentType(ctx context.Context, request UnspecifiedContentTypeRequestObject) (UnspecifiedContentTypeResponseObject, error) - - // (POST /urlencoded) - URLEncodedExample(ctx context.Context, request URLEncodedExampleRequestObject) (URLEncodedExampleResponseObject, error) - - // (POST /with-headers) - HeadersExample(ctx context.Context, request HeadersExampleRequestObject) (HeadersExampleResponseObject, error) - - // (POST /with-union) - UnionExample(ctx context.Context, request UnionExampleRequestObject) (UnionExampleResponseObject, error) -} - -type StrictHandlerFunc = strictecho.StrictEchoHandlerFunc -type StrictMiddlewareFunc = strictecho.StrictEchoMiddlewareFunc - -func NewStrictHandler(ssi StrictServerInterface, middlewares []StrictMiddlewareFunc) ServerInterface { - return &strictHandler{ssi: ssi, middlewares: middlewares} -} - -type strictHandler struct { - ssi StrictServerInterface - middlewares []StrictMiddlewareFunc -} - -// JSONExample operation middleware -func (sh *strictHandler) JSONExample(ctx echo.Context) error { - var request JSONExampleRequestObject - - var body JSONExampleJSONRequestBody - if err := ctx.Bind(&body); err != nil { - if !errors.Is(err, io.EOF) { - return err - } - } else { - request.Body = &body - } - - handler := func(ctx echo.Context, request interface{}) (interface{}, error) { - return sh.ssi.JSONExample(ctx.Request().Context(), request.(JSONExampleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "JSONExample") - } - - response, err := handler(ctx, request) - - if err != nil { - return err - } else if validResponse, ok := response.(JSONExampleResponseObject); ok { - return validResponse.VisitJSONExampleResponse(ctx.Response()) - } else if response != nil { - return fmt.Errorf("unexpected response type: %T", response) - } - return nil -} - -// MultipartExample operation middleware -func (sh *strictHandler) MultipartExample(ctx echo.Context) error { - var request MultipartExampleRequestObject - - if reader, err := ctx.Request().MultipartReader(); err != nil { - return err - } else { - request.Body = reader - } - - handler := func(ctx echo.Context, request interface{}) (interface{}, error) { - return sh.ssi.MultipartExample(ctx.Request().Context(), request.(MultipartExampleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "MultipartExample") - } - - response, err := handler(ctx, request) - - if err != nil { - return err - } else if validResponse, ok := response.(MultipartExampleResponseObject); ok { - return validResponse.VisitMultipartExampleResponse(ctx.Response()) - } else if response != nil { - return fmt.Errorf("unexpected response type: %T", response) - } - return nil -} - -// MultipartRelatedExample operation middleware -func (sh *strictHandler) MultipartRelatedExample(ctx echo.Context) error { - var request MultipartRelatedExampleRequestObject - - if _, params, err := mime.ParseMediaType(ctx.Request().Header.Get("Content-Type")); err != nil { - return err - } else if boundary := params["boundary"]; boundary == "" { - return http.ErrMissingBoundary - } else { - request.Body = multipart.NewReader(ctx.Request().Body, boundary) - } - - handler := func(ctx echo.Context, request interface{}) (interface{}, error) { - return sh.ssi.MultipartRelatedExample(ctx.Request().Context(), request.(MultipartRelatedExampleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "MultipartRelatedExample") - } - - response, err := handler(ctx, request) - - if err != nil { - return err - } else if validResponse, ok := response.(MultipartRelatedExampleResponseObject); ok { - return validResponse.VisitMultipartRelatedExampleResponse(ctx.Response()) - } else if response != nil { - return fmt.Errorf("unexpected response type: %T", response) - } - return nil -} - -// MultipleRequestAndResponseTypes operation middleware -func (sh *strictHandler) MultipleRequestAndResponseTypes(ctx echo.Context) error { - var request MultipleRequestAndResponseTypesRequestObject - - if strings.HasPrefix(ctx.Request().Header.Get("Content-Type"), "application/json") { - var body MultipleRequestAndResponseTypesJSONRequestBody - if err := ctx.Bind(&body); err != nil { - if !errors.Is(err, io.EOF) { - return err - } - } else { - request.JSONBody = &body - } - } - if strings.HasPrefix(ctx.Request().Header.Get("Content-Type"), "application/x-www-form-urlencoded") { - if form, err := ctx.FormParams(); err == nil { - var body MultipleRequestAndResponseTypesFormdataRequestBody - if err := runtime.BindForm(&body, form, nil, nil); err != nil { - return err - } - request.FormdataBody = &body - } else { - return err - } - } - if strings.HasPrefix(ctx.Request().Header.Get("Content-Type"), "image/png") { - request.Body = ctx.Request().Body - } - if strings.HasPrefix(ctx.Request().Header.Get("Content-Type"), "multipart/form-data") { - if reader, err := ctx.Request().MultipartReader(); err != nil { - return err - } else { - request.MultipartBody = reader - } - } - if strings.HasPrefix(ctx.Request().Header.Get("Content-Type"), "text/plain") { - data, err := io.ReadAll(ctx.Request().Body) - if err != nil { - return err - } - if len(data) > 0 { - body := MultipleRequestAndResponseTypesTextRequestBody(data) - request.TextBody = &body - } - } - - handler := func(ctx echo.Context, request interface{}) (interface{}, error) { - return sh.ssi.MultipleRequestAndResponseTypes(ctx.Request().Context(), request.(MultipleRequestAndResponseTypesRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "MultipleRequestAndResponseTypes") - } - - response, err := handler(ctx, request) - - if err != nil { - return err - } else if validResponse, ok := response.(MultipleRequestAndResponseTypesResponseObject); ok { - return validResponse.VisitMultipleRequestAndResponseTypesResponse(ctx.Response()) - } else if response != nil { - return fmt.Errorf("unexpected response type: %T", response) - } - return nil -} - -// RequiredJSONBody operation middleware -func (sh *strictHandler) RequiredJSONBody(ctx echo.Context) error { - var request RequiredJSONBodyRequestObject - - var body RequiredJSONBodyJSONRequestBody - if err := ctx.Bind(&body); err != nil { - return err - } - request.Body = &body - - handler := func(ctx echo.Context, request interface{}) (interface{}, error) { - return sh.ssi.RequiredJSONBody(ctx.Request().Context(), request.(RequiredJSONBodyRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "RequiredJSONBody") - } - - response, err := handler(ctx, request) - - if err != nil { - return err - } else if validResponse, ok := response.(RequiredJSONBodyResponseObject); ok { - return validResponse.VisitRequiredJSONBodyResponse(ctx.Response()) - } else if response != nil { - return fmt.Errorf("unexpected response type: %T", response) - } - return nil -} - -// RequiredTextBody operation middleware -func (sh *strictHandler) RequiredTextBody(ctx echo.Context) error { - var request RequiredTextBodyRequestObject - - data, err := io.ReadAll(ctx.Request().Body) - if err != nil { - return err - } - body := RequiredTextBodyTextRequestBody(data) - request.Body = &body - - handler := func(ctx echo.Context, request interface{}) (interface{}, error) { - return sh.ssi.RequiredTextBody(ctx.Request().Context(), request.(RequiredTextBodyRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "RequiredTextBody") - } - - response, err := handler(ctx, request) - - if err != nil { - return err - } else if validResponse, ok := response.(RequiredTextBodyResponseObject); ok { - return validResponse.VisitRequiredTextBodyResponse(ctx.Response()) - } else if response != nil { - return fmt.Errorf("unexpected response type: %T", response) - } - return nil -} - -// ReservedGoKeywordParameters operation middleware -func (sh *strictHandler) ReservedGoKeywordParameters(ctx echo.Context, pType string) error { - var request ReservedGoKeywordParametersRequestObject - - request.Type = pType - - handler := func(ctx echo.Context, request interface{}) (interface{}, error) { - return sh.ssi.ReservedGoKeywordParameters(ctx.Request().Context(), request.(ReservedGoKeywordParametersRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "ReservedGoKeywordParameters") - } - - response, err := handler(ctx, request) - - if err != nil { - return err - } else if validResponse, ok := response.(ReservedGoKeywordParametersResponseObject); ok { - return validResponse.VisitReservedGoKeywordParametersResponse(ctx.Response()) - } else if response != nil { - return fmt.Errorf("unexpected response type: %T", response) - } - return nil -} - -// ReusableResponses operation middleware -func (sh *strictHandler) ReusableResponses(ctx echo.Context) error { - var request ReusableResponsesRequestObject - - var body ReusableResponsesJSONRequestBody - if err := ctx.Bind(&body); err != nil { - if !errors.Is(err, io.EOF) { - return err - } - } else { - request.Body = &body - } - - handler := func(ctx echo.Context, request interface{}) (interface{}, error) { - return sh.ssi.ReusableResponses(ctx.Request().Context(), request.(ReusableResponsesRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "ReusableResponses") - } - - response, err := handler(ctx, request) - - if err != nil { - return err - } else if validResponse, ok := response.(ReusableResponsesResponseObject); ok { - return validResponse.VisitReusableResponsesResponse(ctx.Response()) - } else if response != nil { - return fmt.Errorf("unexpected response type: %T", response) - } - return nil -} - -// TextExample operation middleware -func (sh *strictHandler) TextExample(ctx echo.Context) error { - var request TextExampleRequestObject - - data, err := io.ReadAll(ctx.Request().Body) - if err != nil { - return err - } - if len(data) > 0 { - body := TextExampleTextRequestBody(data) - request.Body = &body - } - - handler := func(ctx echo.Context, request interface{}) (interface{}, error) { - return sh.ssi.TextExample(ctx.Request().Context(), request.(TextExampleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "TextExample") - } - - response, err := handler(ctx, request) - - if err != nil { - return err - } else if validResponse, ok := response.(TextExampleResponseObject); ok { - return validResponse.VisitTextExampleResponse(ctx.Response()) - } else if response != nil { - return fmt.Errorf("unexpected response type: %T", response) - } - return nil -} - -// UnknownExample operation middleware -func (sh *strictHandler) UnknownExample(ctx echo.Context) error { - var request UnknownExampleRequestObject - - request.Body = ctx.Request().Body - - handler := func(ctx echo.Context, request interface{}) (interface{}, error) { - return sh.ssi.UnknownExample(ctx.Request().Context(), request.(UnknownExampleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "UnknownExample") - } - - response, err := handler(ctx, request) - - if err != nil { - return err - } else if validResponse, ok := response.(UnknownExampleResponseObject); ok { - return validResponse.VisitUnknownExampleResponse(ctx.Response()) - } else if response != nil { - return fmt.Errorf("unexpected response type: %T", response) - } - return nil -} - -// UnspecifiedContentType operation middleware -func (sh *strictHandler) UnspecifiedContentType(ctx echo.Context) error { - var request UnspecifiedContentTypeRequestObject - - request.ContentType = ctx.Request().Header.Get("Content-Type") - - request.Body = ctx.Request().Body - - handler := func(ctx echo.Context, request interface{}) (interface{}, error) { - return sh.ssi.UnspecifiedContentType(ctx.Request().Context(), request.(UnspecifiedContentTypeRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "UnspecifiedContentType") - } - - response, err := handler(ctx, request) - - if err != nil { - return err - } else if validResponse, ok := response.(UnspecifiedContentTypeResponseObject); ok { - return validResponse.VisitUnspecifiedContentTypeResponse(ctx.Response()) - } else if response != nil { - return fmt.Errorf("unexpected response type: %T", response) - } - return nil -} - -// URLEncodedExample operation middleware -func (sh *strictHandler) URLEncodedExample(ctx echo.Context) error { - var request URLEncodedExampleRequestObject - - if form, err := ctx.FormParams(); err == nil { - var body URLEncodedExampleFormdataRequestBody - if err := runtime.BindForm(&body, form, nil, nil); err != nil { - return err - } - request.Body = &body - } else { - return err - } - - handler := func(ctx echo.Context, request interface{}) (interface{}, error) { - return sh.ssi.URLEncodedExample(ctx.Request().Context(), request.(URLEncodedExampleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "URLEncodedExample") - } - - response, err := handler(ctx, request) - - if err != nil { - return err - } else if validResponse, ok := response.(URLEncodedExampleResponseObject); ok { - return validResponse.VisitURLEncodedExampleResponse(ctx.Response()) - } else if response != nil { - return fmt.Errorf("unexpected response type: %T", response) - } - return nil -} - -// HeadersExample operation middleware -func (sh *strictHandler) HeadersExample(ctx echo.Context, params HeadersExampleParams) error { - var request HeadersExampleRequestObject - - request.Params = params - - var body HeadersExampleJSONRequestBody - if err := ctx.Bind(&body); err != nil { - if !errors.Is(err, io.EOF) { - return err - } - } else { - request.Body = &body - } - - handler := func(ctx echo.Context, request interface{}) (interface{}, error) { - return sh.ssi.HeadersExample(ctx.Request().Context(), request.(HeadersExampleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "HeadersExample") - } - - response, err := handler(ctx, request) - - if err != nil { - return err - } else if validResponse, ok := response.(HeadersExampleResponseObject); ok { - return validResponse.VisitHeadersExampleResponse(ctx.Response()) - } else if response != nil { - return fmt.Errorf("unexpected response type: %T", response) - } - return nil -} - -// UnionExample operation middleware -func (sh *strictHandler) UnionExample(ctx echo.Context) error { - var request UnionExampleRequestObject - - var body UnionExampleJSONRequestBody - if err := ctx.Bind(&body); err != nil { - if !errors.Is(err, io.EOF) { - return err - } - } else { - request.Body = &body - } - - handler := func(ctx echo.Context, request interface{}) (interface{}, error) { - return sh.ssi.UnionExample(ctx.Request().Context(), request.(UnionExampleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "UnionExample") - } - - response, err := handler(ctx, request) - - if err != nil { - return err - } else if validResponse, ok := response.(UnionExampleResponseObject); ok { - return validResponse.VisitUnionExampleResponse(ctx.Response()) - } else if response != nil { - return fmt.Errorf("unexpected response type: %T", response) - } - return nil -} - -// Base64 encoded, gzipped, json marshaled Swagger object -var swaggerSpec = []string{ - - "H4sIAAAAAAAC/+xZTXPbNhP+Kzt431NKmrbjE2+NJ5O2aeuObJ86PkDESkJCAiiwFK3R6L93QEBfFq1K", - "qT4ynt5Ecr/wPLuLBTRlha6MVqjIsXzKLDqjlcP2oc+Fxb9qdOSfBLrCSkNSK5azD1z04rdZwizWjvdL", - "nKt7+UIrQtWqcmNKWXCvmn1xXn/KXDHCivtf/7c4YDn7X7YMJQtfXYbPvDIlstlslryI4O4zS9gIuUDb", - "Rht+Xq3bpolBljNHVqoh80aC2HWnmFSEQ7TemxeNQXiBeRz5lBmrDVqSAaMxL2vs9hTf6P4XLCisQKqB", - "3sTyViviUjkQcjBAi4ogggfehgNXG6MtoYD+BLyHgsChHaNlCSNJPjB2v/oeYsCOJWyM1gVHVxeXF5ee", - "L21QcSNZzt63rxJmOI3aBS0IMrqL91/u734H6YDXpCtOsuBlOYGKWzfiJQqQirQPsS7IXbDWk22J/1lE", - "7Y8RSp81bQJ90GJyjIRp83Ilna8vL0+Ul7OE3QRnXTYWQWUrBdaaGfC67MD8UX1VulGA1mobV5ZVdUnS", - "cEurXK2j/dtcZBfIF/aygbZVKjjxI6F+KE/nBj61WHJCsQMBvSC5Hw8r5o/Kwr/xc1YOYj/u7FP3I904", - "GOkGSINAXkIjaQRzxRcNVirg4KQalgjzoJJOMkuM296PSvTiWh68jaP3s2TNynPaNE3aFlBtS1SFFt9G", - "YcJkxYeYGTVcV/e2ObGc9SfkU3ZzgztQISeM8JkyU3Kptu/eJ2rp/yF9sMIO5eofpUWRekbSfqyP7sKN", - "5QVeyg8ac90EnIZKOl+l4aMb6boUwMuGT1zoD5sTRy+q+8mjLcyjjx3BgffJcrI1vu0xZEGtz6zzUPuA", - "z/SP1O6R+PvSd+qa2p+i9kwg0qFOv+Kk0VakhlteIaF12dTHOfO2hthh8o+FJBRcQR9B8QoF8AGhhU8a", - "oknXwU/w+0l/DiJLU+2BY/GQ/zllHrz2EMIS5h2wPOD3ko5kC8BPx6VqjmY46qZrrl5L+Cgyh87iwPmB", - "pIvjDvyCp96KxHmOTNtzc+Pwf4qk9ky+Pnj7lrDLsH3AweN77wJ1ePk6ZlFrF9i+cY7ZAcWxFKizytzs", - "aflsoDqDhRxIFGlcRRpie60l3GpVWKT1A4jfDJUmWBiD/gRohBAQaPfHBqGqHYHhzoGktouUMtwVCdxo", - "Ho/LyG6Dp4dlO93G6rsjcfruXIzeXF7tr/L+yHmzdpB4pR57v34MMvvemB3sxLLneetwfs9Uzo2kUbpy", - "pdxdwj8FgeWeXqAc+4lICbBItVUoYCz5/Bp0ozajgSWtXbNQCGM5Dc2vt/cZiJKttq5Zsu0K/OkNX9Ae", - "84+DU+VpreS2i/pH/xniDP1yb5BafafX8LwktIqTHOMPh7m/2bSiFd4N2kp7wXKyo4ent5dVs4SFf45C", - "C6pt6fsEkcmzLPzjdOEaPhyivZA640Z6FP4OAAD//0nTejA+HAAA", -} - -// GetSwagger returns the content of the embedded swagger specification file -// or error if failed to decode -func decodeSpec() ([]byte, error) { - zipped, err := base64.StdEncoding.DecodeString(strings.Join(swaggerSpec, "")) - if err != nil { - return nil, fmt.Errorf("error base64 decoding spec: %w", err) - } - zr, err := gzip.NewReader(bytes.NewReader(zipped)) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - var buf bytes.Buffer - _, err = buf.ReadFrom(zr) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - - return buf.Bytes(), nil -} - -var rawSpec = decodeSpecCached() - -// a naive cached of a decoded swagger spec -func decodeSpecCached() func() ([]byte, error) { - data, err := decodeSpec() - return func() ([]byte, error) { - return data, err - } -} - -// Constructs a synthetic filesystem for resolving external references when loading openapi specifications. -func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { - res := make(map[string]func() ([]byte, error)) - if len(pathToFile) > 0 { - res[pathToFile] = rawSpec - } - - return res -} - -// GetSwagger returns the Swagger specification corresponding to the generated code -// in this file. The external references of Swagger specification are resolved. -// The logic of resolving external references is tightly connected to "import-mapping" feature. -// Externally referenced files must be embedded in the corresponding golang packages. -// Urls can be supported but this task was out of the scope. -func GetSwagger() (swagger *openapi3.T, err error) { - resolvePath := PathToRawSpec("") - - loader := openapi3.NewLoader() - loader.IsExternalRefsAllowed = true - loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() - pathToFile = path.Clean(pathToFile) - getSpec, ok := resolvePath[pathToFile] - if !ok { - err1 := fmt.Errorf("path not found: %s", pathToFile) - return nil, err1 - } - return getSpec() - } - var specData []byte - specData, err = rawSpec() - if err != nil { - return - } - swagger, err = loader.LoadFromData(specData) - if err != nil { - return - } - return -} diff --git a/internal/test/strict-server/echo/server.go b/internal/test/strict-server/echo/server.go deleted file mode 100644 index 914f967268..0000000000 --- a/internal/test/strict-server/echo/server.go +++ /dev/null @@ -1,152 +0,0 @@ -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=server.cfg.yaml ../strict-schema.yaml -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=types.cfg.yaml ../strict-schema.yaml - -package api - -import ( - "context" - "encoding/json" - "io" - "mime/multipart" -) - -type StrictServer struct { -} - -func (s StrictServer) JSONExample(ctx context.Context, request JSONExampleRequestObject) (JSONExampleResponseObject, error) { - return JSONExample200JSONResponse(*request.Body), nil -} - -func (s StrictServer) MultipartExample(ctx context.Context, request MultipartExampleRequestObject) (MultipartExampleResponseObject, error) { - return MultipartExample200MultipartResponse(func(writer *multipart.Writer) error { - for { - part, err := request.Body.NextPart() - if err == io.EOF { - return nil - } else if err != nil { - return err - } - w, err := writer.CreatePart(part.Header) - if err != nil { - return err - } - _, err = io.Copy(w, part) - if err != nil { - return err - } - if err = part.Close(); err != nil { - return err - } - } - }), nil -} - -func (s StrictServer) MultipartRelatedExample(ctx context.Context, request MultipartRelatedExampleRequestObject) (MultipartRelatedExampleResponseObject, error) { - return MultipartRelatedExample200MultipartResponse(func(writer *multipart.Writer) error { - for { - part, err := request.Body.NextPart() - if err == io.EOF { - return nil - } else if err != nil { - return err - } - w, err := writer.CreatePart(part.Header) - if err != nil { - return err - } - _, err = io.Copy(w, part) - if err != nil { - return err - } - if err = part.Close(); err != nil { - return err - } - } - }), nil -} - -func (s StrictServer) MultipleRequestAndResponseTypes(ctx context.Context, request MultipleRequestAndResponseTypesRequestObject) (MultipleRequestAndResponseTypesResponseObject, error) { - switch { - case request.Body != nil: - return MultipleRequestAndResponseTypes200ImagepngResponse{Body: request.Body}, nil - case request.JSONBody != nil: - return MultipleRequestAndResponseTypes200JSONResponse(*request.JSONBody), nil - case request.FormdataBody != nil: - return MultipleRequestAndResponseTypes200FormdataResponse(*request.FormdataBody), nil - case request.TextBody != nil: - return MultipleRequestAndResponseTypes200TextResponse(*request.TextBody), nil - case request.MultipartBody != nil: - return MultipleRequestAndResponseTypes200MultipartResponse(func(writer *multipart.Writer) error { - for { - part, err := request.MultipartBody.NextPart() - if err == io.EOF { - return nil - } else if err != nil { - return err - } - w, err := writer.CreatePart(part.Header) - if err != nil { - return err - } - _, err = io.Copy(w, part) - if err != nil { - return err - } - if err = part.Close(); err != nil { - return err - } - } - }), nil - default: - return MultipleRequestAndResponseTypes400Response{}, nil - } -} - -func (s StrictServer) TextExample(ctx context.Context, request TextExampleRequestObject) (TextExampleResponseObject, error) { - return TextExample200TextResponse(*request.Body), nil -} - -func (s StrictServer) UnknownExample(ctx context.Context, request UnknownExampleRequestObject) (UnknownExampleResponseObject, error) { - return UnknownExample200Videomp4Response{Body: request.Body}, nil -} - -func (s StrictServer) UnspecifiedContentType(ctx context.Context, request UnspecifiedContentTypeRequestObject) (UnspecifiedContentTypeResponseObject, error) { - return UnspecifiedContentType200VideoResponse{Body: request.Body, ContentType: request.ContentType}, nil -} - -func (s StrictServer) URLEncodedExample(ctx context.Context, request URLEncodedExampleRequestObject) (URLEncodedExampleResponseObject, error) { - return URLEncodedExample200FormdataResponse(*request.Body), nil -} - -func (s StrictServer) HeadersExample(ctx context.Context, request HeadersExampleRequestObject) (HeadersExampleResponseObject, error) { - return HeadersExample200JSONResponse{Body: *request.Body, Headers: HeadersExample200ResponseHeaders{Header1: request.Params.Header1, Header2: *request.Params.Header2}}, nil -} - -func (s StrictServer) ReusableResponses(ctx context.Context, request ReusableResponsesRequestObject) (ReusableResponsesResponseObject, error) { - return ReusableResponses200JSONResponse{ReusableresponseJSONResponse: ReusableresponseJSONResponse{Body: *request.Body}}, nil -} - -func (s StrictServer) RequiredJSONBody(ctx context.Context, request RequiredJSONBodyRequestObject) (RequiredJSONBodyResponseObject, error) { - return RequiredJSONBody200JSONResponse(*request.Body), nil -} - -func (s StrictServer) RequiredTextBody(ctx context.Context, request RequiredTextBodyRequestObject) (RequiredTextBodyResponseObject, error) { - return RequiredTextBody200TextResponse(*request.Body), nil -} - -func (s StrictServer) ReservedGoKeywordParameters(ctx context.Context, request ReservedGoKeywordParametersRequestObject) (ReservedGoKeywordParametersResponseObject, error) { - return ReservedGoKeywordParameters200TextResponse(""), nil -} - -func (s StrictServer) UnionExample(ctx context.Context, request UnionExampleRequestObject) (UnionExampleResponseObject, error) { - union, err := json.Marshal(*request.Body) - if err != nil { - return nil, err - } - - return UnionExample200JSONResponse{ - Body: struct{ union json.RawMessage }{ - union: union, - }, - }, nil -} diff --git a/internal/test/strict-server/echo/types.gen.go b/internal/test/strict-server/echo/types.gen.go deleted file mode 100644 index fac014c4bb..0000000000 --- a/internal/test/strict-server/echo/types.gen.go +++ /dev/null @@ -1,69 +0,0 @@ -// Package api provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package api - -// Example defines model for example. -type Example struct { - Value *string `json:"value,omitempty"` -} - -// Reusableresponse defines model for reusableresponse. -type Reusableresponse = Example - -// MultipleRequestAndResponseTypesTextBody defines parameters for MultipleRequestAndResponseTypes. -type MultipleRequestAndResponseTypesTextBody = string - -// RequiredTextBodyTextBody defines parameters for RequiredTextBody. -type RequiredTextBodyTextBody = string - -// TextExampleTextBody defines parameters for TextExample. -type TextExampleTextBody = string - -// HeadersExampleParams defines parameters for HeadersExample. -type HeadersExampleParams struct { - Header1 string `json:"header1"` - Header2 *int `json:"header2,omitempty"` -} - -// JSONExampleJSONRequestBody defines body for JSONExample for application/json ContentType. -type JSONExampleJSONRequestBody = Example - -// MultipartExampleMultipartRequestBody defines body for MultipartExample for multipart/form-data ContentType. -type MultipartExampleMultipartRequestBody = Example - -// MultipartRelatedExampleMultipartRequestBody defines body for MultipartRelatedExample for multipart/related ContentType. -type MultipartRelatedExampleMultipartRequestBody = Example - -// MultipleRequestAndResponseTypesJSONRequestBody defines body for MultipleRequestAndResponseTypes for application/json ContentType. -type MultipleRequestAndResponseTypesJSONRequestBody = Example - -// MultipleRequestAndResponseTypesFormdataRequestBody defines body for MultipleRequestAndResponseTypes for application/x-www-form-urlencoded ContentType. -type MultipleRequestAndResponseTypesFormdataRequestBody = Example - -// MultipleRequestAndResponseTypesMultipartRequestBody defines body for MultipleRequestAndResponseTypes for multipart/form-data ContentType. -type MultipleRequestAndResponseTypesMultipartRequestBody = Example - -// MultipleRequestAndResponseTypesTextRequestBody defines body for MultipleRequestAndResponseTypes for text/plain ContentType. -type MultipleRequestAndResponseTypesTextRequestBody = MultipleRequestAndResponseTypesTextBody - -// RequiredJSONBodyJSONRequestBody defines body for RequiredJSONBody for application/json ContentType. -type RequiredJSONBodyJSONRequestBody = Example - -// RequiredTextBodyTextRequestBody defines body for RequiredTextBody for text/plain ContentType. -type RequiredTextBodyTextRequestBody = RequiredTextBodyTextBody - -// ReusableResponsesJSONRequestBody defines body for ReusableResponses for application/json ContentType. -type ReusableResponsesJSONRequestBody = Example - -// TextExampleTextRequestBody defines body for TextExample for text/plain ContentType. -type TextExampleTextRequestBody = TextExampleTextBody - -// URLEncodedExampleFormdataRequestBody defines body for URLEncodedExample for application/x-www-form-urlencoded ContentType. -type URLEncodedExampleFormdataRequestBody = Example - -// HeadersExampleJSONRequestBody defines body for HeadersExample for application/json ContentType. -type HeadersExampleJSONRequestBody = Example - -// UnionExampleJSONRequestBody defines body for UnionExample for application/json ContentType. -type UnionExampleJSONRequestBody = Example diff --git a/internal/test/strict-server/fiber/fiber_strict_test.go b/internal/test/strict-server/fiber/fiber_strict_test.go deleted file mode 100644 index cb8b509b08..0000000000 --- a/internal/test/strict-server/fiber/fiber_strict_test.go +++ /dev/null @@ -1,229 +0,0 @@ -package api - -import ( - "bytes" - "encoding/json" - "io" - "mime" - "mime/multipart" - "net/http" - "net/url" - "strings" - "testing" - - "github.com/gofiber/fiber/v2" - "github.com/gofiber/fiber/v2/middleware/adaptor" - "github.com/stretchr/testify/assert" - - clientAPI "github.com/oapi-codegen/oapi-codegen/v2/internal/test/strict-server/client" - "github.com/oapi-codegen/runtime" - "github.com/oapi-codegen/testutil" -) - -func TestFiberServer(t *testing.T) { - server := StrictServer{} - strictHandler := NewStrictHandler(server, nil) - r := fiber.New() - RegisterHandlers(r, strictHandler) - testImpl(t, adaptor.FiberApp(r)) -} - -func testImpl(t *testing.T, handler http.Handler) { - t.Run("JSONExample", func(t *testing.T) { - value := "123" - requestBody := clientAPI.Example{Value: &value} - rr := testutil.NewRequest().Post("/json").WithJsonBody(requestBody).GoWithHTTPHandler(t, handler).Recorder - assert.Equal(t, http.StatusOK, rr.Code) - assert.True(t, strings.HasPrefix(rr.Header().Get("Content-Type"), "application/json")) - var responseBody clientAPI.Example - err := json.NewDecoder(rr.Body).Decode(&responseBody) - assert.NoError(t, err) - assert.Equal(t, requestBody, responseBody) - }) - t.Run("URLEncodedExample", func(t *testing.T) { - value := "456" - requestBody := clientAPI.Example{Value: &value} - requestBodyEncoded, err := runtime.MarshalForm(&requestBody, nil) - assert.NoError(t, err) - rr := testutil.NewRequest().Post("/urlencoded").WithContentType("application/x-www-form-urlencoded").WithBody([]byte(requestBodyEncoded.Encode())).GoWithHTTPHandler(t, handler).Recorder - assert.Equal(t, http.StatusOK, rr.Code) - assert.Equal(t, "application/x-www-form-urlencoded", rr.Header().Get("Content-Type")) - values, err := url.ParseQuery(rr.Body.String()) - assert.NoError(t, err) - var responseBody clientAPI.Example - err = runtime.BindForm(&responseBody, values, nil, nil) - assert.NoError(t, err) - assert.Equal(t, requestBody, responseBody) - }) - t.Run("MultipartExample", func(t *testing.T) { - value := "789" - fieldName := "value" - var writer bytes.Buffer - mw := multipart.NewWriter(&writer) - field, err := mw.CreateFormField(fieldName) - assert.NoError(t, err) - _, _ = field.Write([]byte(value)) - assert.NoError(t, mw.Close()) - rr := testutil.NewRequest().Post("/multipart").WithContentType(mw.FormDataContentType()).WithBody(writer.Bytes()).GoWithHTTPHandler(t, handler).Recorder - assert.Equal(t, http.StatusOK, rr.Code) - contentType, params, err := mime.ParseMediaType(rr.Header().Get("Content-Type")) - assert.NoError(t, err) - assert.Equal(t, "multipart/form-data", contentType) - reader := multipart.NewReader(rr.Body, params["boundary"]) - part, err := reader.NextPart() - assert.NoError(t, err) - assert.Equal(t, part.FormName(), fieldName) - readValue, err := io.ReadAll(part) - assert.NoError(t, err) - assert.Equal(t, value, string(readValue)) - _, err = reader.NextPart() - assert.Equal(t, io.EOF, err) - }) - t.Run("MultipartRelatedExample", func(t *testing.T) { - value := "789" - fieldName := "value" - var writer bytes.Buffer - mw := multipart.NewWriter(&writer) - field, err := mw.CreateFormField(fieldName) - assert.NoError(t, err) - _, _ = field.Write([]byte(value)) - assert.NoError(t, mw.Close()) - rr := testutil.NewRequest().Post("/multipart-related").WithContentType(mime.FormatMediaType("multipart/related", map[string]string{"boundary": mw.Boundary()})).WithBody(writer.Bytes()).GoWithHTTPHandler(t, handler).Recorder - assert.Equal(t, http.StatusOK, rr.Code) - contentType, params, err := mime.ParseMediaType(rr.Header().Get("Content-Type")) - assert.NoError(t, err) - assert.Equal(t, "multipart/related", contentType) - reader := multipart.NewReader(rr.Body, params["boundary"]) - part, err := reader.NextPart() - assert.NoError(t, err) - assert.Equal(t, part.FormName(), fieldName) - readValue, err := io.ReadAll(part) - assert.NoError(t, err) - assert.Equal(t, value, string(readValue)) - _, err = reader.NextPart() - assert.Equal(t, io.EOF, err) - }) - t.Run("TextExample", func(t *testing.T) { - value := "text" - rr := testutil.NewRequest().Post("/text").WithContentType("text/plain").WithBody([]byte(value)).GoWithHTTPHandler(t, handler).Recorder - assert.Equal(t, http.StatusOK, rr.Code) - assert.Equal(t, "text/plain", rr.Header().Get("Content-Type")) - assert.Equal(t, value, rr.Body.String()) - }) - t.Run("UnknownExample", func(t *testing.T) { - data := []byte("unknown data") - rr := testutil.NewRequest().Post("/unknown").WithContentType("image/png").WithBody(data).GoWithHTTPHandler(t, handler).Recorder - assert.Equal(t, http.StatusOK, rr.Code) - assert.Equal(t, "video/mp4", rr.Header().Get("Content-Type")) - assert.Equal(t, data, rr.Body.Bytes()) - }) - t.Run("MultipleRequestAndResponseTypesJSON", func(t *testing.T) { - value := "123" - requestBody := clientAPI.Example{Value: &value} - rr := testutil.NewRequest().Post("/multiple").WithJsonBody(requestBody).GoWithHTTPHandler(t, handler).Recorder - assert.Equal(t, http.StatusOK, rr.Code) - assert.True(t, strings.HasPrefix(rr.Header().Get("Content-Type"), "application/json")) - var responseBody clientAPI.Example - err := json.NewDecoder(rr.Body).Decode(&responseBody) - assert.NoError(t, err) - assert.Equal(t, requestBody, responseBody) - }) - t.Run("MultipleRequestAndResponseTypesFormdata", func(t *testing.T) { - value := "456" - requestBody := clientAPI.Example{Value: &value} - requestBodyEncoded, err := runtime.MarshalForm(&requestBody, nil) - assert.NoError(t, err) - rr := testutil.NewRequest().Post("/multiple").WithContentType("application/x-www-form-urlencoded").WithBody([]byte(requestBodyEncoded.Encode())).GoWithHTTPHandler(t, handler).Recorder - assert.Equal(t, http.StatusOK, rr.Code) - assert.Equal(t, "application/x-www-form-urlencoded", rr.Header().Get("Content-Type")) - values, err := url.ParseQuery(rr.Body.String()) - assert.NoError(t, err) - var responseBody clientAPI.Example - err = runtime.BindForm(&responseBody, values, nil, nil) - assert.NoError(t, err) - assert.Equal(t, requestBody, responseBody) - }) - t.Run("MultipleRequestAndResponseTypesMultipart", func(t *testing.T) { - value := "789" - fieldName := "value" - var writer bytes.Buffer - mw := multipart.NewWriter(&writer) - field, err := mw.CreateFormField(fieldName) - assert.NoError(t, err) - _, _ = field.Write([]byte(value)) - assert.NoError(t, mw.Close()) - rr := testutil.NewRequest().Post("/multiple").WithContentType(mw.FormDataContentType()).WithBody(writer.Bytes()).GoWithHTTPHandler(t, handler).Recorder - assert.Equal(t, http.StatusOK, rr.Code) - contentType, params, err := mime.ParseMediaType(rr.Header().Get("Content-Type")) - assert.NoError(t, err) - assert.Equal(t, "multipart/form-data", contentType) - reader := multipart.NewReader(rr.Body, params["boundary"]) - part, err := reader.NextPart() - assert.NoError(t, err) - assert.Equal(t, part.FormName(), fieldName) - readValue, err := io.ReadAll(part) - assert.NoError(t, err) - assert.Equal(t, value, string(readValue)) - _, err = reader.NextPart() - assert.Equal(t, io.EOF, err) - }) - t.Run("MultipleRequestAndResponseTypesText", func(t *testing.T) { - value := "text" - rr := testutil.NewRequest().Post("/multiple").WithContentType("text/plain").WithBody([]byte(value)).GoWithHTTPHandler(t, handler).Recorder - assert.Equal(t, http.StatusOK, rr.Code) - assert.Equal(t, "text/plain", rr.Header().Get("Content-Type")) - assert.Equal(t, value, rr.Body.String()) - }) - t.Run("MultipleRequestAndResponseTypesImage", func(t *testing.T) { - data := []byte("unknown data") - rr := testutil.NewRequest().Post("/multiple").WithContentType("image/png").WithBody(data).GoWithHTTPHandler(t, handler).Recorder - assert.Equal(t, http.StatusOK, rr.Code) - assert.Equal(t, "image/png", rr.Header().Get("Content-Type")) - assert.Equal(t, data, rr.Body.Bytes()) - }) - t.Run("HeadersExample", func(t *testing.T) { - header1 := "value1" - header2 := "890" - value := "asdf" - requestBody := clientAPI.Example{Value: &value} - rr := testutil.NewRequest().Post("/with-headers").WithHeader("header1", header1).WithHeader("header2", header2).WithJsonBody(requestBody).GoWithHTTPHandler(t, handler).Recorder - assert.Equal(t, http.StatusOK, rr.Code) - assert.True(t, strings.HasPrefix(rr.Header().Get("Content-Type"), "application/json")) - var responseBody clientAPI.Example - err := json.NewDecoder(rr.Body).Decode(&responseBody) - assert.NoError(t, err) - assert.Equal(t, requestBody, responseBody) - assert.Equal(t, header1, rr.Header().Get("header1")) - assert.Equal(t, header2, rr.Header().Get("header2")) - }) - t.Run("UnspecifiedContentType", func(t *testing.T) { - data := []byte("image data") - contentType := "image/jpeg" - rr := testutil.NewRequest().Post("/unspecified-content-type").WithContentType(contentType).WithBody(data).GoWithHTTPHandler(t, handler).Recorder - assert.Equal(t, http.StatusOK, rr.Code) - assert.Equal(t, contentType, rr.Header().Get("Content-Type")) - assert.Equal(t, data, rr.Body.Bytes()) - }) - t.Run("ReusableResponses", func(t *testing.T) { - value := "jkl;" - requestBody := clientAPI.Example{Value: &value} - rr := testutil.NewRequest().Post("/reusable-responses").WithJsonBody(requestBody).GoWithHTTPHandler(t, handler).Recorder - assert.Equal(t, http.StatusOK, rr.Code) - assert.True(t, strings.HasPrefix(rr.Header().Get("Content-Type"), "application/json")) - var responseBody clientAPI.Example - err := json.NewDecoder(rr.Body).Decode(&responseBody) - assert.NoError(t, err) - assert.Equal(t, requestBody, responseBody) - }) - t.Run("UnionResponses", func(t *testing.T) { - value := "union" - requestBody := clientAPI.Example{Value: &value} - rr := testutil.NewRequest().Post("/with-union").WithJsonBody(requestBody).GoWithHTTPHandler(t, handler).Recorder - assert.Equal(t, http.StatusOK, rr.Code) - assert.True(t, strings.HasPrefix(rr.Header().Get("Content-Type"), "application/json")) - var responseBody clientAPI.Example - err := json.NewDecoder(rr.Body).Decode(&responseBody) - assert.NoError(t, err) - assert.Equal(t, requestBody, responseBody) - }) -} diff --git a/internal/test/strict-server/fiber/server.cfg.yaml b/internal/test/strict-server/fiber/server.cfg.yaml deleted file mode 100644 index 73540ffc2c..0000000000 --- a/internal/test/strict-server/fiber/server.cfg.yaml +++ /dev/null @@ -1,7 +0,0 @@ -# yaml-language-server: $schema=../../../../configuration-schema.json -package: api -generate: - fiber-server: true - strict-server: true - embedded-spec: true -output: server.gen.go diff --git a/internal/test/strict-server/fiber/server.gen.go b/internal/test/strict-server/fiber/server.gen.go deleted file mode 100644 index 44d3c65de7..0000000000 --- a/internal/test/strict-server/fiber/server.gen.go +++ /dev/null @@ -1,1479 +0,0 @@ -// Package api provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package api - -import ( - "bytes" - "compress/gzip" - "context" - "encoding/base64" - "encoding/json" - "errors" - "fmt" - "io" - "mime" - "mime/multipart" - "net/http" - "net/url" - "path" - "strings" - - "github.com/getkin/kin-openapi/openapi3" - "github.com/gofiber/fiber/v2" - "github.com/oapi-codegen/runtime" -) - -// ServerInterface represents all server handlers. -type ServerInterface interface { - - // (POST /json) - JSONExample(c *fiber.Ctx) error - - // (POST /multipart) - MultipartExample(c *fiber.Ctx) error - - // (POST /multipart-related) - MultipartRelatedExample(c *fiber.Ctx) error - - // (POST /multiple) - MultipleRequestAndResponseTypes(c *fiber.Ctx) error - - // (POST /required-json-body) - RequiredJSONBody(c *fiber.Ctx) error - - // (POST /required-text-body) - RequiredTextBody(c *fiber.Ctx) error - - // (GET /reserved-go-keyword-parameters/{type}) - ReservedGoKeywordParameters(c *fiber.Ctx, pType string) error - - // (POST /reusable-responses) - ReusableResponses(c *fiber.Ctx) error - - // (POST /text) - TextExample(c *fiber.Ctx) error - - // (POST /unknown) - UnknownExample(c *fiber.Ctx) error - - // (POST /unspecified-content-type) - UnspecifiedContentType(c *fiber.Ctx) error - - // (POST /urlencoded) - URLEncodedExample(c *fiber.Ctx) error - - // (POST /with-headers) - HeadersExample(c *fiber.Ctx, params HeadersExampleParams) error - - // (POST /with-union) - UnionExample(c *fiber.Ctx) error -} - -// ServerInterfaceWrapper converts contexts to parameters. -type ServerInterfaceWrapper struct { - Handler ServerInterface -} - -type MiddlewareFunc fiber.Handler - -// JSONExample operation middleware -func (siw *ServerInterfaceWrapper) JSONExample(c *fiber.Ctx) error { - - return siw.Handler.JSONExample(c) -} - -// MultipartExample operation middleware -func (siw *ServerInterfaceWrapper) MultipartExample(c *fiber.Ctx) error { - - return siw.Handler.MultipartExample(c) -} - -// MultipartRelatedExample operation middleware -func (siw *ServerInterfaceWrapper) MultipartRelatedExample(c *fiber.Ctx) error { - - return siw.Handler.MultipartRelatedExample(c) -} - -// MultipleRequestAndResponseTypes operation middleware -func (siw *ServerInterfaceWrapper) MultipleRequestAndResponseTypes(c *fiber.Ctx) error { - - return siw.Handler.MultipleRequestAndResponseTypes(c) -} - -// RequiredJSONBody operation middleware -func (siw *ServerInterfaceWrapper) RequiredJSONBody(c *fiber.Ctx) error { - - return siw.Handler.RequiredJSONBody(c) -} - -// RequiredTextBody operation middleware -func (siw *ServerInterfaceWrapper) RequiredTextBody(c *fiber.Ctx) error { - - return siw.Handler.RequiredTextBody(c) -} - -// ReservedGoKeywordParameters operation middleware -func (siw *ServerInterfaceWrapper) ReservedGoKeywordParameters(c *fiber.Ctx) error { - - var err error - - // ------------- Path parameter "type" ------------- - var pType string - - err = runtime.BindStyledParameterWithOptions("simple", "type", c.Params("type"), &pType, runtime.BindStyledParameterOptions{Explode: false, Required: true, Type: "string", Format: ""}) - if err != nil { - return fiber.NewError(fiber.StatusBadRequest, fmt.Errorf("Invalid format for parameter type: %w", err).Error()) - } - - return siw.Handler.ReservedGoKeywordParameters(c, pType) -} - -// ReusableResponses operation middleware -func (siw *ServerInterfaceWrapper) ReusableResponses(c *fiber.Ctx) error { - - return siw.Handler.ReusableResponses(c) -} - -// TextExample operation middleware -func (siw *ServerInterfaceWrapper) TextExample(c *fiber.Ctx) error { - - return siw.Handler.TextExample(c) -} - -// UnknownExample operation middleware -func (siw *ServerInterfaceWrapper) UnknownExample(c *fiber.Ctx) error { - - return siw.Handler.UnknownExample(c) -} - -// UnspecifiedContentType operation middleware -func (siw *ServerInterfaceWrapper) UnspecifiedContentType(c *fiber.Ctx) error { - - return siw.Handler.UnspecifiedContentType(c) -} - -// URLEncodedExample operation middleware -func (siw *ServerInterfaceWrapper) URLEncodedExample(c *fiber.Ctx) error { - - return siw.Handler.URLEncodedExample(c) -} - -// HeadersExample operation middleware -func (siw *ServerInterfaceWrapper) HeadersExample(c *fiber.Ctx) error { - - var err error - - // Parameter object where we will unmarshal all parameters from the context - var params HeadersExampleParams - - headers := c.GetReqHeaders() - - // ------------- Required header parameter "header1" ------------- - if valueList, found := headers[http.CanonicalHeaderKey("header1")]; found { - var Header1 string - n := len(valueList) - if n != 1 { - return fiber.NewError(fiber.StatusBadRequest, fmt.Sprintf("Too many values for ParamName header1, 1 is required, but %d found", n)) - } - - err = runtime.BindStyledParameterWithOptions("simple", "header1", valueList[0], &Header1, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: true, Type: "string", Format: ""}) - if err != nil { - return fiber.NewError(fiber.StatusBadRequest, fmt.Errorf("Invalid format for parameter header1: %w", err).Error()) - } - - params.Header1 = Header1 - - } else { - err = fmt.Errorf("Header parameter header1 is required, but not found: %w", err) - return fiber.NewError(fiber.StatusBadRequest, err.Error()) - } - - // ------------- Optional header parameter "header2" ------------- - if valueList, found := headers[http.CanonicalHeaderKey("header2")]; found { - var Header2 int - n := len(valueList) - if n != 1 { - return fiber.NewError(fiber.StatusBadRequest, fmt.Sprintf("Too many values for ParamName header2, 1 is required, but %d found", n)) - } - - err = runtime.BindStyledParameterWithOptions("simple", "header2", valueList[0], &Header2, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: ""}) - if err != nil { - return fiber.NewError(fiber.StatusBadRequest, fmt.Errorf("Invalid format for parameter header2: %w", err).Error()) - } - - params.Header2 = &Header2 - - } - - return siw.Handler.HeadersExample(c, params) -} - -// UnionExample operation middleware -func (siw *ServerInterfaceWrapper) UnionExample(c *fiber.Ctx) error { - - return siw.Handler.UnionExample(c) -} - -// FiberServerOptions provides options for the Fiber server. -type FiberServerOptions struct { - BaseURL string - Middlewares []MiddlewareFunc -} - -// RegisterHandlers creates http.Handler with routing matching OpenAPI spec. -func RegisterHandlers(router fiber.Router, si ServerInterface) { - RegisterHandlersWithOptions(router, si, FiberServerOptions{}) -} - -// RegisterHandlersWithOptions creates http.Handler with additional options -func RegisterHandlersWithOptions(router fiber.Router, si ServerInterface, options FiberServerOptions) { - wrapper := ServerInterfaceWrapper{ - Handler: si, - } - - for _, m := range options.Middlewares { - router.Use(fiber.Handler(m)) - } - - router.Post(options.BaseURL+"/json", wrapper.JSONExample) - - router.Post(options.BaseURL+"/multipart", wrapper.MultipartExample) - - router.Post(options.BaseURL+"/multipart-related", wrapper.MultipartRelatedExample) - - router.Post(options.BaseURL+"/multiple", wrapper.MultipleRequestAndResponseTypes) - - router.Post(options.BaseURL+"/required-json-body", wrapper.RequiredJSONBody) - - router.Post(options.BaseURL+"/required-text-body", wrapper.RequiredTextBody) - - router.Get(options.BaseURL+"/reserved-go-keyword-parameters/:type", wrapper.ReservedGoKeywordParameters) - - router.Post(options.BaseURL+"/reusable-responses", wrapper.ReusableResponses) - - router.Post(options.BaseURL+"/text", wrapper.TextExample) - - router.Post(options.BaseURL+"/unknown", wrapper.UnknownExample) - - router.Post(options.BaseURL+"/unspecified-content-type", wrapper.UnspecifiedContentType) - - router.Post(options.BaseURL+"/urlencoded", wrapper.URLEncodedExample) - - router.Post(options.BaseURL+"/with-headers", wrapper.HeadersExample) - - router.Post(options.BaseURL+"/with-union", wrapper.UnionExample) - -} - -type BadrequestResponse struct { -} - -type ReusableresponseResponseHeaders struct { - Header1 string - Header2 int -} -type ReusableresponseJSONResponse struct { - Body Example - - Headers ReusableresponseResponseHeaders -} - -type JSONExampleRequestObject struct { - Body *JSONExampleJSONRequestBody -} - -type JSONExampleResponseObject interface { - VisitJSONExampleResponse(ctx *fiber.Ctx) error -} - -type JSONExample200JSONResponse Example - -func (response JSONExample200JSONResponse) VisitJSONExampleResponse(ctx *fiber.Ctx) error { - ctx.Response().Header.Set("Content-Type", "application/json") - ctx.Status(200) - - return ctx.JSON(&response) -} - -type JSONExample400Response = BadrequestResponse - -func (response JSONExample400Response) VisitJSONExampleResponse(ctx *fiber.Ctx) error { - ctx.Status(400) - return nil -} - -type JSONExampledefaultResponse struct { - StatusCode int -} - -func (response JSONExampledefaultResponse) VisitJSONExampleResponse(ctx *fiber.Ctx) error { - ctx.Status(response.StatusCode) - return nil -} - -type MultipartExampleRequestObject struct { - Body *multipart.Reader -} - -type MultipartExampleResponseObject interface { - VisitMultipartExampleResponse(ctx *fiber.Ctx) error -} - -type MultipartExample200MultipartResponse func(writer *multipart.Writer) error - -func (response MultipartExample200MultipartResponse) VisitMultipartExampleResponse(ctx *fiber.Ctx) error { - writer := multipart.NewWriter(ctx.Response().BodyWriter()) - ctx.Response().Header.Set("Content-Type", writer.FormDataContentType()) - ctx.Status(200) - - defer writer.Close() - return response(writer) -} - -type MultipartExample400Response = BadrequestResponse - -func (response MultipartExample400Response) VisitMultipartExampleResponse(ctx *fiber.Ctx) error { - ctx.Status(400) - return nil -} - -type MultipartExampledefaultResponse struct { - StatusCode int -} - -func (response MultipartExampledefaultResponse) VisitMultipartExampleResponse(ctx *fiber.Ctx) error { - ctx.Status(response.StatusCode) - return nil -} - -type MultipartRelatedExampleRequestObject struct { - Body *multipart.Reader -} - -type MultipartRelatedExampleResponseObject interface { - VisitMultipartRelatedExampleResponse(ctx *fiber.Ctx) error -} - -type MultipartRelatedExample200MultipartResponse func(writer *multipart.Writer) error - -func (response MultipartRelatedExample200MultipartResponse) VisitMultipartRelatedExampleResponse(ctx *fiber.Ctx) error { - writer := multipart.NewWriter(ctx.Response().BodyWriter()) - ctx.Response().Header.Set("Content-Type", mime.FormatMediaType("multipart/related", map[string]string{"boundary": writer.Boundary()})) - ctx.Status(200) - - defer writer.Close() - return response(writer) -} - -type MultipartRelatedExample400Response = BadrequestResponse - -func (response MultipartRelatedExample400Response) VisitMultipartRelatedExampleResponse(ctx *fiber.Ctx) error { - ctx.Status(400) - return nil -} - -type MultipartRelatedExampledefaultResponse struct { - StatusCode int -} - -func (response MultipartRelatedExampledefaultResponse) VisitMultipartRelatedExampleResponse(ctx *fiber.Ctx) error { - ctx.Status(response.StatusCode) - return nil -} - -type MultipleRequestAndResponseTypesRequestObject struct { - JSONBody *MultipleRequestAndResponseTypesJSONRequestBody - FormdataBody *MultipleRequestAndResponseTypesFormdataRequestBody - Body io.Reader - MultipartBody *multipart.Reader - TextBody *MultipleRequestAndResponseTypesTextRequestBody -} - -type MultipleRequestAndResponseTypesResponseObject interface { - VisitMultipleRequestAndResponseTypesResponse(ctx *fiber.Ctx) error -} - -type MultipleRequestAndResponseTypes200JSONResponse Example - -func (response MultipleRequestAndResponseTypes200JSONResponse) VisitMultipleRequestAndResponseTypesResponse(ctx *fiber.Ctx) error { - ctx.Response().Header.Set("Content-Type", "application/json") - ctx.Status(200) - - return ctx.JSON(&response) -} - -type MultipleRequestAndResponseTypes200FormdataResponse Example - -func (response MultipleRequestAndResponseTypes200FormdataResponse) VisitMultipleRequestAndResponseTypesResponse(ctx *fiber.Ctx) error { - ctx.Response().Header.Set("Content-Type", "application/x-www-form-urlencoded") - ctx.Status(200) - - if form, err := runtime.MarshalForm(response, nil); err != nil { - return err - } else { - _, err := ctx.WriteString(form.Encode()) - return err - } -} - -type MultipleRequestAndResponseTypes200ImagepngResponse struct { - Body io.Reader - ContentLength int64 -} - -func (response MultipleRequestAndResponseTypes200ImagepngResponse) VisitMultipleRequestAndResponseTypesResponse(ctx *fiber.Ctx) error { - ctx.Response().Header.Set("Content-Type", "image/png") - if response.ContentLength != 0 { - ctx.Response().Header.Set("Content-Length", fmt.Sprint(response.ContentLength)) - } - ctx.Status(200) - - if closer, ok := response.Body.(io.ReadCloser); ok { - defer closer.Close() - } - _, err := io.Copy(ctx.Response().BodyWriter(), response.Body) - return err -} - -type MultipleRequestAndResponseTypes200MultipartResponse func(writer *multipart.Writer) error - -func (response MultipleRequestAndResponseTypes200MultipartResponse) VisitMultipleRequestAndResponseTypesResponse(ctx *fiber.Ctx) error { - writer := multipart.NewWriter(ctx.Response().BodyWriter()) - ctx.Response().Header.Set("Content-Type", writer.FormDataContentType()) - ctx.Status(200) - - defer writer.Close() - return response(writer) -} - -type MultipleRequestAndResponseTypes200TextResponse string - -func (response MultipleRequestAndResponseTypes200TextResponse) VisitMultipleRequestAndResponseTypesResponse(ctx *fiber.Ctx) error { - ctx.Response().Header.Set("Content-Type", "text/plain") - ctx.Status(200) - - _, err := ctx.WriteString(string(response)) - return err -} - -type MultipleRequestAndResponseTypes400Response = BadrequestResponse - -func (response MultipleRequestAndResponseTypes400Response) VisitMultipleRequestAndResponseTypesResponse(ctx *fiber.Ctx) error { - ctx.Status(400) - return nil -} - -type RequiredJSONBodyRequestObject struct { - Body *RequiredJSONBodyJSONRequestBody -} - -type RequiredJSONBodyResponseObject interface { - VisitRequiredJSONBodyResponse(ctx *fiber.Ctx) error -} - -type RequiredJSONBody200JSONResponse Example - -func (response RequiredJSONBody200JSONResponse) VisitRequiredJSONBodyResponse(ctx *fiber.Ctx) error { - ctx.Response().Header.Set("Content-Type", "application/json") - ctx.Status(200) - - return ctx.JSON(&response) -} - -type RequiredJSONBody400Response = BadrequestResponse - -func (response RequiredJSONBody400Response) VisitRequiredJSONBodyResponse(ctx *fiber.Ctx) error { - ctx.Status(400) - return nil -} - -type RequiredJSONBodydefaultResponse struct { - StatusCode int -} - -func (response RequiredJSONBodydefaultResponse) VisitRequiredJSONBodyResponse(ctx *fiber.Ctx) error { - ctx.Status(response.StatusCode) - return nil -} - -type RequiredTextBodyRequestObject struct { - Body *RequiredTextBodyTextRequestBody -} - -type RequiredTextBodyResponseObject interface { - VisitRequiredTextBodyResponse(ctx *fiber.Ctx) error -} - -type RequiredTextBody200TextResponse string - -func (response RequiredTextBody200TextResponse) VisitRequiredTextBodyResponse(ctx *fiber.Ctx) error { - ctx.Response().Header.Set("Content-Type", "text/plain") - ctx.Status(200) - - _, err := ctx.WriteString(string(response)) - return err -} - -type RequiredTextBody400Response = BadrequestResponse - -func (response RequiredTextBody400Response) VisitRequiredTextBodyResponse(ctx *fiber.Ctx) error { - ctx.Status(400) - return nil -} - -type RequiredTextBodydefaultResponse struct { - StatusCode int -} - -func (response RequiredTextBodydefaultResponse) VisitRequiredTextBodyResponse(ctx *fiber.Ctx) error { - ctx.Status(response.StatusCode) - return nil -} - -type ReservedGoKeywordParametersRequestObject struct { - Type string `json:"type"` -} - -type ReservedGoKeywordParametersResponseObject interface { - VisitReservedGoKeywordParametersResponse(ctx *fiber.Ctx) error -} - -type ReservedGoKeywordParameters200TextResponse string - -func (response ReservedGoKeywordParameters200TextResponse) VisitReservedGoKeywordParametersResponse(ctx *fiber.Ctx) error { - ctx.Response().Header.Set("Content-Type", "text/plain") - ctx.Status(200) - - _, err := ctx.WriteString(string(response)) - return err -} - -type ReusableResponsesRequestObject struct { - Body *ReusableResponsesJSONRequestBody -} - -type ReusableResponsesResponseObject interface { - VisitReusableResponsesResponse(ctx *fiber.Ctx) error -} - -type ReusableResponses200JSONResponse struct{ ReusableresponseJSONResponse } - -func (response ReusableResponses200JSONResponse) VisitReusableResponsesResponse(ctx *fiber.Ctx) error { - ctx.Response().Header.Set("header1", fmt.Sprint(response.Headers.Header1)) - ctx.Response().Header.Set("header2", fmt.Sprint(response.Headers.Header2)) - ctx.Response().Header.Set("Content-Type", "application/json") - ctx.Status(200) - - return ctx.JSON(&response.Body) -} - -type ReusableResponses400Response = BadrequestResponse - -func (response ReusableResponses400Response) VisitReusableResponsesResponse(ctx *fiber.Ctx) error { - ctx.Status(400) - return nil -} - -type ReusableResponsesdefaultResponse struct { - StatusCode int -} - -func (response ReusableResponsesdefaultResponse) VisitReusableResponsesResponse(ctx *fiber.Ctx) error { - ctx.Status(response.StatusCode) - return nil -} - -type TextExampleRequestObject struct { - Body *TextExampleTextRequestBody -} - -type TextExampleResponseObject interface { - VisitTextExampleResponse(ctx *fiber.Ctx) error -} - -type TextExample200TextResponse string - -func (response TextExample200TextResponse) VisitTextExampleResponse(ctx *fiber.Ctx) error { - ctx.Response().Header.Set("Content-Type", "text/plain") - ctx.Status(200) - - _, err := ctx.WriteString(string(response)) - return err -} - -type TextExample400Response = BadrequestResponse - -func (response TextExample400Response) VisitTextExampleResponse(ctx *fiber.Ctx) error { - ctx.Status(400) - return nil -} - -type TextExampledefaultResponse struct { - StatusCode int -} - -func (response TextExampledefaultResponse) VisitTextExampleResponse(ctx *fiber.Ctx) error { - ctx.Status(response.StatusCode) - return nil -} - -type UnknownExampleRequestObject struct { - Body io.Reader -} - -type UnknownExampleResponseObject interface { - VisitUnknownExampleResponse(ctx *fiber.Ctx) error -} - -type UnknownExample200Videomp4Response struct { - Body io.Reader - ContentLength int64 -} - -func (response UnknownExample200Videomp4Response) VisitUnknownExampleResponse(ctx *fiber.Ctx) error { - ctx.Response().Header.Set("Content-Type", "video/mp4") - if response.ContentLength != 0 { - ctx.Response().Header.Set("Content-Length", fmt.Sprint(response.ContentLength)) - } - ctx.Status(200) - - if closer, ok := response.Body.(io.ReadCloser); ok { - defer closer.Close() - } - _, err := io.Copy(ctx.Response().BodyWriter(), response.Body) - return err -} - -type UnknownExample400Response = BadrequestResponse - -func (response UnknownExample400Response) VisitUnknownExampleResponse(ctx *fiber.Ctx) error { - ctx.Status(400) - return nil -} - -type UnknownExampledefaultResponse struct { - StatusCode int -} - -func (response UnknownExampledefaultResponse) VisitUnknownExampleResponse(ctx *fiber.Ctx) error { - ctx.Status(response.StatusCode) - return nil -} - -type UnspecifiedContentTypeRequestObject struct { - ContentType string - Body io.Reader -} - -type UnspecifiedContentTypeResponseObject interface { - VisitUnspecifiedContentTypeResponse(ctx *fiber.Ctx) error -} - -type UnspecifiedContentType200VideoResponse struct { - Body io.Reader - ContentType string - ContentLength int64 -} - -func (response UnspecifiedContentType200VideoResponse) VisitUnspecifiedContentTypeResponse(ctx *fiber.Ctx) error { - ctx.Response().Header.Set("Content-Type", response.ContentType) - if response.ContentLength != 0 { - ctx.Response().Header.Set("Content-Length", fmt.Sprint(response.ContentLength)) - } - ctx.Status(200) - - if closer, ok := response.Body.(io.ReadCloser); ok { - defer closer.Close() - } - _, err := io.Copy(ctx.Response().BodyWriter(), response.Body) - return err -} - -type UnspecifiedContentType400Response = BadrequestResponse - -func (response UnspecifiedContentType400Response) VisitUnspecifiedContentTypeResponse(ctx *fiber.Ctx) error { - ctx.Status(400) - return nil -} - -type UnspecifiedContentType401Response struct { -} - -func (response UnspecifiedContentType401Response) VisitUnspecifiedContentTypeResponse(ctx *fiber.Ctx) error { - ctx.Status(401) - return nil -} - -type UnspecifiedContentType403Response struct { -} - -func (response UnspecifiedContentType403Response) VisitUnspecifiedContentTypeResponse(ctx *fiber.Ctx) error { - ctx.Status(403) - return nil -} - -type UnspecifiedContentTypedefaultResponse struct { - StatusCode int -} - -func (response UnspecifiedContentTypedefaultResponse) VisitUnspecifiedContentTypeResponse(ctx *fiber.Ctx) error { - ctx.Status(response.StatusCode) - return nil -} - -type URLEncodedExampleRequestObject struct { - Body *URLEncodedExampleFormdataRequestBody -} - -type URLEncodedExampleResponseObject interface { - VisitURLEncodedExampleResponse(ctx *fiber.Ctx) error -} - -type URLEncodedExample200FormdataResponse Example - -func (response URLEncodedExample200FormdataResponse) VisitURLEncodedExampleResponse(ctx *fiber.Ctx) error { - ctx.Response().Header.Set("Content-Type", "application/x-www-form-urlencoded") - ctx.Status(200) - - if form, err := runtime.MarshalForm(response, nil); err != nil { - return err - } else { - _, err := ctx.WriteString(form.Encode()) - return err - } -} - -type URLEncodedExample400Response = BadrequestResponse - -func (response URLEncodedExample400Response) VisitURLEncodedExampleResponse(ctx *fiber.Ctx) error { - ctx.Status(400) - return nil -} - -type URLEncodedExampledefaultResponse struct { - StatusCode int -} - -func (response URLEncodedExampledefaultResponse) VisitURLEncodedExampleResponse(ctx *fiber.Ctx) error { - ctx.Status(response.StatusCode) - return nil -} - -type HeadersExampleRequestObject struct { - Params HeadersExampleParams - Body *HeadersExampleJSONRequestBody -} - -type HeadersExampleResponseObject interface { - VisitHeadersExampleResponse(ctx *fiber.Ctx) error -} - -type HeadersExample200ResponseHeaders struct { - Header1 string - Header2 int -} - -type HeadersExample200JSONResponse struct { - Body Example - Headers HeadersExample200ResponseHeaders -} - -func (response HeadersExample200JSONResponse) VisitHeadersExampleResponse(ctx *fiber.Ctx) error { - ctx.Response().Header.Set("header1", fmt.Sprint(response.Headers.Header1)) - ctx.Response().Header.Set("header2", fmt.Sprint(response.Headers.Header2)) - ctx.Response().Header.Set("Content-Type", "application/json") - ctx.Status(200) - - return ctx.JSON(&response.Body) -} - -type HeadersExample400Response = BadrequestResponse - -func (response HeadersExample400Response) VisitHeadersExampleResponse(ctx *fiber.Ctx) error { - ctx.Status(400) - return nil -} - -type HeadersExampledefaultResponse struct { - StatusCode int -} - -func (response HeadersExampledefaultResponse) VisitHeadersExampleResponse(ctx *fiber.Ctx) error { - ctx.Status(response.StatusCode) - return nil -} - -type UnionExampleRequestObject struct { - Body *UnionExampleJSONRequestBody -} - -type UnionExampleResponseObject interface { - VisitUnionExampleResponse(ctx *fiber.Ctx) error -} - -type UnionExample200ResponseHeaders struct { - Header1 string - Header2 int -} - -type UnionExample200ApplicationAlternativePlusJSONResponse struct { - Body Example - Headers UnionExample200ResponseHeaders -} - -func (response UnionExample200ApplicationAlternativePlusJSONResponse) VisitUnionExampleResponse(ctx *fiber.Ctx) error { - ctx.Response().Header.Set("header1", fmt.Sprint(response.Headers.Header1)) - ctx.Response().Header.Set("header2", fmt.Sprint(response.Headers.Header2)) - ctx.Response().Header.Set("Content-Type", "application/alternative+json") - ctx.Status(200) - - return ctx.JSON(&response.Body) -} - -type UnionExample200JSONResponse struct { - Body struct { - union json.RawMessage - } - Headers UnionExample200ResponseHeaders -} - -func (response UnionExample200JSONResponse) VisitUnionExampleResponse(ctx *fiber.Ctx) error { - ctx.Response().Header.Set("header1", fmt.Sprint(response.Headers.Header1)) - ctx.Response().Header.Set("header2", fmt.Sprint(response.Headers.Header2)) - ctx.Response().Header.Set("Content-Type", "application/json") - ctx.Status(200) - - return ctx.JSON(&response.Body.union) -} - -type UnionExample400Response = BadrequestResponse - -func (response UnionExample400Response) VisitUnionExampleResponse(ctx *fiber.Ctx) error { - ctx.Status(400) - return nil -} - -type UnionExampledefaultResponse struct { - StatusCode int -} - -func (response UnionExampledefaultResponse) VisitUnionExampleResponse(ctx *fiber.Ctx) error { - ctx.Status(response.StatusCode) - return nil -} - -// StrictServerInterface represents all server handlers. -type StrictServerInterface interface { - - // (POST /json) - JSONExample(ctx context.Context, request JSONExampleRequestObject) (JSONExampleResponseObject, error) - - // (POST /multipart) - MultipartExample(ctx context.Context, request MultipartExampleRequestObject) (MultipartExampleResponseObject, error) - - // (POST /multipart-related) - MultipartRelatedExample(ctx context.Context, request MultipartRelatedExampleRequestObject) (MultipartRelatedExampleResponseObject, error) - - // (POST /multiple) - MultipleRequestAndResponseTypes(ctx context.Context, request MultipleRequestAndResponseTypesRequestObject) (MultipleRequestAndResponseTypesResponseObject, error) - - // (POST /required-json-body) - RequiredJSONBody(ctx context.Context, request RequiredJSONBodyRequestObject) (RequiredJSONBodyResponseObject, error) - - // (POST /required-text-body) - RequiredTextBody(ctx context.Context, request RequiredTextBodyRequestObject) (RequiredTextBodyResponseObject, error) - - // (GET /reserved-go-keyword-parameters/{type}) - ReservedGoKeywordParameters(ctx context.Context, request ReservedGoKeywordParametersRequestObject) (ReservedGoKeywordParametersResponseObject, error) - - // (POST /reusable-responses) - ReusableResponses(ctx context.Context, request ReusableResponsesRequestObject) (ReusableResponsesResponseObject, error) - - // (POST /text) - TextExample(ctx context.Context, request TextExampleRequestObject) (TextExampleResponseObject, error) - - // (POST /unknown) - UnknownExample(ctx context.Context, request UnknownExampleRequestObject) (UnknownExampleResponseObject, error) - - // (POST /unspecified-content-type) - UnspecifiedContentType(ctx context.Context, request UnspecifiedContentTypeRequestObject) (UnspecifiedContentTypeResponseObject, error) - - // (POST /urlencoded) - URLEncodedExample(ctx context.Context, request URLEncodedExampleRequestObject) (URLEncodedExampleResponseObject, error) - - // (POST /with-headers) - HeadersExample(ctx context.Context, request HeadersExampleRequestObject) (HeadersExampleResponseObject, error) - - // (POST /with-union) - UnionExample(ctx context.Context, request UnionExampleRequestObject) (UnionExampleResponseObject, error) -} - -type StrictHandlerFunc func(ctx *fiber.Ctx, args interface{}) (interface{}, error) - -type StrictMiddlewareFunc func(f StrictHandlerFunc, operationID string) StrictHandlerFunc - -func NewStrictHandler(ssi StrictServerInterface, middlewares []StrictMiddlewareFunc) ServerInterface { - return &strictHandler{ssi: ssi, middlewares: middlewares} -} - -type strictHandler struct { - ssi StrictServerInterface - middlewares []StrictMiddlewareFunc -} - -// JSONExample operation middleware -func (sh *strictHandler) JSONExample(ctx *fiber.Ctx) error { - var request JSONExampleRequestObject - - var body JSONExampleJSONRequestBody - if err := ctx.BodyParser(&body); err != nil { - if !errors.Is(err, io.EOF) { - return fiber.NewError(fiber.StatusBadRequest, err.Error()) - } - } else { - request.Body = &body - } - - handler := func(ctx *fiber.Ctx, request interface{}) (interface{}, error) { - return sh.ssi.JSONExample(ctx.UserContext(), request.(JSONExampleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "JSONExample") - } - - response, err := handler(ctx, request) - - if err != nil { - return fiber.NewError(fiber.StatusBadRequest, err.Error()) - } else if validResponse, ok := response.(JSONExampleResponseObject); ok { - if err := validResponse.VisitJSONExampleResponse(ctx); err != nil { - return fiber.NewError(fiber.StatusBadRequest, err.Error()) - } - } else if response != nil { - return fmt.Errorf("unexpected response type: %T", response) - } - return nil -} - -// MultipartExample operation middleware -func (sh *strictHandler) MultipartExample(ctx *fiber.Ctx) error { - var request MultipartExampleRequestObject - - request.Body = multipart.NewReader(bytes.NewReader(ctx.Request().Body()), string(ctx.Request().Header.MultipartFormBoundary())) - - handler := func(ctx *fiber.Ctx, request interface{}) (interface{}, error) { - return sh.ssi.MultipartExample(ctx.UserContext(), request.(MultipartExampleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "MultipartExample") - } - - response, err := handler(ctx, request) - - if err != nil { - return fiber.NewError(fiber.StatusBadRequest, err.Error()) - } else if validResponse, ok := response.(MultipartExampleResponseObject); ok { - if err := validResponse.VisitMultipartExampleResponse(ctx); err != nil { - return fiber.NewError(fiber.StatusBadRequest, err.Error()) - } - } else if response != nil { - return fmt.Errorf("unexpected response type: %T", response) - } - return nil -} - -// MultipartRelatedExample operation middleware -func (sh *strictHandler) MultipartRelatedExample(ctx *fiber.Ctx) error { - var request MultipartRelatedExampleRequestObject - - if _, params, err := mime.ParseMediaType(string(ctx.Request().Header.ContentType())); err != nil { - return fiber.NewError(fiber.StatusBadRequest, err.Error()) - } else if boundary := params["boundary"]; boundary == "" { - return fiber.NewError(fiber.StatusBadRequest, http.ErrMissingBoundary.Error()) - } else { - request.Body = multipart.NewReader(bytes.NewReader(ctx.Request().Body()), boundary) - } - - handler := func(ctx *fiber.Ctx, request interface{}) (interface{}, error) { - return sh.ssi.MultipartRelatedExample(ctx.UserContext(), request.(MultipartRelatedExampleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "MultipartRelatedExample") - } - - response, err := handler(ctx, request) - - if err != nil { - return fiber.NewError(fiber.StatusBadRequest, err.Error()) - } else if validResponse, ok := response.(MultipartRelatedExampleResponseObject); ok { - if err := validResponse.VisitMultipartRelatedExampleResponse(ctx); err != nil { - return fiber.NewError(fiber.StatusBadRequest, err.Error()) - } - } else if response != nil { - return fmt.Errorf("unexpected response type: %T", response) - } - return nil -} - -// MultipleRequestAndResponseTypes operation middleware -func (sh *strictHandler) MultipleRequestAndResponseTypes(ctx *fiber.Ctx) error { - var request MultipleRequestAndResponseTypesRequestObject - - if strings.HasPrefix(string(ctx.Request().Header.ContentType()), "application/json") { - - var body MultipleRequestAndResponseTypesJSONRequestBody - if err := ctx.BodyParser(&body); err != nil { - if !errors.Is(err, io.EOF) { - return fiber.NewError(fiber.StatusBadRequest, err.Error()) - } - } else { - request.JSONBody = &body - } - } - if strings.HasPrefix(string(ctx.Request().Header.ContentType()), "application/x-www-form-urlencoded") { - var body MultipleRequestAndResponseTypesFormdataRequestBody - if err := ctx.BodyParser(&body); err != nil { - return fiber.NewError(fiber.StatusBadRequest, err.Error()) - } - request.FormdataBody = &body - } - if strings.HasPrefix(string(ctx.Request().Header.ContentType()), "image/png") { - request.Body = bytes.NewReader(ctx.Request().Body()) - } - if strings.HasPrefix(string(ctx.Request().Header.ContentType()), "multipart/form-data") { - request.MultipartBody = multipart.NewReader(bytes.NewReader(ctx.Request().Body()), string(ctx.Request().Header.MultipartFormBoundary())) - } - if strings.HasPrefix(string(ctx.Request().Header.ContentType()), "text/plain") { - data := ctx.Request().Body() - if len(data) > 0 { - body := MultipleRequestAndResponseTypesTextRequestBody(data) - request.TextBody = &body - } - } - - handler := func(ctx *fiber.Ctx, request interface{}) (interface{}, error) { - return sh.ssi.MultipleRequestAndResponseTypes(ctx.UserContext(), request.(MultipleRequestAndResponseTypesRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "MultipleRequestAndResponseTypes") - } - - response, err := handler(ctx, request) - - if err != nil { - return fiber.NewError(fiber.StatusBadRequest, err.Error()) - } else if validResponse, ok := response.(MultipleRequestAndResponseTypesResponseObject); ok { - if err := validResponse.VisitMultipleRequestAndResponseTypesResponse(ctx); err != nil { - return fiber.NewError(fiber.StatusBadRequest, err.Error()) - } - } else if response != nil { - return fmt.Errorf("unexpected response type: %T", response) - } - return nil -} - -// RequiredJSONBody operation middleware -func (sh *strictHandler) RequiredJSONBody(ctx *fiber.Ctx) error { - var request RequiredJSONBodyRequestObject - - var body RequiredJSONBodyJSONRequestBody - if err := ctx.BodyParser(&body); err != nil { - return fiber.NewError(fiber.StatusBadRequest, err.Error()) - } - request.Body = &body - - handler := func(ctx *fiber.Ctx, request interface{}) (interface{}, error) { - return sh.ssi.RequiredJSONBody(ctx.UserContext(), request.(RequiredJSONBodyRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "RequiredJSONBody") - } - - response, err := handler(ctx, request) - - if err != nil { - return fiber.NewError(fiber.StatusBadRequest, err.Error()) - } else if validResponse, ok := response.(RequiredJSONBodyResponseObject); ok { - if err := validResponse.VisitRequiredJSONBodyResponse(ctx); err != nil { - return fiber.NewError(fiber.StatusBadRequest, err.Error()) - } - } else if response != nil { - return fmt.Errorf("unexpected response type: %T", response) - } - return nil -} - -// RequiredTextBody operation middleware -func (sh *strictHandler) RequiredTextBody(ctx *fiber.Ctx) error { - var request RequiredTextBodyRequestObject - - data := ctx.Request().Body() - body := RequiredTextBodyTextRequestBody(data) - request.Body = &body - - handler := func(ctx *fiber.Ctx, request interface{}) (interface{}, error) { - return sh.ssi.RequiredTextBody(ctx.UserContext(), request.(RequiredTextBodyRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "RequiredTextBody") - } - - response, err := handler(ctx, request) - - if err != nil { - return fiber.NewError(fiber.StatusBadRequest, err.Error()) - } else if validResponse, ok := response.(RequiredTextBodyResponseObject); ok { - if err := validResponse.VisitRequiredTextBodyResponse(ctx); err != nil { - return fiber.NewError(fiber.StatusBadRequest, err.Error()) - } - } else if response != nil { - return fmt.Errorf("unexpected response type: %T", response) - } - return nil -} - -// ReservedGoKeywordParameters operation middleware -func (sh *strictHandler) ReservedGoKeywordParameters(ctx *fiber.Ctx, pType string) error { - var request ReservedGoKeywordParametersRequestObject - - request.Type = pType - - handler := func(ctx *fiber.Ctx, request interface{}) (interface{}, error) { - return sh.ssi.ReservedGoKeywordParameters(ctx.UserContext(), request.(ReservedGoKeywordParametersRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "ReservedGoKeywordParameters") - } - - response, err := handler(ctx, request) - - if err != nil { - return fiber.NewError(fiber.StatusBadRequest, err.Error()) - } else if validResponse, ok := response.(ReservedGoKeywordParametersResponseObject); ok { - if err := validResponse.VisitReservedGoKeywordParametersResponse(ctx); err != nil { - return fiber.NewError(fiber.StatusBadRequest, err.Error()) - } - } else if response != nil { - return fmt.Errorf("unexpected response type: %T", response) - } - return nil -} - -// ReusableResponses operation middleware -func (sh *strictHandler) ReusableResponses(ctx *fiber.Ctx) error { - var request ReusableResponsesRequestObject - - var body ReusableResponsesJSONRequestBody - if err := ctx.BodyParser(&body); err != nil { - if !errors.Is(err, io.EOF) { - return fiber.NewError(fiber.StatusBadRequest, err.Error()) - } - } else { - request.Body = &body - } - - handler := func(ctx *fiber.Ctx, request interface{}) (interface{}, error) { - return sh.ssi.ReusableResponses(ctx.UserContext(), request.(ReusableResponsesRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "ReusableResponses") - } - - response, err := handler(ctx, request) - - if err != nil { - return fiber.NewError(fiber.StatusBadRequest, err.Error()) - } else if validResponse, ok := response.(ReusableResponsesResponseObject); ok { - if err := validResponse.VisitReusableResponsesResponse(ctx); err != nil { - return fiber.NewError(fiber.StatusBadRequest, err.Error()) - } - } else if response != nil { - return fmt.Errorf("unexpected response type: %T", response) - } - return nil -} - -// TextExample operation middleware -func (sh *strictHandler) TextExample(ctx *fiber.Ctx) error { - var request TextExampleRequestObject - - data := ctx.Request().Body() - if len(data) > 0 { - body := TextExampleTextRequestBody(data) - request.Body = &body - } - - handler := func(ctx *fiber.Ctx, request interface{}) (interface{}, error) { - return sh.ssi.TextExample(ctx.UserContext(), request.(TextExampleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "TextExample") - } - - response, err := handler(ctx, request) - - if err != nil { - return fiber.NewError(fiber.StatusBadRequest, err.Error()) - } else if validResponse, ok := response.(TextExampleResponseObject); ok { - if err := validResponse.VisitTextExampleResponse(ctx); err != nil { - return fiber.NewError(fiber.StatusBadRequest, err.Error()) - } - } else if response != nil { - return fmt.Errorf("unexpected response type: %T", response) - } - return nil -} - -// UnknownExample operation middleware -func (sh *strictHandler) UnknownExample(ctx *fiber.Ctx) error { - var request UnknownExampleRequestObject - - request.Body = bytes.NewReader(ctx.Request().Body()) - - handler := func(ctx *fiber.Ctx, request interface{}) (interface{}, error) { - return sh.ssi.UnknownExample(ctx.UserContext(), request.(UnknownExampleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "UnknownExample") - } - - response, err := handler(ctx, request) - - if err != nil { - return fiber.NewError(fiber.StatusBadRequest, err.Error()) - } else if validResponse, ok := response.(UnknownExampleResponseObject); ok { - if err := validResponse.VisitUnknownExampleResponse(ctx); err != nil { - return fiber.NewError(fiber.StatusBadRequest, err.Error()) - } - } else if response != nil { - return fmt.Errorf("unexpected response type: %T", response) - } - return nil -} - -// UnspecifiedContentType operation middleware -func (sh *strictHandler) UnspecifiedContentType(ctx *fiber.Ctx) error { - var request UnspecifiedContentTypeRequestObject - - request.ContentType = string(ctx.Request().Header.ContentType()) - - request.Body = bytes.NewReader(ctx.Request().Body()) - - handler := func(ctx *fiber.Ctx, request interface{}) (interface{}, error) { - return sh.ssi.UnspecifiedContentType(ctx.UserContext(), request.(UnspecifiedContentTypeRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "UnspecifiedContentType") - } - - response, err := handler(ctx, request) - - if err != nil { - return fiber.NewError(fiber.StatusBadRequest, err.Error()) - } else if validResponse, ok := response.(UnspecifiedContentTypeResponseObject); ok { - if err := validResponse.VisitUnspecifiedContentTypeResponse(ctx); err != nil { - return fiber.NewError(fiber.StatusBadRequest, err.Error()) - } - } else if response != nil { - return fmt.Errorf("unexpected response type: %T", response) - } - return nil -} - -// URLEncodedExample operation middleware -func (sh *strictHandler) URLEncodedExample(ctx *fiber.Ctx) error { - var request URLEncodedExampleRequestObject - - var body URLEncodedExampleFormdataRequestBody - if err := ctx.BodyParser(&body); err != nil { - return fiber.NewError(fiber.StatusBadRequest, err.Error()) - } - request.Body = &body - - handler := func(ctx *fiber.Ctx, request interface{}) (interface{}, error) { - return sh.ssi.URLEncodedExample(ctx.UserContext(), request.(URLEncodedExampleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "URLEncodedExample") - } - - response, err := handler(ctx, request) - - if err != nil { - return fiber.NewError(fiber.StatusBadRequest, err.Error()) - } else if validResponse, ok := response.(URLEncodedExampleResponseObject); ok { - if err := validResponse.VisitURLEncodedExampleResponse(ctx); err != nil { - return fiber.NewError(fiber.StatusBadRequest, err.Error()) - } - } else if response != nil { - return fmt.Errorf("unexpected response type: %T", response) - } - return nil -} - -// HeadersExample operation middleware -func (sh *strictHandler) HeadersExample(ctx *fiber.Ctx, params HeadersExampleParams) error { - var request HeadersExampleRequestObject - - request.Params = params - - var body HeadersExampleJSONRequestBody - if err := ctx.BodyParser(&body); err != nil { - if !errors.Is(err, io.EOF) { - return fiber.NewError(fiber.StatusBadRequest, err.Error()) - } - } else { - request.Body = &body - } - - handler := func(ctx *fiber.Ctx, request interface{}) (interface{}, error) { - return sh.ssi.HeadersExample(ctx.UserContext(), request.(HeadersExampleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "HeadersExample") - } - - response, err := handler(ctx, request) - - if err != nil { - return fiber.NewError(fiber.StatusBadRequest, err.Error()) - } else if validResponse, ok := response.(HeadersExampleResponseObject); ok { - if err := validResponse.VisitHeadersExampleResponse(ctx); err != nil { - return fiber.NewError(fiber.StatusBadRequest, err.Error()) - } - } else if response != nil { - return fmt.Errorf("unexpected response type: %T", response) - } - return nil -} - -// UnionExample operation middleware -func (sh *strictHandler) UnionExample(ctx *fiber.Ctx) error { - var request UnionExampleRequestObject - - var body UnionExampleJSONRequestBody - if err := ctx.BodyParser(&body); err != nil { - if !errors.Is(err, io.EOF) { - return fiber.NewError(fiber.StatusBadRequest, err.Error()) - } - } else { - request.Body = &body - } - - handler := func(ctx *fiber.Ctx, request interface{}) (interface{}, error) { - return sh.ssi.UnionExample(ctx.UserContext(), request.(UnionExampleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "UnionExample") - } - - response, err := handler(ctx, request) - - if err != nil { - return fiber.NewError(fiber.StatusBadRequest, err.Error()) - } else if validResponse, ok := response.(UnionExampleResponseObject); ok { - if err := validResponse.VisitUnionExampleResponse(ctx); err != nil { - return fiber.NewError(fiber.StatusBadRequest, err.Error()) - } - } else if response != nil { - return fmt.Errorf("unexpected response type: %T", response) - } - return nil -} - -// Base64 encoded, gzipped, json marshaled Swagger object -var swaggerSpec = []string{ - - "H4sIAAAAAAAC/+xZTXPbNhP+Kzt431NKmrbjE2+NJ5O2aeuObJ86PkDESkJCAiiwFK3R6L93QEBfFq1K", - "qT4ynt5Ecr/wPLuLBTRlha6MVqjIsXzKLDqjlcP2oc+Fxb9qdOSfBLrCSkNSK5azD1z04rdZwizWjvdL", - "nKt7+UIrQtWqcmNKWXCvmn1xXn/KXDHCivtf/7c4YDn7X7YMJQtfXYbPvDIlstlslryI4O4zS9gIuUDb", - "Rht+Xq3bpolBljNHVqoh80aC2HWnmFSEQ7TemxeNQXiBeRz5lBmrDVqSAaMxL2vs9hTf6P4XLCisQKqB", - "3sTyViviUjkQcjBAi4ogggfehgNXG6MtoYD+BLyHgsChHaNlCSNJPjB2v/oeYsCOJWyM1gVHVxeXF5ee", - "L21QcSNZzt63rxJmOI3aBS0IMrqL91/u734H6YDXpCtOsuBlOYGKWzfiJQqQirQPsS7IXbDWk22J/1lE", - "7Y8RSp81bQJ90GJyjIRp83Ilna8vL0+Ul7OE3QRnXTYWQWUrBdaaGfC67MD8UX1VulGA1mobV5ZVdUnS", - "cEurXK2j/dtcZBfIF/aygbZVKjjxI6F+KE/nBj61WHJCsQMBvSC5Hw8r5o/Kwr/xc1YOYj/u7FP3I904", - "GOkGSINAXkIjaQRzxRcNVirg4KQalgjzoJJOMkuM296PSvTiWh68jaP3s2TNynPaNE3aFlBtS1SFFt9G", - "YcJkxYeYGTVcV/e2ObGc9SfkU3ZzgztQISeM8JkyU3Kptu/eJ2rp/yF9sMIO5eofpUWRekbSfqyP7sKN", - "5QVeyg8ac90EnIZKOl+l4aMb6boUwMuGT1zoD5sTRy+q+8mjLcyjjx3BgffJcrI1vu0xZEGtz6zzUPuA", - "z/SP1O6R+PvSd+qa2p+i9kwg0qFOv+Kk0VakhlteIaF12dTHOfO2hthh8o+FJBRcQR9B8QoF8AGhhU8a", - "oknXwU/w+0l/DiJLU+2BY/GQ/zllHrz2EMIS5h2wPOD3ko5kC8BPx6VqjmY46qZrrl5L+Cgyh87iwPmB", - "pIvjDvyCp96KxHmOTNtzc+Pwf4qk9ky+Pnj7lrDLsH3AweN77wJ1ePk6ZlFrF9i+cY7ZAcWxFKizytzs", - "aflsoDqDhRxIFGlcRRpie60l3GpVWKT1A4jfDJUmWBiD/gRohBAQaPfHBqGqHYHhzoGktouUMtwVCdxo", - "Ho/LyG6Dp4dlO93G6rsjcfruXIzeXF7tr/L+yHmzdpB4pR57v34MMvvemB3sxLLneetwfs9Uzo2kUbpy", - "pdxdwj8FgeWeXqAc+4lICbBItVUoYCz5/Bp0ozajgSWtXbNQCGM5Dc2vt/cZiJKttq5Zsu0K/OkNX9Ae", - "84+DU+VpreS2i/pH/xniDP1yb5BafafX8LwktIqTHOMPh7m/2bSiFd4N2kp7wXKyo4ent5dVs4SFf45C", - "C6pt6fsEkcmzLPzjdOEaPhyivZA640Z6FP4OAAD//0nTejA+HAAA", -} - -// GetSwagger returns the content of the embedded swagger specification file -// or error if failed to decode -func decodeSpec() ([]byte, error) { - zipped, err := base64.StdEncoding.DecodeString(strings.Join(swaggerSpec, "")) - if err != nil { - return nil, fmt.Errorf("error base64 decoding spec: %w", err) - } - zr, err := gzip.NewReader(bytes.NewReader(zipped)) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - var buf bytes.Buffer - _, err = buf.ReadFrom(zr) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - - return buf.Bytes(), nil -} - -var rawSpec = decodeSpecCached() - -// a naive cached of a decoded swagger spec -func decodeSpecCached() func() ([]byte, error) { - data, err := decodeSpec() - return func() ([]byte, error) { - return data, err - } -} - -// Constructs a synthetic filesystem for resolving external references when loading openapi specifications. -func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { - res := make(map[string]func() ([]byte, error)) - if len(pathToFile) > 0 { - res[pathToFile] = rawSpec - } - - return res -} - -// GetSwagger returns the Swagger specification corresponding to the generated code -// in this file. The external references of Swagger specification are resolved. -// The logic of resolving external references is tightly connected to "import-mapping" feature. -// Externally referenced files must be embedded in the corresponding golang packages. -// Urls can be supported but this task was out of the scope. -func GetSwagger() (swagger *openapi3.T, err error) { - resolvePath := PathToRawSpec("") - - loader := openapi3.NewLoader() - loader.IsExternalRefsAllowed = true - loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() - pathToFile = path.Clean(pathToFile) - getSpec, ok := resolvePath[pathToFile] - if !ok { - err1 := fmt.Errorf("path not found: %s", pathToFile) - return nil, err1 - } - return getSpec() - } - var specData []byte - specData, err = rawSpec() - if err != nil { - return - } - swagger, err = loader.LoadFromData(specData) - if err != nil { - return - } - return -} diff --git a/internal/test/strict-server/fiber/server.go b/internal/test/strict-server/fiber/server.go deleted file mode 100644 index 914f967268..0000000000 --- a/internal/test/strict-server/fiber/server.go +++ /dev/null @@ -1,152 +0,0 @@ -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=server.cfg.yaml ../strict-schema.yaml -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=types.cfg.yaml ../strict-schema.yaml - -package api - -import ( - "context" - "encoding/json" - "io" - "mime/multipart" -) - -type StrictServer struct { -} - -func (s StrictServer) JSONExample(ctx context.Context, request JSONExampleRequestObject) (JSONExampleResponseObject, error) { - return JSONExample200JSONResponse(*request.Body), nil -} - -func (s StrictServer) MultipartExample(ctx context.Context, request MultipartExampleRequestObject) (MultipartExampleResponseObject, error) { - return MultipartExample200MultipartResponse(func(writer *multipart.Writer) error { - for { - part, err := request.Body.NextPart() - if err == io.EOF { - return nil - } else if err != nil { - return err - } - w, err := writer.CreatePart(part.Header) - if err != nil { - return err - } - _, err = io.Copy(w, part) - if err != nil { - return err - } - if err = part.Close(); err != nil { - return err - } - } - }), nil -} - -func (s StrictServer) MultipartRelatedExample(ctx context.Context, request MultipartRelatedExampleRequestObject) (MultipartRelatedExampleResponseObject, error) { - return MultipartRelatedExample200MultipartResponse(func(writer *multipart.Writer) error { - for { - part, err := request.Body.NextPart() - if err == io.EOF { - return nil - } else if err != nil { - return err - } - w, err := writer.CreatePart(part.Header) - if err != nil { - return err - } - _, err = io.Copy(w, part) - if err != nil { - return err - } - if err = part.Close(); err != nil { - return err - } - } - }), nil -} - -func (s StrictServer) MultipleRequestAndResponseTypes(ctx context.Context, request MultipleRequestAndResponseTypesRequestObject) (MultipleRequestAndResponseTypesResponseObject, error) { - switch { - case request.Body != nil: - return MultipleRequestAndResponseTypes200ImagepngResponse{Body: request.Body}, nil - case request.JSONBody != nil: - return MultipleRequestAndResponseTypes200JSONResponse(*request.JSONBody), nil - case request.FormdataBody != nil: - return MultipleRequestAndResponseTypes200FormdataResponse(*request.FormdataBody), nil - case request.TextBody != nil: - return MultipleRequestAndResponseTypes200TextResponse(*request.TextBody), nil - case request.MultipartBody != nil: - return MultipleRequestAndResponseTypes200MultipartResponse(func(writer *multipart.Writer) error { - for { - part, err := request.MultipartBody.NextPart() - if err == io.EOF { - return nil - } else if err != nil { - return err - } - w, err := writer.CreatePart(part.Header) - if err != nil { - return err - } - _, err = io.Copy(w, part) - if err != nil { - return err - } - if err = part.Close(); err != nil { - return err - } - } - }), nil - default: - return MultipleRequestAndResponseTypes400Response{}, nil - } -} - -func (s StrictServer) TextExample(ctx context.Context, request TextExampleRequestObject) (TextExampleResponseObject, error) { - return TextExample200TextResponse(*request.Body), nil -} - -func (s StrictServer) UnknownExample(ctx context.Context, request UnknownExampleRequestObject) (UnknownExampleResponseObject, error) { - return UnknownExample200Videomp4Response{Body: request.Body}, nil -} - -func (s StrictServer) UnspecifiedContentType(ctx context.Context, request UnspecifiedContentTypeRequestObject) (UnspecifiedContentTypeResponseObject, error) { - return UnspecifiedContentType200VideoResponse{Body: request.Body, ContentType: request.ContentType}, nil -} - -func (s StrictServer) URLEncodedExample(ctx context.Context, request URLEncodedExampleRequestObject) (URLEncodedExampleResponseObject, error) { - return URLEncodedExample200FormdataResponse(*request.Body), nil -} - -func (s StrictServer) HeadersExample(ctx context.Context, request HeadersExampleRequestObject) (HeadersExampleResponseObject, error) { - return HeadersExample200JSONResponse{Body: *request.Body, Headers: HeadersExample200ResponseHeaders{Header1: request.Params.Header1, Header2: *request.Params.Header2}}, nil -} - -func (s StrictServer) ReusableResponses(ctx context.Context, request ReusableResponsesRequestObject) (ReusableResponsesResponseObject, error) { - return ReusableResponses200JSONResponse{ReusableresponseJSONResponse: ReusableresponseJSONResponse{Body: *request.Body}}, nil -} - -func (s StrictServer) RequiredJSONBody(ctx context.Context, request RequiredJSONBodyRequestObject) (RequiredJSONBodyResponseObject, error) { - return RequiredJSONBody200JSONResponse(*request.Body), nil -} - -func (s StrictServer) RequiredTextBody(ctx context.Context, request RequiredTextBodyRequestObject) (RequiredTextBodyResponseObject, error) { - return RequiredTextBody200TextResponse(*request.Body), nil -} - -func (s StrictServer) ReservedGoKeywordParameters(ctx context.Context, request ReservedGoKeywordParametersRequestObject) (ReservedGoKeywordParametersResponseObject, error) { - return ReservedGoKeywordParameters200TextResponse(""), nil -} - -func (s StrictServer) UnionExample(ctx context.Context, request UnionExampleRequestObject) (UnionExampleResponseObject, error) { - union, err := json.Marshal(*request.Body) - if err != nil { - return nil, err - } - - return UnionExample200JSONResponse{ - Body: struct{ union json.RawMessage }{ - union: union, - }, - }, nil -} diff --git a/internal/test/strict-server/fiber/types.gen.go b/internal/test/strict-server/fiber/types.gen.go deleted file mode 100644 index fac014c4bb..0000000000 --- a/internal/test/strict-server/fiber/types.gen.go +++ /dev/null @@ -1,69 +0,0 @@ -// Package api provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package api - -// Example defines model for example. -type Example struct { - Value *string `json:"value,omitempty"` -} - -// Reusableresponse defines model for reusableresponse. -type Reusableresponse = Example - -// MultipleRequestAndResponseTypesTextBody defines parameters for MultipleRequestAndResponseTypes. -type MultipleRequestAndResponseTypesTextBody = string - -// RequiredTextBodyTextBody defines parameters for RequiredTextBody. -type RequiredTextBodyTextBody = string - -// TextExampleTextBody defines parameters for TextExample. -type TextExampleTextBody = string - -// HeadersExampleParams defines parameters for HeadersExample. -type HeadersExampleParams struct { - Header1 string `json:"header1"` - Header2 *int `json:"header2,omitempty"` -} - -// JSONExampleJSONRequestBody defines body for JSONExample for application/json ContentType. -type JSONExampleJSONRequestBody = Example - -// MultipartExampleMultipartRequestBody defines body for MultipartExample for multipart/form-data ContentType. -type MultipartExampleMultipartRequestBody = Example - -// MultipartRelatedExampleMultipartRequestBody defines body for MultipartRelatedExample for multipart/related ContentType. -type MultipartRelatedExampleMultipartRequestBody = Example - -// MultipleRequestAndResponseTypesJSONRequestBody defines body for MultipleRequestAndResponseTypes for application/json ContentType. -type MultipleRequestAndResponseTypesJSONRequestBody = Example - -// MultipleRequestAndResponseTypesFormdataRequestBody defines body for MultipleRequestAndResponseTypes for application/x-www-form-urlencoded ContentType. -type MultipleRequestAndResponseTypesFormdataRequestBody = Example - -// MultipleRequestAndResponseTypesMultipartRequestBody defines body for MultipleRequestAndResponseTypes for multipart/form-data ContentType. -type MultipleRequestAndResponseTypesMultipartRequestBody = Example - -// MultipleRequestAndResponseTypesTextRequestBody defines body for MultipleRequestAndResponseTypes for text/plain ContentType. -type MultipleRequestAndResponseTypesTextRequestBody = MultipleRequestAndResponseTypesTextBody - -// RequiredJSONBodyJSONRequestBody defines body for RequiredJSONBody for application/json ContentType. -type RequiredJSONBodyJSONRequestBody = Example - -// RequiredTextBodyTextRequestBody defines body for RequiredTextBody for text/plain ContentType. -type RequiredTextBodyTextRequestBody = RequiredTextBodyTextBody - -// ReusableResponsesJSONRequestBody defines body for ReusableResponses for application/json ContentType. -type ReusableResponsesJSONRequestBody = Example - -// TextExampleTextRequestBody defines body for TextExample for text/plain ContentType. -type TextExampleTextRequestBody = TextExampleTextBody - -// URLEncodedExampleFormdataRequestBody defines body for URLEncodedExample for application/x-www-form-urlencoded ContentType. -type URLEncodedExampleFormdataRequestBody = Example - -// HeadersExampleJSONRequestBody defines body for HeadersExample for application/json ContentType. -type HeadersExampleJSONRequestBody = Example - -// UnionExampleJSONRequestBody defines body for UnionExample for application/json ContentType. -type UnionExampleJSONRequestBody = Example diff --git a/internal/test/strict-server/gin/server.cfg.yaml b/internal/test/strict-server/gin/server.cfg.yaml deleted file mode 100644 index a79bf0e85d..0000000000 --- a/internal/test/strict-server/gin/server.cfg.yaml +++ /dev/null @@ -1,7 +0,0 @@ -# yaml-language-server: $schema=../../../../configuration-schema.json -package: api -generate: - gin-server: true - strict-server: true - embedded-spec: true -output: server.gen.go diff --git a/internal/test/strict-server/gin/server.gen.go b/internal/test/strict-server/gin/server.gen.go deleted file mode 100644 index b664de93d3..0000000000 --- a/internal/test/strict-server/gin/server.gen.go +++ /dev/null @@ -1,1622 +0,0 @@ -// Package api provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package api - -import ( - "bytes" - "compress/gzip" - "context" - "encoding/base64" - "encoding/json" - "errors" - "fmt" - "io" - "mime" - "mime/multipart" - "net/http" - "net/url" - "path" - "strings" - - "github.com/getkin/kin-openapi/openapi3" - "github.com/gin-gonic/gin" - "github.com/oapi-codegen/runtime" - strictgin "github.com/oapi-codegen/runtime/strictmiddleware/gin" -) - -// ServerInterface represents all server handlers. -type ServerInterface interface { - - // (POST /json) - JSONExample(c *gin.Context) - - // (POST /multipart) - MultipartExample(c *gin.Context) - - // (POST /multipart-related) - MultipartRelatedExample(c *gin.Context) - - // (POST /multiple) - MultipleRequestAndResponseTypes(c *gin.Context) - - // (POST /required-json-body) - RequiredJSONBody(c *gin.Context) - - // (POST /required-text-body) - RequiredTextBody(c *gin.Context) - - // (GET /reserved-go-keyword-parameters/{type}) - ReservedGoKeywordParameters(c *gin.Context, pType string) - - // (POST /reusable-responses) - ReusableResponses(c *gin.Context) - - // (POST /text) - TextExample(c *gin.Context) - - // (POST /unknown) - UnknownExample(c *gin.Context) - - // (POST /unspecified-content-type) - UnspecifiedContentType(c *gin.Context) - - // (POST /urlencoded) - URLEncodedExample(c *gin.Context) - - // (POST /with-headers) - HeadersExample(c *gin.Context, params HeadersExampleParams) - - // (POST /with-union) - UnionExample(c *gin.Context) -} - -// ServerInterfaceWrapper converts contexts to parameters. -type ServerInterfaceWrapper struct { - Handler ServerInterface - HandlerMiddlewares []MiddlewareFunc - ErrorHandler func(*gin.Context, error, int) -} - -type MiddlewareFunc func(c *gin.Context) - -// JSONExample operation middleware -func (siw *ServerInterfaceWrapper) JSONExample(c *gin.Context) { - - for _, middleware := range siw.HandlerMiddlewares { - middleware(c) - if c.IsAborted() { - return - } - } - - siw.Handler.JSONExample(c) -} - -// MultipartExample operation middleware -func (siw *ServerInterfaceWrapper) MultipartExample(c *gin.Context) { - - for _, middleware := range siw.HandlerMiddlewares { - middleware(c) - if c.IsAborted() { - return - } - } - - siw.Handler.MultipartExample(c) -} - -// MultipartRelatedExample operation middleware -func (siw *ServerInterfaceWrapper) MultipartRelatedExample(c *gin.Context) { - - for _, middleware := range siw.HandlerMiddlewares { - middleware(c) - if c.IsAborted() { - return - } - } - - siw.Handler.MultipartRelatedExample(c) -} - -// MultipleRequestAndResponseTypes operation middleware -func (siw *ServerInterfaceWrapper) MultipleRequestAndResponseTypes(c *gin.Context) { - - for _, middleware := range siw.HandlerMiddlewares { - middleware(c) - if c.IsAborted() { - return - } - } - - siw.Handler.MultipleRequestAndResponseTypes(c) -} - -// RequiredJSONBody operation middleware -func (siw *ServerInterfaceWrapper) RequiredJSONBody(c *gin.Context) { - - for _, middleware := range siw.HandlerMiddlewares { - middleware(c) - if c.IsAborted() { - return - } - } - - siw.Handler.RequiredJSONBody(c) -} - -// RequiredTextBody operation middleware -func (siw *ServerInterfaceWrapper) RequiredTextBody(c *gin.Context) { - - for _, middleware := range siw.HandlerMiddlewares { - middleware(c) - if c.IsAborted() { - return - } - } - - siw.Handler.RequiredTextBody(c) -} - -// ReservedGoKeywordParameters operation middleware -func (siw *ServerInterfaceWrapper) ReservedGoKeywordParameters(c *gin.Context) { - - var err error - - // ------------- Path parameter "type" ------------- - var pType string - - err = runtime.BindStyledParameterWithOptions("simple", "type", c.Param("type"), &pType, runtime.BindStyledParameterOptions{Explode: false, Required: true, Type: "string", Format: ""}) - if err != nil { - siw.ErrorHandler(c, fmt.Errorf("Invalid format for parameter type: %w", err), http.StatusBadRequest) - return - } - - for _, middleware := range siw.HandlerMiddlewares { - middleware(c) - if c.IsAborted() { - return - } - } - - siw.Handler.ReservedGoKeywordParameters(c, pType) -} - -// ReusableResponses operation middleware -func (siw *ServerInterfaceWrapper) ReusableResponses(c *gin.Context) { - - for _, middleware := range siw.HandlerMiddlewares { - middleware(c) - if c.IsAborted() { - return - } - } - - siw.Handler.ReusableResponses(c) -} - -// TextExample operation middleware -func (siw *ServerInterfaceWrapper) TextExample(c *gin.Context) { - - for _, middleware := range siw.HandlerMiddlewares { - middleware(c) - if c.IsAborted() { - return - } - } - - siw.Handler.TextExample(c) -} - -// UnknownExample operation middleware -func (siw *ServerInterfaceWrapper) UnknownExample(c *gin.Context) { - - for _, middleware := range siw.HandlerMiddlewares { - middleware(c) - if c.IsAborted() { - return - } - } - - siw.Handler.UnknownExample(c) -} - -// UnspecifiedContentType operation middleware -func (siw *ServerInterfaceWrapper) UnspecifiedContentType(c *gin.Context) { - - for _, middleware := range siw.HandlerMiddlewares { - middleware(c) - if c.IsAborted() { - return - } - } - - siw.Handler.UnspecifiedContentType(c) -} - -// URLEncodedExample operation middleware -func (siw *ServerInterfaceWrapper) URLEncodedExample(c *gin.Context) { - - for _, middleware := range siw.HandlerMiddlewares { - middleware(c) - if c.IsAborted() { - return - } - } - - siw.Handler.URLEncodedExample(c) -} - -// HeadersExample operation middleware -func (siw *ServerInterfaceWrapper) HeadersExample(c *gin.Context) { - - var err error - - // Parameter object where we will unmarshal all parameters from the context - var params HeadersExampleParams - - headers := c.Request.Header - - // ------------- Required header parameter "header1" ------------- - if valueList, found := headers[http.CanonicalHeaderKey("header1")]; found { - var Header1 string - n := len(valueList) - if n != 1 { - siw.ErrorHandler(c, fmt.Errorf("Expected one value for header1, got %d", n), http.StatusBadRequest) - return - } - - err = runtime.BindStyledParameterWithOptions("simple", "header1", valueList[0], &Header1, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: true, Type: "string", Format: ""}) - if err != nil { - siw.ErrorHandler(c, fmt.Errorf("Invalid format for parameter header1: %w", err), http.StatusBadRequest) - return - } - - params.Header1 = Header1 - - } else { - siw.ErrorHandler(c, fmt.Errorf("Header parameter header1 is required, but not found"), http.StatusBadRequest) - return - } - - // ------------- Optional header parameter "header2" ------------- - if valueList, found := headers[http.CanonicalHeaderKey("header2")]; found { - var Header2 int - n := len(valueList) - if n != 1 { - siw.ErrorHandler(c, fmt.Errorf("Expected one value for header2, got %d", n), http.StatusBadRequest) - return - } - - err = runtime.BindStyledParameterWithOptions("simple", "header2", valueList[0], &Header2, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: ""}) - if err != nil { - siw.ErrorHandler(c, fmt.Errorf("Invalid format for parameter header2: %w", err), http.StatusBadRequest) - return - } - - params.Header2 = &Header2 - - } - - for _, middleware := range siw.HandlerMiddlewares { - middleware(c) - if c.IsAborted() { - return - } - } - - siw.Handler.HeadersExample(c, params) -} - -// UnionExample operation middleware -func (siw *ServerInterfaceWrapper) UnionExample(c *gin.Context) { - - for _, middleware := range siw.HandlerMiddlewares { - middleware(c) - if c.IsAborted() { - return - } - } - - siw.Handler.UnionExample(c) -} - -// GinServerOptions provides options for the Gin server. -type GinServerOptions struct { - BaseURL string - Middlewares []MiddlewareFunc - ErrorHandler func(*gin.Context, error, int) -} - -// RegisterHandlers creates http.Handler with routing matching OpenAPI spec. -func RegisterHandlers(router gin.IRouter, si ServerInterface) { - RegisterHandlersWithOptions(router, si, GinServerOptions{}) -} - -// RegisterHandlersWithOptions creates http.Handler with additional options -func RegisterHandlersWithOptions(router gin.IRouter, si ServerInterface, options GinServerOptions) { - errorHandler := options.ErrorHandler - if errorHandler == nil { - errorHandler = func(c *gin.Context, err error, statusCode int) { - c.JSON(statusCode, gin.H{"msg": err.Error()}) - } - } - - wrapper := ServerInterfaceWrapper{ - Handler: si, - HandlerMiddlewares: options.Middlewares, - ErrorHandler: errorHandler, - } - - router.POST(options.BaseURL+"/json", wrapper.JSONExample) - router.POST(options.BaseURL+"/multipart", wrapper.MultipartExample) - router.POST(options.BaseURL+"/multipart-related", wrapper.MultipartRelatedExample) - router.POST(options.BaseURL+"/multiple", wrapper.MultipleRequestAndResponseTypes) - router.POST(options.BaseURL+"/required-json-body", wrapper.RequiredJSONBody) - router.POST(options.BaseURL+"/required-text-body", wrapper.RequiredTextBody) - router.GET(options.BaseURL+"/reserved-go-keyword-parameters/:type", wrapper.ReservedGoKeywordParameters) - router.POST(options.BaseURL+"/reusable-responses", wrapper.ReusableResponses) - router.POST(options.BaseURL+"/text", wrapper.TextExample) - router.POST(options.BaseURL+"/unknown", wrapper.UnknownExample) - router.POST(options.BaseURL+"/unspecified-content-type", wrapper.UnspecifiedContentType) - router.POST(options.BaseURL+"/urlencoded", wrapper.URLEncodedExample) - router.POST(options.BaseURL+"/with-headers", wrapper.HeadersExample) - router.POST(options.BaseURL+"/with-union", wrapper.UnionExample) -} - -type BadrequestResponse struct { -} - -type ReusableresponseResponseHeaders struct { - Header1 string - Header2 int -} -type ReusableresponseJSONResponse struct { - Body Example - - Headers ReusableresponseResponseHeaders -} - -type JSONExampleRequestObject struct { - Body *JSONExampleJSONRequestBody -} - -type JSONExampleResponseObject interface { - VisitJSONExampleResponse(w http.ResponseWriter) error -} - -type JSONExample200JSONResponse Example - -func (response JSONExample200JSONResponse) VisitJSONExampleResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(200) - - return json.NewEncoder(w).Encode(response) -} - -type JSONExample400Response = BadrequestResponse - -func (response JSONExample400Response) VisitJSONExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type JSONExampledefaultResponse struct { - StatusCode int -} - -func (response JSONExampledefaultResponse) VisitJSONExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -type MultipartExampleRequestObject struct { - Body *multipart.Reader -} - -type MultipartExampleResponseObject interface { - VisitMultipartExampleResponse(w http.ResponseWriter) error -} - -type MultipartExample200MultipartResponse func(writer *multipart.Writer) error - -func (response MultipartExample200MultipartResponse) VisitMultipartExampleResponse(w http.ResponseWriter) error { - writer := multipart.NewWriter(w) - w.Header().Set("Content-Type", writer.FormDataContentType()) - w.WriteHeader(200) - - defer writer.Close() - return response(writer) -} - -type MultipartExample400Response = BadrequestResponse - -func (response MultipartExample400Response) VisitMultipartExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type MultipartExampledefaultResponse struct { - StatusCode int -} - -func (response MultipartExampledefaultResponse) VisitMultipartExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -type MultipartRelatedExampleRequestObject struct { - Body *multipart.Reader -} - -type MultipartRelatedExampleResponseObject interface { - VisitMultipartRelatedExampleResponse(w http.ResponseWriter) error -} - -type MultipartRelatedExample200MultipartResponse func(writer *multipart.Writer) error - -func (response MultipartRelatedExample200MultipartResponse) VisitMultipartRelatedExampleResponse(w http.ResponseWriter) error { - writer := multipart.NewWriter(w) - w.Header().Set("Content-Type", mime.FormatMediaType("multipart/related", map[string]string{"boundary": writer.Boundary()})) - w.WriteHeader(200) - - defer writer.Close() - return response(writer) -} - -type MultipartRelatedExample400Response = BadrequestResponse - -func (response MultipartRelatedExample400Response) VisitMultipartRelatedExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type MultipartRelatedExampledefaultResponse struct { - StatusCode int -} - -func (response MultipartRelatedExampledefaultResponse) VisitMultipartRelatedExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -type MultipleRequestAndResponseTypesRequestObject struct { - JSONBody *MultipleRequestAndResponseTypesJSONRequestBody - FormdataBody *MultipleRequestAndResponseTypesFormdataRequestBody - Body io.Reader - MultipartBody *multipart.Reader - TextBody *MultipleRequestAndResponseTypesTextRequestBody -} - -type MultipleRequestAndResponseTypesResponseObject interface { - VisitMultipleRequestAndResponseTypesResponse(w http.ResponseWriter) error -} - -type MultipleRequestAndResponseTypes200JSONResponse Example - -func (response MultipleRequestAndResponseTypes200JSONResponse) VisitMultipleRequestAndResponseTypesResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(200) - - return json.NewEncoder(w).Encode(response) -} - -type MultipleRequestAndResponseTypes200FormdataResponse Example - -func (response MultipleRequestAndResponseTypes200FormdataResponse) VisitMultipleRequestAndResponseTypesResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/x-www-form-urlencoded") - w.WriteHeader(200) - - if form, err := runtime.MarshalForm(response, nil); err != nil { - return err - } else { - _, err := w.Write([]byte(form.Encode())) - return err - } -} - -type MultipleRequestAndResponseTypes200ImagepngResponse struct { - Body io.Reader - ContentLength int64 -} - -func (response MultipleRequestAndResponseTypes200ImagepngResponse) VisitMultipleRequestAndResponseTypesResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "image/png") - if response.ContentLength != 0 { - w.Header().Set("Content-Length", fmt.Sprint(response.ContentLength)) - } - w.WriteHeader(200) - - if closer, ok := response.Body.(io.ReadCloser); ok { - defer closer.Close() - } - _, err := io.Copy(w, response.Body) - return err -} - -type MultipleRequestAndResponseTypes200MultipartResponse func(writer *multipart.Writer) error - -func (response MultipleRequestAndResponseTypes200MultipartResponse) VisitMultipleRequestAndResponseTypesResponse(w http.ResponseWriter) error { - writer := multipart.NewWriter(w) - w.Header().Set("Content-Type", writer.FormDataContentType()) - w.WriteHeader(200) - - defer writer.Close() - return response(writer) -} - -type MultipleRequestAndResponseTypes200TextResponse string - -func (response MultipleRequestAndResponseTypes200TextResponse) VisitMultipleRequestAndResponseTypesResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "text/plain") - w.WriteHeader(200) - - _, err := w.Write([]byte(response)) - return err -} - -type MultipleRequestAndResponseTypes400Response = BadrequestResponse - -func (response MultipleRequestAndResponseTypes400Response) VisitMultipleRequestAndResponseTypesResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type RequiredJSONBodyRequestObject struct { - Body *RequiredJSONBodyJSONRequestBody -} - -type RequiredJSONBodyResponseObject interface { - VisitRequiredJSONBodyResponse(w http.ResponseWriter) error -} - -type RequiredJSONBody200JSONResponse Example - -func (response RequiredJSONBody200JSONResponse) VisitRequiredJSONBodyResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(200) - - return json.NewEncoder(w).Encode(response) -} - -type RequiredJSONBody400Response = BadrequestResponse - -func (response RequiredJSONBody400Response) VisitRequiredJSONBodyResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type RequiredJSONBodydefaultResponse struct { - StatusCode int -} - -func (response RequiredJSONBodydefaultResponse) VisitRequiredJSONBodyResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -type RequiredTextBodyRequestObject struct { - Body *RequiredTextBodyTextRequestBody -} - -type RequiredTextBodyResponseObject interface { - VisitRequiredTextBodyResponse(w http.ResponseWriter) error -} - -type RequiredTextBody200TextResponse string - -func (response RequiredTextBody200TextResponse) VisitRequiredTextBodyResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "text/plain") - w.WriteHeader(200) - - _, err := w.Write([]byte(response)) - return err -} - -type RequiredTextBody400Response = BadrequestResponse - -func (response RequiredTextBody400Response) VisitRequiredTextBodyResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type RequiredTextBodydefaultResponse struct { - StatusCode int -} - -func (response RequiredTextBodydefaultResponse) VisitRequiredTextBodyResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -type ReservedGoKeywordParametersRequestObject struct { - Type string `json:"type"` -} - -type ReservedGoKeywordParametersResponseObject interface { - VisitReservedGoKeywordParametersResponse(w http.ResponseWriter) error -} - -type ReservedGoKeywordParameters200TextResponse string - -func (response ReservedGoKeywordParameters200TextResponse) VisitReservedGoKeywordParametersResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "text/plain") - w.WriteHeader(200) - - _, err := w.Write([]byte(response)) - return err -} - -type ReusableResponsesRequestObject struct { - Body *ReusableResponsesJSONRequestBody -} - -type ReusableResponsesResponseObject interface { - VisitReusableResponsesResponse(w http.ResponseWriter) error -} - -type ReusableResponses200JSONResponse struct{ ReusableresponseJSONResponse } - -func (response ReusableResponses200JSONResponse) VisitReusableResponsesResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/json") - w.Header().Set("header1", fmt.Sprint(response.Headers.Header1)) - w.Header().Set("header2", fmt.Sprint(response.Headers.Header2)) - w.WriteHeader(200) - - return json.NewEncoder(w).Encode(response.Body) -} - -type ReusableResponses400Response = BadrequestResponse - -func (response ReusableResponses400Response) VisitReusableResponsesResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type ReusableResponsesdefaultResponse struct { - StatusCode int -} - -func (response ReusableResponsesdefaultResponse) VisitReusableResponsesResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -type TextExampleRequestObject struct { - Body *TextExampleTextRequestBody -} - -type TextExampleResponseObject interface { - VisitTextExampleResponse(w http.ResponseWriter) error -} - -type TextExample200TextResponse string - -func (response TextExample200TextResponse) VisitTextExampleResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "text/plain") - w.WriteHeader(200) - - _, err := w.Write([]byte(response)) - return err -} - -type TextExample400Response = BadrequestResponse - -func (response TextExample400Response) VisitTextExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type TextExampledefaultResponse struct { - StatusCode int -} - -func (response TextExampledefaultResponse) VisitTextExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -type UnknownExampleRequestObject struct { - Body io.Reader -} - -type UnknownExampleResponseObject interface { - VisitUnknownExampleResponse(w http.ResponseWriter) error -} - -type UnknownExample200Videomp4Response struct { - Body io.Reader - ContentLength int64 -} - -func (response UnknownExample200Videomp4Response) VisitUnknownExampleResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "video/mp4") - if response.ContentLength != 0 { - w.Header().Set("Content-Length", fmt.Sprint(response.ContentLength)) - } - w.WriteHeader(200) - - if closer, ok := response.Body.(io.ReadCloser); ok { - defer closer.Close() - } - _, err := io.Copy(w, response.Body) - return err -} - -type UnknownExample400Response = BadrequestResponse - -func (response UnknownExample400Response) VisitUnknownExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type UnknownExampledefaultResponse struct { - StatusCode int -} - -func (response UnknownExampledefaultResponse) VisitUnknownExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -type UnspecifiedContentTypeRequestObject struct { - ContentType string - Body io.Reader -} - -type UnspecifiedContentTypeResponseObject interface { - VisitUnspecifiedContentTypeResponse(w http.ResponseWriter) error -} - -type UnspecifiedContentType200VideoResponse struct { - Body io.Reader - ContentType string - ContentLength int64 -} - -func (response UnspecifiedContentType200VideoResponse) VisitUnspecifiedContentTypeResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", response.ContentType) - if response.ContentLength != 0 { - w.Header().Set("Content-Length", fmt.Sprint(response.ContentLength)) - } - w.WriteHeader(200) - - if closer, ok := response.Body.(io.ReadCloser); ok { - defer closer.Close() - } - _, err := io.Copy(w, response.Body) - return err -} - -type UnspecifiedContentType400Response = BadrequestResponse - -func (response UnspecifiedContentType400Response) VisitUnspecifiedContentTypeResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type UnspecifiedContentType401Response struct { -} - -func (response UnspecifiedContentType401Response) VisitUnspecifiedContentTypeResponse(w http.ResponseWriter) error { - w.WriteHeader(401) - return nil -} - -type UnspecifiedContentType403Response struct { -} - -func (response UnspecifiedContentType403Response) VisitUnspecifiedContentTypeResponse(w http.ResponseWriter) error { - w.WriteHeader(403) - return nil -} - -type UnspecifiedContentTypedefaultResponse struct { - StatusCode int -} - -func (response UnspecifiedContentTypedefaultResponse) VisitUnspecifiedContentTypeResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -type URLEncodedExampleRequestObject struct { - Body *URLEncodedExampleFormdataRequestBody -} - -type URLEncodedExampleResponseObject interface { - VisitURLEncodedExampleResponse(w http.ResponseWriter) error -} - -type URLEncodedExample200FormdataResponse Example - -func (response URLEncodedExample200FormdataResponse) VisitURLEncodedExampleResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/x-www-form-urlencoded") - w.WriteHeader(200) - - if form, err := runtime.MarshalForm(response, nil); err != nil { - return err - } else { - _, err := w.Write([]byte(form.Encode())) - return err - } -} - -type URLEncodedExample400Response = BadrequestResponse - -func (response URLEncodedExample400Response) VisitURLEncodedExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type URLEncodedExampledefaultResponse struct { - StatusCode int -} - -func (response URLEncodedExampledefaultResponse) VisitURLEncodedExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -type HeadersExampleRequestObject struct { - Params HeadersExampleParams - Body *HeadersExampleJSONRequestBody -} - -type HeadersExampleResponseObject interface { - VisitHeadersExampleResponse(w http.ResponseWriter) error -} - -type HeadersExample200ResponseHeaders struct { - Header1 string - Header2 int -} - -type HeadersExample200JSONResponse struct { - Body Example - Headers HeadersExample200ResponseHeaders -} - -func (response HeadersExample200JSONResponse) VisitHeadersExampleResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/json") - w.Header().Set("header1", fmt.Sprint(response.Headers.Header1)) - w.Header().Set("header2", fmt.Sprint(response.Headers.Header2)) - w.WriteHeader(200) - - return json.NewEncoder(w).Encode(response.Body) -} - -type HeadersExample400Response = BadrequestResponse - -func (response HeadersExample400Response) VisitHeadersExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type HeadersExampledefaultResponse struct { - StatusCode int -} - -func (response HeadersExampledefaultResponse) VisitHeadersExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -type UnionExampleRequestObject struct { - Body *UnionExampleJSONRequestBody -} - -type UnionExampleResponseObject interface { - VisitUnionExampleResponse(w http.ResponseWriter) error -} - -type UnionExample200ResponseHeaders struct { - Header1 string - Header2 int -} - -type UnionExample200ApplicationAlternativePlusJSONResponse struct { - Body Example - Headers UnionExample200ResponseHeaders -} - -func (response UnionExample200ApplicationAlternativePlusJSONResponse) VisitUnionExampleResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/alternative+json") - w.Header().Set("header1", fmt.Sprint(response.Headers.Header1)) - w.Header().Set("header2", fmt.Sprint(response.Headers.Header2)) - w.WriteHeader(200) - - return json.NewEncoder(w).Encode(response.Body) -} - -type UnionExample200JSONResponse struct { - Body struct { - union json.RawMessage - } - Headers UnionExample200ResponseHeaders -} - -func (response UnionExample200JSONResponse) VisitUnionExampleResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/json") - w.Header().Set("header1", fmt.Sprint(response.Headers.Header1)) - w.Header().Set("header2", fmt.Sprint(response.Headers.Header2)) - w.WriteHeader(200) - - return json.NewEncoder(w).Encode(response.Body.union) -} - -type UnionExample400Response = BadrequestResponse - -func (response UnionExample400Response) VisitUnionExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type UnionExampledefaultResponse struct { - StatusCode int -} - -func (response UnionExampledefaultResponse) VisitUnionExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -// StrictServerInterface represents all server handlers. -type StrictServerInterface interface { - - // (POST /json) - JSONExample(ctx context.Context, request JSONExampleRequestObject) (JSONExampleResponseObject, error) - - // (POST /multipart) - MultipartExample(ctx context.Context, request MultipartExampleRequestObject) (MultipartExampleResponseObject, error) - - // (POST /multipart-related) - MultipartRelatedExample(ctx context.Context, request MultipartRelatedExampleRequestObject) (MultipartRelatedExampleResponseObject, error) - - // (POST /multiple) - MultipleRequestAndResponseTypes(ctx context.Context, request MultipleRequestAndResponseTypesRequestObject) (MultipleRequestAndResponseTypesResponseObject, error) - - // (POST /required-json-body) - RequiredJSONBody(ctx context.Context, request RequiredJSONBodyRequestObject) (RequiredJSONBodyResponseObject, error) - - // (POST /required-text-body) - RequiredTextBody(ctx context.Context, request RequiredTextBodyRequestObject) (RequiredTextBodyResponseObject, error) - - // (GET /reserved-go-keyword-parameters/{type}) - ReservedGoKeywordParameters(ctx context.Context, request ReservedGoKeywordParametersRequestObject) (ReservedGoKeywordParametersResponseObject, error) - - // (POST /reusable-responses) - ReusableResponses(ctx context.Context, request ReusableResponsesRequestObject) (ReusableResponsesResponseObject, error) - - // (POST /text) - TextExample(ctx context.Context, request TextExampleRequestObject) (TextExampleResponseObject, error) - - // (POST /unknown) - UnknownExample(ctx context.Context, request UnknownExampleRequestObject) (UnknownExampleResponseObject, error) - - // (POST /unspecified-content-type) - UnspecifiedContentType(ctx context.Context, request UnspecifiedContentTypeRequestObject) (UnspecifiedContentTypeResponseObject, error) - - // (POST /urlencoded) - URLEncodedExample(ctx context.Context, request URLEncodedExampleRequestObject) (URLEncodedExampleResponseObject, error) - - // (POST /with-headers) - HeadersExample(ctx context.Context, request HeadersExampleRequestObject) (HeadersExampleResponseObject, error) - - // (POST /with-union) - UnionExample(ctx context.Context, request UnionExampleRequestObject) (UnionExampleResponseObject, error) -} - -type StrictHandlerFunc = strictgin.StrictGinHandlerFunc -type StrictMiddlewareFunc = strictgin.StrictGinMiddlewareFunc - -func NewStrictHandler(ssi StrictServerInterface, middlewares []StrictMiddlewareFunc) ServerInterface { - return &strictHandler{ssi: ssi, middlewares: middlewares} -} - -type strictHandler struct { - ssi StrictServerInterface - middlewares []StrictMiddlewareFunc -} - -// JSONExample operation middleware -func (sh *strictHandler) JSONExample(ctx *gin.Context) { - var request JSONExampleRequestObject - - var body JSONExampleJSONRequestBody - if err := ctx.ShouldBindJSON(&body); err != nil { - if !errors.Is(err, io.EOF) { - ctx.Status(http.StatusBadRequest) - ctx.Error(err) - return - } - } else { - request.Body = &body - } - - handler := func(ctx *gin.Context, request interface{}) (interface{}, error) { - return sh.ssi.JSONExample(ctx, request.(JSONExampleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "JSONExample") - } - - response, err := handler(ctx, request) - - if err != nil { - ctx.Error(err) - ctx.Status(http.StatusInternalServerError) - } else if validResponse, ok := response.(JSONExampleResponseObject); ok { - if err := validResponse.VisitJSONExampleResponse(ctx.Writer); err != nil { - ctx.Error(err) - } - } else if response != nil { - ctx.Error(fmt.Errorf("unexpected response type: %T", response)) - } -} - -// MultipartExample operation middleware -func (sh *strictHandler) MultipartExample(ctx *gin.Context) { - var request MultipartExampleRequestObject - - if reader, err := ctx.Request.MultipartReader(); err == nil { - request.Body = reader - } else { - ctx.Error(err) - return - } - - handler := func(ctx *gin.Context, request interface{}) (interface{}, error) { - return sh.ssi.MultipartExample(ctx, request.(MultipartExampleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "MultipartExample") - } - - response, err := handler(ctx, request) - - if err != nil { - ctx.Error(err) - ctx.Status(http.StatusInternalServerError) - } else if validResponse, ok := response.(MultipartExampleResponseObject); ok { - if err := validResponse.VisitMultipartExampleResponse(ctx.Writer); err != nil { - ctx.Error(err) - } - } else if response != nil { - ctx.Error(fmt.Errorf("unexpected response type: %T", response)) - } -} - -// MultipartRelatedExample operation middleware -func (sh *strictHandler) MultipartRelatedExample(ctx *gin.Context) { - var request MultipartRelatedExampleRequestObject - - if _, params, err := mime.ParseMediaType(ctx.Request.Header.Get("Content-Type")); err != nil { - ctx.Error(err) - return - } else if boundary := params["boundary"]; boundary == "" { - ctx.Error(http.ErrMissingBoundary) - return - } else { - request.Body = multipart.NewReader(ctx.Request.Body, boundary) - } - - handler := func(ctx *gin.Context, request interface{}) (interface{}, error) { - return sh.ssi.MultipartRelatedExample(ctx, request.(MultipartRelatedExampleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "MultipartRelatedExample") - } - - response, err := handler(ctx, request) - - if err != nil { - ctx.Error(err) - ctx.Status(http.StatusInternalServerError) - } else if validResponse, ok := response.(MultipartRelatedExampleResponseObject); ok { - if err := validResponse.VisitMultipartRelatedExampleResponse(ctx.Writer); err != nil { - ctx.Error(err) - } - } else if response != nil { - ctx.Error(fmt.Errorf("unexpected response type: %T", response)) - } -} - -// MultipleRequestAndResponseTypes operation middleware -func (sh *strictHandler) MultipleRequestAndResponseTypes(ctx *gin.Context) { - var request MultipleRequestAndResponseTypesRequestObject - - if strings.HasPrefix(ctx.GetHeader("Content-Type"), "application/json") { - - var body MultipleRequestAndResponseTypesJSONRequestBody - if err := ctx.ShouldBindJSON(&body); err != nil { - if !errors.Is(err, io.EOF) { - ctx.Status(http.StatusBadRequest) - ctx.Error(err) - return - } - } else { - request.JSONBody = &body - } - } - if strings.HasPrefix(ctx.GetHeader("Content-Type"), "application/x-www-form-urlencoded") { - if err := ctx.Request.ParseForm(); err != nil { - ctx.Error(err) - return - } - var body MultipleRequestAndResponseTypesFormdataRequestBody - if err := runtime.BindForm(&body, ctx.Request.Form, nil, nil); err != nil { - ctx.Error(err) - return - } - request.FormdataBody = &body - } - if strings.HasPrefix(ctx.GetHeader("Content-Type"), "image/png") { - request.Body = ctx.Request.Body - } - if strings.HasPrefix(ctx.GetHeader("Content-Type"), "multipart/form-data") { - if reader, err := ctx.Request.MultipartReader(); err == nil { - request.MultipartBody = reader - } else { - ctx.Error(err) - return - } - } - if strings.HasPrefix(ctx.GetHeader("Content-Type"), "text/plain") { - data, err := io.ReadAll(ctx.Request.Body) - if err != nil { - ctx.Error(err) - return - } - if len(data) > 0 { - body := MultipleRequestAndResponseTypesTextRequestBody(data) - request.TextBody = &body - } - } - - handler := func(ctx *gin.Context, request interface{}) (interface{}, error) { - return sh.ssi.MultipleRequestAndResponseTypes(ctx, request.(MultipleRequestAndResponseTypesRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "MultipleRequestAndResponseTypes") - } - - response, err := handler(ctx, request) - - if err != nil { - ctx.Error(err) - ctx.Status(http.StatusInternalServerError) - } else if validResponse, ok := response.(MultipleRequestAndResponseTypesResponseObject); ok { - if err := validResponse.VisitMultipleRequestAndResponseTypesResponse(ctx.Writer); err != nil { - ctx.Error(err) - } - } else if response != nil { - ctx.Error(fmt.Errorf("unexpected response type: %T", response)) - } -} - -// RequiredJSONBody operation middleware -func (sh *strictHandler) RequiredJSONBody(ctx *gin.Context) { - var request RequiredJSONBodyRequestObject - - var body RequiredJSONBodyJSONRequestBody - if err := ctx.ShouldBindJSON(&body); err != nil { - ctx.Status(http.StatusBadRequest) - ctx.Error(err) - return - } - request.Body = &body - - handler := func(ctx *gin.Context, request interface{}) (interface{}, error) { - return sh.ssi.RequiredJSONBody(ctx, request.(RequiredJSONBodyRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "RequiredJSONBody") - } - - response, err := handler(ctx, request) - - if err != nil { - ctx.Error(err) - ctx.Status(http.StatusInternalServerError) - } else if validResponse, ok := response.(RequiredJSONBodyResponseObject); ok { - if err := validResponse.VisitRequiredJSONBodyResponse(ctx.Writer); err != nil { - ctx.Error(err) - } - } else if response != nil { - ctx.Error(fmt.Errorf("unexpected response type: %T", response)) - } -} - -// RequiredTextBody operation middleware -func (sh *strictHandler) RequiredTextBody(ctx *gin.Context) { - var request RequiredTextBodyRequestObject - - data, err := io.ReadAll(ctx.Request.Body) - if err != nil { - ctx.Error(err) - return - } - body := RequiredTextBodyTextRequestBody(data) - request.Body = &body - - handler := func(ctx *gin.Context, request interface{}) (interface{}, error) { - return sh.ssi.RequiredTextBody(ctx, request.(RequiredTextBodyRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "RequiredTextBody") - } - - response, err := handler(ctx, request) - - if err != nil { - ctx.Error(err) - ctx.Status(http.StatusInternalServerError) - } else if validResponse, ok := response.(RequiredTextBodyResponseObject); ok { - if err := validResponse.VisitRequiredTextBodyResponse(ctx.Writer); err != nil { - ctx.Error(err) - } - } else if response != nil { - ctx.Error(fmt.Errorf("unexpected response type: %T", response)) - } -} - -// ReservedGoKeywordParameters operation middleware -func (sh *strictHandler) ReservedGoKeywordParameters(ctx *gin.Context, pType string) { - var request ReservedGoKeywordParametersRequestObject - - request.Type = pType - - handler := func(ctx *gin.Context, request interface{}) (interface{}, error) { - return sh.ssi.ReservedGoKeywordParameters(ctx, request.(ReservedGoKeywordParametersRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "ReservedGoKeywordParameters") - } - - response, err := handler(ctx, request) - - if err != nil { - ctx.Error(err) - ctx.Status(http.StatusInternalServerError) - } else if validResponse, ok := response.(ReservedGoKeywordParametersResponseObject); ok { - if err := validResponse.VisitReservedGoKeywordParametersResponse(ctx.Writer); err != nil { - ctx.Error(err) - } - } else if response != nil { - ctx.Error(fmt.Errorf("unexpected response type: %T", response)) - } -} - -// ReusableResponses operation middleware -func (sh *strictHandler) ReusableResponses(ctx *gin.Context) { - var request ReusableResponsesRequestObject - - var body ReusableResponsesJSONRequestBody - if err := ctx.ShouldBindJSON(&body); err != nil { - if !errors.Is(err, io.EOF) { - ctx.Status(http.StatusBadRequest) - ctx.Error(err) - return - } - } else { - request.Body = &body - } - - handler := func(ctx *gin.Context, request interface{}) (interface{}, error) { - return sh.ssi.ReusableResponses(ctx, request.(ReusableResponsesRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "ReusableResponses") - } - - response, err := handler(ctx, request) - - if err != nil { - ctx.Error(err) - ctx.Status(http.StatusInternalServerError) - } else if validResponse, ok := response.(ReusableResponsesResponseObject); ok { - if err := validResponse.VisitReusableResponsesResponse(ctx.Writer); err != nil { - ctx.Error(err) - } - } else if response != nil { - ctx.Error(fmt.Errorf("unexpected response type: %T", response)) - } -} - -// TextExample operation middleware -func (sh *strictHandler) TextExample(ctx *gin.Context) { - var request TextExampleRequestObject - - data, err := io.ReadAll(ctx.Request.Body) - if err != nil { - ctx.Error(err) - return - } - if len(data) > 0 { - body := TextExampleTextRequestBody(data) - request.Body = &body - } - - handler := func(ctx *gin.Context, request interface{}) (interface{}, error) { - return sh.ssi.TextExample(ctx, request.(TextExampleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "TextExample") - } - - response, err := handler(ctx, request) - - if err != nil { - ctx.Error(err) - ctx.Status(http.StatusInternalServerError) - } else if validResponse, ok := response.(TextExampleResponseObject); ok { - if err := validResponse.VisitTextExampleResponse(ctx.Writer); err != nil { - ctx.Error(err) - } - } else if response != nil { - ctx.Error(fmt.Errorf("unexpected response type: %T", response)) - } -} - -// UnknownExample operation middleware -func (sh *strictHandler) UnknownExample(ctx *gin.Context) { - var request UnknownExampleRequestObject - - request.Body = ctx.Request.Body - - handler := func(ctx *gin.Context, request interface{}) (interface{}, error) { - return sh.ssi.UnknownExample(ctx, request.(UnknownExampleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "UnknownExample") - } - - response, err := handler(ctx, request) - - if err != nil { - ctx.Error(err) - ctx.Status(http.StatusInternalServerError) - } else if validResponse, ok := response.(UnknownExampleResponseObject); ok { - if err := validResponse.VisitUnknownExampleResponse(ctx.Writer); err != nil { - ctx.Error(err) - } - } else if response != nil { - ctx.Error(fmt.Errorf("unexpected response type: %T", response)) - } -} - -// UnspecifiedContentType operation middleware -func (sh *strictHandler) UnspecifiedContentType(ctx *gin.Context) { - var request UnspecifiedContentTypeRequestObject - - request.ContentType = ctx.ContentType() - - request.Body = ctx.Request.Body - - handler := func(ctx *gin.Context, request interface{}) (interface{}, error) { - return sh.ssi.UnspecifiedContentType(ctx, request.(UnspecifiedContentTypeRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "UnspecifiedContentType") - } - - response, err := handler(ctx, request) - - if err != nil { - ctx.Error(err) - ctx.Status(http.StatusInternalServerError) - } else if validResponse, ok := response.(UnspecifiedContentTypeResponseObject); ok { - if err := validResponse.VisitUnspecifiedContentTypeResponse(ctx.Writer); err != nil { - ctx.Error(err) - } - } else if response != nil { - ctx.Error(fmt.Errorf("unexpected response type: %T", response)) - } -} - -// URLEncodedExample operation middleware -func (sh *strictHandler) URLEncodedExample(ctx *gin.Context) { - var request URLEncodedExampleRequestObject - - if err := ctx.Request.ParseForm(); err != nil { - ctx.Error(err) - return - } - var body URLEncodedExampleFormdataRequestBody - if err := runtime.BindForm(&body, ctx.Request.Form, nil, nil); err != nil { - ctx.Error(err) - return - } - request.Body = &body - - handler := func(ctx *gin.Context, request interface{}) (interface{}, error) { - return sh.ssi.URLEncodedExample(ctx, request.(URLEncodedExampleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "URLEncodedExample") - } - - response, err := handler(ctx, request) - - if err != nil { - ctx.Error(err) - ctx.Status(http.StatusInternalServerError) - } else if validResponse, ok := response.(URLEncodedExampleResponseObject); ok { - if err := validResponse.VisitURLEncodedExampleResponse(ctx.Writer); err != nil { - ctx.Error(err) - } - } else if response != nil { - ctx.Error(fmt.Errorf("unexpected response type: %T", response)) - } -} - -// HeadersExample operation middleware -func (sh *strictHandler) HeadersExample(ctx *gin.Context, params HeadersExampleParams) { - var request HeadersExampleRequestObject - - request.Params = params - - var body HeadersExampleJSONRequestBody - if err := ctx.ShouldBindJSON(&body); err != nil { - if !errors.Is(err, io.EOF) { - ctx.Status(http.StatusBadRequest) - ctx.Error(err) - return - } - } else { - request.Body = &body - } - - handler := func(ctx *gin.Context, request interface{}) (interface{}, error) { - return sh.ssi.HeadersExample(ctx, request.(HeadersExampleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "HeadersExample") - } - - response, err := handler(ctx, request) - - if err != nil { - ctx.Error(err) - ctx.Status(http.StatusInternalServerError) - } else if validResponse, ok := response.(HeadersExampleResponseObject); ok { - if err := validResponse.VisitHeadersExampleResponse(ctx.Writer); err != nil { - ctx.Error(err) - } - } else if response != nil { - ctx.Error(fmt.Errorf("unexpected response type: %T", response)) - } -} - -// UnionExample operation middleware -func (sh *strictHandler) UnionExample(ctx *gin.Context) { - var request UnionExampleRequestObject - - var body UnionExampleJSONRequestBody - if err := ctx.ShouldBindJSON(&body); err != nil { - if !errors.Is(err, io.EOF) { - ctx.Status(http.StatusBadRequest) - ctx.Error(err) - return - } - } else { - request.Body = &body - } - - handler := func(ctx *gin.Context, request interface{}) (interface{}, error) { - return sh.ssi.UnionExample(ctx, request.(UnionExampleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "UnionExample") - } - - response, err := handler(ctx, request) - - if err != nil { - ctx.Error(err) - ctx.Status(http.StatusInternalServerError) - } else if validResponse, ok := response.(UnionExampleResponseObject); ok { - if err := validResponse.VisitUnionExampleResponse(ctx.Writer); err != nil { - ctx.Error(err) - } - } else if response != nil { - ctx.Error(fmt.Errorf("unexpected response type: %T", response)) - } -} - -// Base64 encoded, gzipped, json marshaled Swagger object -var swaggerSpec = []string{ - - "H4sIAAAAAAAC/+xZTXPbNhP+Kzt431NKmrbjE2+NJ5O2aeuObJ86PkDESkJCAiiwFK3R6L93QEBfFq1K", - "qT4ynt5Ecr/wPLuLBTRlha6MVqjIsXzKLDqjlcP2oc+Fxb9qdOSfBLrCSkNSK5azD1z04rdZwizWjvdL", - "nKt7+UIrQtWqcmNKWXCvmn1xXn/KXDHCivtf/7c4YDn7X7YMJQtfXYbPvDIlstlslryI4O4zS9gIuUDb", - "Rht+Xq3bpolBljNHVqoh80aC2HWnmFSEQ7TemxeNQXiBeRz5lBmrDVqSAaMxL2vs9hTf6P4XLCisQKqB", - "3sTyViviUjkQcjBAi4ogggfehgNXG6MtoYD+BLyHgsChHaNlCSNJPjB2v/oeYsCOJWyM1gVHVxeXF5ee", - "L21QcSNZzt63rxJmOI3aBS0IMrqL91/u734H6YDXpCtOsuBlOYGKWzfiJQqQirQPsS7IXbDWk22J/1lE", - "7Y8RSp81bQJ90GJyjIRp83Ilna8vL0+Ul7OE3QRnXTYWQWUrBdaaGfC67MD8UX1VulGA1mobV5ZVdUnS", - "cEurXK2j/dtcZBfIF/aygbZVKjjxI6F+KE/nBj61WHJCsQMBvSC5Hw8r5o/Kwr/xc1YOYj/u7FP3I904", - "GOkGSINAXkIjaQRzxRcNVirg4KQalgjzoJJOMkuM296PSvTiWh68jaP3s2TNynPaNE3aFlBtS1SFFt9G", - "YcJkxYeYGTVcV/e2ObGc9SfkU3ZzgztQISeM8JkyU3Kptu/eJ2rp/yF9sMIO5eofpUWRekbSfqyP7sKN", - "5QVeyg8ac90EnIZKOl+l4aMb6boUwMuGT1zoD5sTRy+q+8mjLcyjjx3BgffJcrI1vu0xZEGtz6zzUPuA", - "z/SP1O6R+PvSd+qa2p+i9kwg0qFOv+Kk0VakhlteIaF12dTHOfO2hthh8o+FJBRcQR9B8QoF8AGhhU8a", - "oknXwU/w+0l/DiJLU+2BY/GQ/zllHrz2EMIS5h2wPOD3ko5kC8BPx6VqjmY46qZrrl5L+Cgyh87iwPmB", - "pIvjDvyCp96KxHmOTNtzc+Pwf4qk9ky+Pnj7lrDLsH3AweN77wJ1ePk6ZlFrF9i+cY7ZAcWxFKizytzs", - "aflsoDqDhRxIFGlcRRpie60l3GpVWKT1A4jfDJUmWBiD/gRohBAQaPfHBqGqHYHhzoGktouUMtwVCdxo", - "Ho/LyG6Dp4dlO93G6rsjcfruXIzeXF7tr/L+yHmzdpB4pR57v34MMvvemB3sxLLneetwfs9Uzo2kUbpy", - "pdxdwj8FgeWeXqAc+4lICbBItVUoYCz5/Bp0ozajgSWtXbNQCGM5Dc2vt/cZiJKttq5Zsu0K/OkNX9Ae", - "84+DU+VpreS2i/pH/xniDP1yb5BafafX8LwktIqTHOMPh7m/2bSiFd4N2kp7wXKyo4ent5dVs4SFf45C", - "C6pt6fsEkcmzLPzjdOEaPhyivZA640Z6FP4OAAD//0nTejA+HAAA", -} - -// GetSwagger returns the content of the embedded swagger specification file -// or error if failed to decode -func decodeSpec() ([]byte, error) { - zipped, err := base64.StdEncoding.DecodeString(strings.Join(swaggerSpec, "")) - if err != nil { - return nil, fmt.Errorf("error base64 decoding spec: %w", err) - } - zr, err := gzip.NewReader(bytes.NewReader(zipped)) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - var buf bytes.Buffer - _, err = buf.ReadFrom(zr) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - - return buf.Bytes(), nil -} - -var rawSpec = decodeSpecCached() - -// a naive cached of a decoded swagger spec -func decodeSpecCached() func() ([]byte, error) { - data, err := decodeSpec() - return func() ([]byte, error) { - return data, err - } -} - -// Constructs a synthetic filesystem for resolving external references when loading openapi specifications. -func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { - res := make(map[string]func() ([]byte, error)) - if len(pathToFile) > 0 { - res[pathToFile] = rawSpec - } - - return res -} - -// GetSwagger returns the Swagger specification corresponding to the generated code -// in this file. The external references of Swagger specification are resolved. -// The logic of resolving external references is tightly connected to "import-mapping" feature. -// Externally referenced files must be embedded in the corresponding golang packages. -// Urls can be supported but this task was out of the scope. -func GetSwagger() (swagger *openapi3.T, err error) { - resolvePath := PathToRawSpec("") - - loader := openapi3.NewLoader() - loader.IsExternalRefsAllowed = true - loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() - pathToFile = path.Clean(pathToFile) - getSpec, ok := resolvePath[pathToFile] - if !ok { - err1 := fmt.Errorf("path not found: %s", pathToFile) - return nil, err1 - } - return getSpec() - } - var specData []byte - specData, err = rawSpec() - if err != nil { - return - } - swagger, err = loader.LoadFromData(specData) - if err != nil { - return - } - return -} diff --git a/internal/test/strict-server/gin/server.go b/internal/test/strict-server/gin/server.go deleted file mode 100644 index 914f967268..0000000000 --- a/internal/test/strict-server/gin/server.go +++ /dev/null @@ -1,152 +0,0 @@ -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=server.cfg.yaml ../strict-schema.yaml -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=types.cfg.yaml ../strict-schema.yaml - -package api - -import ( - "context" - "encoding/json" - "io" - "mime/multipart" -) - -type StrictServer struct { -} - -func (s StrictServer) JSONExample(ctx context.Context, request JSONExampleRequestObject) (JSONExampleResponseObject, error) { - return JSONExample200JSONResponse(*request.Body), nil -} - -func (s StrictServer) MultipartExample(ctx context.Context, request MultipartExampleRequestObject) (MultipartExampleResponseObject, error) { - return MultipartExample200MultipartResponse(func(writer *multipart.Writer) error { - for { - part, err := request.Body.NextPart() - if err == io.EOF { - return nil - } else if err != nil { - return err - } - w, err := writer.CreatePart(part.Header) - if err != nil { - return err - } - _, err = io.Copy(w, part) - if err != nil { - return err - } - if err = part.Close(); err != nil { - return err - } - } - }), nil -} - -func (s StrictServer) MultipartRelatedExample(ctx context.Context, request MultipartRelatedExampleRequestObject) (MultipartRelatedExampleResponseObject, error) { - return MultipartRelatedExample200MultipartResponse(func(writer *multipart.Writer) error { - for { - part, err := request.Body.NextPart() - if err == io.EOF { - return nil - } else if err != nil { - return err - } - w, err := writer.CreatePart(part.Header) - if err != nil { - return err - } - _, err = io.Copy(w, part) - if err != nil { - return err - } - if err = part.Close(); err != nil { - return err - } - } - }), nil -} - -func (s StrictServer) MultipleRequestAndResponseTypes(ctx context.Context, request MultipleRequestAndResponseTypesRequestObject) (MultipleRequestAndResponseTypesResponseObject, error) { - switch { - case request.Body != nil: - return MultipleRequestAndResponseTypes200ImagepngResponse{Body: request.Body}, nil - case request.JSONBody != nil: - return MultipleRequestAndResponseTypes200JSONResponse(*request.JSONBody), nil - case request.FormdataBody != nil: - return MultipleRequestAndResponseTypes200FormdataResponse(*request.FormdataBody), nil - case request.TextBody != nil: - return MultipleRequestAndResponseTypes200TextResponse(*request.TextBody), nil - case request.MultipartBody != nil: - return MultipleRequestAndResponseTypes200MultipartResponse(func(writer *multipart.Writer) error { - for { - part, err := request.MultipartBody.NextPart() - if err == io.EOF { - return nil - } else if err != nil { - return err - } - w, err := writer.CreatePart(part.Header) - if err != nil { - return err - } - _, err = io.Copy(w, part) - if err != nil { - return err - } - if err = part.Close(); err != nil { - return err - } - } - }), nil - default: - return MultipleRequestAndResponseTypes400Response{}, nil - } -} - -func (s StrictServer) TextExample(ctx context.Context, request TextExampleRequestObject) (TextExampleResponseObject, error) { - return TextExample200TextResponse(*request.Body), nil -} - -func (s StrictServer) UnknownExample(ctx context.Context, request UnknownExampleRequestObject) (UnknownExampleResponseObject, error) { - return UnknownExample200Videomp4Response{Body: request.Body}, nil -} - -func (s StrictServer) UnspecifiedContentType(ctx context.Context, request UnspecifiedContentTypeRequestObject) (UnspecifiedContentTypeResponseObject, error) { - return UnspecifiedContentType200VideoResponse{Body: request.Body, ContentType: request.ContentType}, nil -} - -func (s StrictServer) URLEncodedExample(ctx context.Context, request URLEncodedExampleRequestObject) (URLEncodedExampleResponseObject, error) { - return URLEncodedExample200FormdataResponse(*request.Body), nil -} - -func (s StrictServer) HeadersExample(ctx context.Context, request HeadersExampleRequestObject) (HeadersExampleResponseObject, error) { - return HeadersExample200JSONResponse{Body: *request.Body, Headers: HeadersExample200ResponseHeaders{Header1: request.Params.Header1, Header2: *request.Params.Header2}}, nil -} - -func (s StrictServer) ReusableResponses(ctx context.Context, request ReusableResponsesRequestObject) (ReusableResponsesResponseObject, error) { - return ReusableResponses200JSONResponse{ReusableresponseJSONResponse: ReusableresponseJSONResponse{Body: *request.Body}}, nil -} - -func (s StrictServer) RequiredJSONBody(ctx context.Context, request RequiredJSONBodyRequestObject) (RequiredJSONBodyResponseObject, error) { - return RequiredJSONBody200JSONResponse(*request.Body), nil -} - -func (s StrictServer) RequiredTextBody(ctx context.Context, request RequiredTextBodyRequestObject) (RequiredTextBodyResponseObject, error) { - return RequiredTextBody200TextResponse(*request.Body), nil -} - -func (s StrictServer) ReservedGoKeywordParameters(ctx context.Context, request ReservedGoKeywordParametersRequestObject) (ReservedGoKeywordParametersResponseObject, error) { - return ReservedGoKeywordParameters200TextResponse(""), nil -} - -func (s StrictServer) UnionExample(ctx context.Context, request UnionExampleRequestObject) (UnionExampleResponseObject, error) { - union, err := json.Marshal(*request.Body) - if err != nil { - return nil, err - } - - return UnionExample200JSONResponse{ - Body: struct{ union json.RawMessage }{ - union: union, - }, - }, nil -} diff --git a/internal/test/strict-server/gin/types.cfg.yaml b/internal/test/strict-server/gin/types.cfg.yaml deleted file mode 100644 index 2ed9740ea7..0000000000 --- a/internal/test/strict-server/gin/types.cfg.yaml +++ /dev/null @@ -1,5 +0,0 @@ -# yaml-language-server: $schema=../../../../configuration-schema.json -package: api -generate: - models: true -output: types.gen.go diff --git a/internal/test/strict-server/gin/types.gen.go b/internal/test/strict-server/gin/types.gen.go deleted file mode 100644 index fac014c4bb..0000000000 --- a/internal/test/strict-server/gin/types.gen.go +++ /dev/null @@ -1,69 +0,0 @@ -// Package api provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package api - -// Example defines model for example. -type Example struct { - Value *string `json:"value,omitempty"` -} - -// Reusableresponse defines model for reusableresponse. -type Reusableresponse = Example - -// MultipleRequestAndResponseTypesTextBody defines parameters for MultipleRequestAndResponseTypes. -type MultipleRequestAndResponseTypesTextBody = string - -// RequiredTextBodyTextBody defines parameters for RequiredTextBody. -type RequiredTextBodyTextBody = string - -// TextExampleTextBody defines parameters for TextExample. -type TextExampleTextBody = string - -// HeadersExampleParams defines parameters for HeadersExample. -type HeadersExampleParams struct { - Header1 string `json:"header1"` - Header2 *int `json:"header2,omitempty"` -} - -// JSONExampleJSONRequestBody defines body for JSONExample for application/json ContentType. -type JSONExampleJSONRequestBody = Example - -// MultipartExampleMultipartRequestBody defines body for MultipartExample for multipart/form-data ContentType. -type MultipartExampleMultipartRequestBody = Example - -// MultipartRelatedExampleMultipartRequestBody defines body for MultipartRelatedExample for multipart/related ContentType. -type MultipartRelatedExampleMultipartRequestBody = Example - -// MultipleRequestAndResponseTypesJSONRequestBody defines body for MultipleRequestAndResponseTypes for application/json ContentType. -type MultipleRequestAndResponseTypesJSONRequestBody = Example - -// MultipleRequestAndResponseTypesFormdataRequestBody defines body for MultipleRequestAndResponseTypes for application/x-www-form-urlencoded ContentType. -type MultipleRequestAndResponseTypesFormdataRequestBody = Example - -// MultipleRequestAndResponseTypesMultipartRequestBody defines body for MultipleRequestAndResponseTypes for multipart/form-data ContentType. -type MultipleRequestAndResponseTypesMultipartRequestBody = Example - -// MultipleRequestAndResponseTypesTextRequestBody defines body for MultipleRequestAndResponseTypes for text/plain ContentType. -type MultipleRequestAndResponseTypesTextRequestBody = MultipleRequestAndResponseTypesTextBody - -// RequiredJSONBodyJSONRequestBody defines body for RequiredJSONBody for application/json ContentType. -type RequiredJSONBodyJSONRequestBody = Example - -// RequiredTextBodyTextRequestBody defines body for RequiredTextBody for text/plain ContentType. -type RequiredTextBodyTextRequestBody = RequiredTextBodyTextBody - -// ReusableResponsesJSONRequestBody defines body for ReusableResponses for application/json ContentType. -type ReusableResponsesJSONRequestBody = Example - -// TextExampleTextRequestBody defines body for TextExample for text/plain ContentType. -type TextExampleTextRequestBody = TextExampleTextBody - -// URLEncodedExampleFormdataRequestBody defines body for URLEncodedExample for application/x-www-form-urlencoded ContentType. -type URLEncodedExampleFormdataRequestBody = Example - -// HeadersExampleJSONRequestBody defines body for HeadersExample for application/json ContentType. -type HeadersExampleJSONRequestBody = Example - -// UnionExampleJSONRequestBody defines body for UnionExample for application/json ContentType. -type UnionExampleJSONRequestBody = Example diff --git a/internal/test/strict-server/gorilla/server.cfg.yaml b/internal/test/strict-server/gorilla/server.cfg.yaml deleted file mode 100644 index a39491cbef..0000000000 --- a/internal/test/strict-server/gorilla/server.cfg.yaml +++ /dev/null @@ -1,7 +0,0 @@ -# yaml-language-server: $schema=../../../../configuration-schema.json -package: api -generate: - gorilla-server: true - strict-server: true - embedded-spec: true -output: server.gen.go diff --git a/internal/test/strict-server/gorilla/server.gen.go b/internal/test/strict-server/gorilla/server.gen.go deleted file mode 100644 index a141223fc5..0000000000 --- a/internal/test/strict-server/gorilla/server.gen.go +++ /dev/null @@ -1,1735 +0,0 @@ -// Package api provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package api - -import ( - "bytes" - "compress/gzip" - "context" - "encoding/base64" - "encoding/json" - "errors" - "fmt" - "io" - "mime" - "mime/multipart" - "net/http" - "net/url" - "path" - "strings" - - "github.com/getkin/kin-openapi/openapi3" - "github.com/gorilla/mux" - "github.com/oapi-codegen/runtime" - strictnethttp "github.com/oapi-codegen/runtime/strictmiddleware/nethttp" -) - -// ServerInterface represents all server handlers. -type ServerInterface interface { - - // (POST /json) - JSONExample(w http.ResponseWriter, r *http.Request) - - // (POST /multipart) - MultipartExample(w http.ResponseWriter, r *http.Request) - - // (POST /multipart-related) - MultipartRelatedExample(w http.ResponseWriter, r *http.Request) - - // (POST /multiple) - MultipleRequestAndResponseTypes(w http.ResponseWriter, r *http.Request) - - // (POST /required-json-body) - RequiredJSONBody(w http.ResponseWriter, r *http.Request) - - // (POST /required-text-body) - RequiredTextBody(w http.ResponseWriter, r *http.Request) - - // (GET /reserved-go-keyword-parameters/{type}) - ReservedGoKeywordParameters(w http.ResponseWriter, r *http.Request, pType string) - - // (POST /reusable-responses) - ReusableResponses(w http.ResponseWriter, r *http.Request) - - // (POST /text) - TextExample(w http.ResponseWriter, r *http.Request) - - // (POST /unknown) - UnknownExample(w http.ResponseWriter, r *http.Request) - - // (POST /unspecified-content-type) - UnspecifiedContentType(w http.ResponseWriter, r *http.Request) - - // (POST /urlencoded) - URLEncodedExample(w http.ResponseWriter, r *http.Request) - - // (POST /with-headers) - HeadersExample(w http.ResponseWriter, r *http.Request, params HeadersExampleParams) - - // (POST /with-union) - UnionExample(w http.ResponseWriter, r *http.Request) -} - -// ServerInterfaceWrapper converts contexts to parameters. -type ServerInterfaceWrapper struct { - Handler ServerInterface - HandlerMiddlewares []MiddlewareFunc - ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) -} - -type MiddlewareFunc func(http.Handler) http.Handler - -// JSONExample operation middleware -func (siw *ServerInterfaceWrapper) JSONExample(w http.ResponseWriter, r *http.Request) { - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.JSONExample(w, r) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -// MultipartExample operation middleware -func (siw *ServerInterfaceWrapper) MultipartExample(w http.ResponseWriter, r *http.Request) { - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.MultipartExample(w, r) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -// MultipartRelatedExample operation middleware -func (siw *ServerInterfaceWrapper) MultipartRelatedExample(w http.ResponseWriter, r *http.Request) { - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.MultipartRelatedExample(w, r) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -// MultipleRequestAndResponseTypes operation middleware -func (siw *ServerInterfaceWrapper) MultipleRequestAndResponseTypes(w http.ResponseWriter, r *http.Request) { - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.MultipleRequestAndResponseTypes(w, r) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -// RequiredJSONBody operation middleware -func (siw *ServerInterfaceWrapper) RequiredJSONBody(w http.ResponseWriter, r *http.Request) { - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.RequiredJSONBody(w, r) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -// RequiredTextBody operation middleware -func (siw *ServerInterfaceWrapper) RequiredTextBody(w http.ResponseWriter, r *http.Request) { - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.RequiredTextBody(w, r) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -// ReservedGoKeywordParameters operation middleware -func (siw *ServerInterfaceWrapper) ReservedGoKeywordParameters(w http.ResponseWriter, r *http.Request) { - - var err error - - // ------------- Path parameter "type" ------------- - var pType string - - err = runtime.BindStyledParameterWithOptions("simple", "type", mux.Vars(r)["type"], &pType, runtime.BindStyledParameterOptions{Explode: false, Required: true, Type: "string", Format: ""}) - if err != nil { - siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "type", Err: err}) - return - } - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.ReservedGoKeywordParameters(w, r, pType) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -// ReusableResponses operation middleware -func (siw *ServerInterfaceWrapper) ReusableResponses(w http.ResponseWriter, r *http.Request) { - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.ReusableResponses(w, r) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -// TextExample operation middleware -func (siw *ServerInterfaceWrapper) TextExample(w http.ResponseWriter, r *http.Request) { - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.TextExample(w, r) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -// UnknownExample operation middleware -func (siw *ServerInterfaceWrapper) UnknownExample(w http.ResponseWriter, r *http.Request) { - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.UnknownExample(w, r) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -// UnspecifiedContentType operation middleware -func (siw *ServerInterfaceWrapper) UnspecifiedContentType(w http.ResponseWriter, r *http.Request) { - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.UnspecifiedContentType(w, r) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -// URLEncodedExample operation middleware -func (siw *ServerInterfaceWrapper) URLEncodedExample(w http.ResponseWriter, r *http.Request) { - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.URLEncodedExample(w, r) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -// HeadersExample operation middleware -func (siw *ServerInterfaceWrapper) HeadersExample(w http.ResponseWriter, r *http.Request) { - - var err error - - // Parameter object where we will unmarshal all parameters from the context - var params HeadersExampleParams - - headers := r.Header - - // ------------- Required header parameter "header1" ------------- - if valueList, found := headers[http.CanonicalHeaderKey("header1")]; found { - var Header1 string - n := len(valueList) - if n != 1 { - siw.ErrorHandlerFunc(w, r, &TooManyValuesForParamError{ParamName: "header1", Count: n}) - return - } - - err = runtime.BindStyledParameterWithOptions("simple", "header1", valueList[0], &Header1, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: true, Type: "string", Format: ""}) - if err != nil { - siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "header1", Err: err}) - return - } - - params.Header1 = Header1 - - } else { - err = fmt.Errorf("Header parameter header1 is required, but not found") - siw.ErrorHandlerFunc(w, r, &RequiredHeaderError{ParamName: "header1", Err: err}) - return - } - - // ------------- Optional header parameter "header2" ------------- - if valueList, found := headers[http.CanonicalHeaderKey("header2")]; found { - var Header2 int - n := len(valueList) - if n != 1 { - siw.ErrorHandlerFunc(w, r, &TooManyValuesForParamError{ParamName: "header2", Count: n}) - return - } - - err = runtime.BindStyledParameterWithOptions("simple", "header2", valueList[0], &Header2, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: ""}) - if err != nil { - siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "header2", Err: err}) - return - } - - params.Header2 = &Header2 - - } - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.HeadersExample(w, r, params) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -// UnionExample operation middleware -func (siw *ServerInterfaceWrapper) UnionExample(w http.ResponseWriter, r *http.Request) { - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.UnionExample(w, r) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -type UnescapedCookieParamError struct { - ParamName string - Err error -} - -func (e *UnescapedCookieParamError) Error() string { - return fmt.Sprintf("error unescaping cookie parameter '%s'", e.ParamName) -} - -func (e *UnescapedCookieParamError) Unwrap() error { - return e.Err -} - -type UnmarshalingParamError struct { - ParamName string - Err error -} - -func (e *UnmarshalingParamError) Error() string { - return fmt.Sprintf("Error unmarshaling parameter %s as JSON: %s", e.ParamName, e.Err.Error()) -} - -func (e *UnmarshalingParamError) Unwrap() error { - return e.Err -} - -type RequiredParamError struct { - ParamName string -} - -func (e *RequiredParamError) Error() string { - return fmt.Sprintf("Query argument %s is required, but not found", e.ParamName) -} - -type RequiredHeaderError struct { - ParamName string - Err error -} - -func (e *RequiredHeaderError) Error() string { - return fmt.Sprintf("Header parameter %s is required, but not found", e.ParamName) -} - -func (e *RequiredHeaderError) Unwrap() error { - return e.Err -} - -type InvalidParamFormatError struct { - ParamName string - Err error -} - -func (e *InvalidParamFormatError) Error() string { - return fmt.Sprintf("Invalid format for parameter %s: %s", e.ParamName, e.Err.Error()) -} - -func (e *InvalidParamFormatError) Unwrap() error { - return e.Err -} - -type TooManyValuesForParamError struct { - ParamName string - Count int -} - -func (e *TooManyValuesForParamError) Error() string { - return fmt.Sprintf("Expected one value for %s, got %d", e.ParamName, e.Count) -} - -// Handler creates http.Handler with routing matching OpenAPI spec. -func Handler(si ServerInterface) http.Handler { - return HandlerWithOptions(si, GorillaServerOptions{}) -} - -type GorillaServerOptions struct { - BaseURL string - BaseRouter *mux.Router - Middlewares []MiddlewareFunc - ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) -} - -// HandlerFromMux creates http.Handler with routing matching OpenAPI spec based on the provided mux. -func HandlerFromMux(si ServerInterface, r *mux.Router) http.Handler { - return HandlerWithOptions(si, GorillaServerOptions{ - BaseRouter: r, - }) -} - -func HandlerFromMuxWithBaseURL(si ServerInterface, r *mux.Router, baseURL string) http.Handler { - return HandlerWithOptions(si, GorillaServerOptions{ - BaseURL: baseURL, - BaseRouter: r, - }) -} - -// HandlerWithOptions creates http.Handler with additional options -func HandlerWithOptions(si ServerInterface, options GorillaServerOptions) http.Handler { - r := options.BaseRouter - - if r == nil { - r = mux.NewRouter() - } - if options.ErrorHandlerFunc == nil { - options.ErrorHandlerFunc = func(w http.ResponseWriter, r *http.Request, err error) { - http.Error(w, err.Error(), http.StatusBadRequest) - } - } - wrapper := ServerInterfaceWrapper{ - Handler: si, - HandlerMiddlewares: options.Middlewares, - ErrorHandlerFunc: options.ErrorHandlerFunc, - } - - r.HandleFunc(options.BaseURL+"/json", wrapper.JSONExample).Methods("POST") - - r.HandleFunc(options.BaseURL+"/multipart", wrapper.MultipartExample).Methods("POST") - - r.HandleFunc(options.BaseURL+"/multipart-related", wrapper.MultipartRelatedExample).Methods("POST") - - r.HandleFunc(options.BaseURL+"/multiple", wrapper.MultipleRequestAndResponseTypes).Methods("POST") - - r.HandleFunc(options.BaseURL+"/required-json-body", wrapper.RequiredJSONBody).Methods("POST") - - r.HandleFunc(options.BaseURL+"/required-text-body", wrapper.RequiredTextBody).Methods("POST") - - r.HandleFunc(options.BaseURL+"/reserved-go-keyword-parameters/{type}", wrapper.ReservedGoKeywordParameters).Methods("GET") - - r.HandleFunc(options.BaseURL+"/reusable-responses", wrapper.ReusableResponses).Methods("POST") - - r.HandleFunc(options.BaseURL+"/text", wrapper.TextExample).Methods("POST") - - r.HandleFunc(options.BaseURL+"/unknown", wrapper.UnknownExample).Methods("POST") - - r.HandleFunc(options.BaseURL+"/unspecified-content-type", wrapper.UnspecifiedContentType).Methods("POST") - - r.HandleFunc(options.BaseURL+"/urlencoded", wrapper.URLEncodedExample).Methods("POST") - - r.HandleFunc(options.BaseURL+"/with-headers", wrapper.HeadersExample).Methods("POST") - - r.HandleFunc(options.BaseURL+"/with-union", wrapper.UnionExample).Methods("POST") - - return r -} - -type BadrequestResponse struct { -} - -type ReusableresponseResponseHeaders struct { - Header1 string - Header2 int -} -type ReusableresponseJSONResponse struct { - Body Example - - Headers ReusableresponseResponseHeaders -} - -type JSONExampleRequestObject struct { - Body *JSONExampleJSONRequestBody -} - -type JSONExampleResponseObject interface { - VisitJSONExampleResponse(w http.ResponseWriter) error -} - -type JSONExample200JSONResponse Example - -func (response JSONExample200JSONResponse) VisitJSONExampleResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(200) - - return json.NewEncoder(w).Encode(response) -} - -type JSONExample400Response = BadrequestResponse - -func (response JSONExample400Response) VisitJSONExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type JSONExampledefaultResponse struct { - StatusCode int -} - -func (response JSONExampledefaultResponse) VisitJSONExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -type MultipartExampleRequestObject struct { - Body *multipart.Reader -} - -type MultipartExampleResponseObject interface { - VisitMultipartExampleResponse(w http.ResponseWriter) error -} - -type MultipartExample200MultipartResponse func(writer *multipart.Writer) error - -func (response MultipartExample200MultipartResponse) VisitMultipartExampleResponse(w http.ResponseWriter) error { - writer := multipart.NewWriter(w) - w.Header().Set("Content-Type", writer.FormDataContentType()) - w.WriteHeader(200) - - defer writer.Close() - return response(writer) -} - -type MultipartExample400Response = BadrequestResponse - -func (response MultipartExample400Response) VisitMultipartExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type MultipartExampledefaultResponse struct { - StatusCode int -} - -func (response MultipartExampledefaultResponse) VisitMultipartExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -type MultipartRelatedExampleRequestObject struct { - Body *multipart.Reader -} - -type MultipartRelatedExampleResponseObject interface { - VisitMultipartRelatedExampleResponse(w http.ResponseWriter) error -} - -type MultipartRelatedExample200MultipartResponse func(writer *multipart.Writer) error - -func (response MultipartRelatedExample200MultipartResponse) VisitMultipartRelatedExampleResponse(w http.ResponseWriter) error { - writer := multipart.NewWriter(w) - w.Header().Set("Content-Type", mime.FormatMediaType("multipart/related", map[string]string{"boundary": writer.Boundary()})) - w.WriteHeader(200) - - defer writer.Close() - return response(writer) -} - -type MultipartRelatedExample400Response = BadrequestResponse - -func (response MultipartRelatedExample400Response) VisitMultipartRelatedExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type MultipartRelatedExampledefaultResponse struct { - StatusCode int -} - -func (response MultipartRelatedExampledefaultResponse) VisitMultipartRelatedExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -type MultipleRequestAndResponseTypesRequestObject struct { - JSONBody *MultipleRequestAndResponseTypesJSONRequestBody - FormdataBody *MultipleRequestAndResponseTypesFormdataRequestBody - Body io.Reader - MultipartBody *multipart.Reader - TextBody *MultipleRequestAndResponseTypesTextRequestBody -} - -type MultipleRequestAndResponseTypesResponseObject interface { - VisitMultipleRequestAndResponseTypesResponse(w http.ResponseWriter) error -} - -type MultipleRequestAndResponseTypes200JSONResponse Example - -func (response MultipleRequestAndResponseTypes200JSONResponse) VisitMultipleRequestAndResponseTypesResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(200) - - return json.NewEncoder(w).Encode(response) -} - -type MultipleRequestAndResponseTypes200FormdataResponse Example - -func (response MultipleRequestAndResponseTypes200FormdataResponse) VisitMultipleRequestAndResponseTypesResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/x-www-form-urlencoded") - w.WriteHeader(200) - - if form, err := runtime.MarshalForm(response, nil); err != nil { - return err - } else { - _, err := w.Write([]byte(form.Encode())) - return err - } -} - -type MultipleRequestAndResponseTypes200ImagepngResponse struct { - Body io.Reader - ContentLength int64 -} - -func (response MultipleRequestAndResponseTypes200ImagepngResponse) VisitMultipleRequestAndResponseTypesResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "image/png") - if response.ContentLength != 0 { - w.Header().Set("Content-Length", fmt.Sprint(response.ContentLength)) - } - w.WriteHeader(200) - - if closer, ok := response.Body.(io.ReadCloser); ok { - defer closer.Close() - } - _, err := io.Copy(w, response.Body) - return err -} - -type MultipleRequestAndResponseTypes200MultipartResponse func(writer *multipart.Writer) error - -func (response MultipleRequestAndResponseTypes200MultipartResponse) VisitMultipleRequestAndResponseTypesResponse(w http.ResponseWriter) error { - writer := multipart.NewWriter(w) - w.Header().Set("Content-Type", writer.FormDataContentType()) - w.WriteHeader(200) - - defer writer.Close() - return response(writer) -} - -type MultipleRequestAndResponseTypes200TextResponse string - -func (response MultipleRequestAndResponseTypes200TextResponse) VisitMultipleRequestAndResponseTypesResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "text/plain") - w.WriteHeader(200) - - _, err := w.Write([]byte(response)) - return err -} - -type MultipleRequestAndResponseTypes400Response = BadrequestResponse - -func (response MultipleRequestAndResponseTypes400Response) VisitMultipleRequestAndResponseTypesResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type RequiredJSONBodyRequestObject struct { - Body *RequiredJSONBodyJSONRequestBody -} - -type RequiredJSONBodyResponseObject interface { - VisitRequiredJSONBodyResponse(w http.ResponseWriter) error -} - -type RequiredJSONBody200JSONResponse Example - -func (response RequiredJSONBody200JSONResponse) VisitRequiredJSONBodyResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(200) - - return json.NewEncoder(w).Encode(response) -} - -type RequiredJSONBody400Response = BadrequestResponse - -func (response RequiredJSONBody400Response) VisitRequiredJSONBodyResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type RequiredJSONBodydefaultResponse struct { - StatusCode int -} - -func (response RequiredJSONBodydefaultResponse) VisitRequiredJSONBodyResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -type RequiredTextBodyRequestObject struct { - Body *RequiredTextBodyTextRequestBody -} - -type RequiredTextBodyResponseObject interface { - VisitRequiredTextBodyResponse(w http.ResponseWriter) error -} - -type RequiredTextBody200TextResponse string - -func (response RequiredTextBody200TextResponse) VisitRequiredTextBodyResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "text/plain") - w.WriteHeader(200) - - _, err := w.Write([]byte(response)) - return err -} - -type RequiredTextBody400Response = BadrequestResponse - -func (response RequiredTextBody400Response) VisitRequiredTextBodyResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type RequiredTextBodydefaultResponse struct { - StatusCode int -} - -func (response RequiredTextBodydefaultResponse) VisitRequiredTextBodyResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -type ReservedGoKeywordParametersRequestObject struct { - Type string `json:"type"` -} - -type ReservedGoKeywordParametersResponseObject interface { - VisitReservedGoKeywordParametersResponse(w http.ResponseWriter) error -} - -type ReservedGoKeywordParameters200TextResponse string - -func (response ReservedGoKeywordParameters200TextResponse) VisitReservedGoKeywordParametersResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "text/plain") - w.WriteHeader(200) - - _, err := w.Write([]byte(response)) - return err -} - -type ReusableResponsesRequestObject struct { - Body *ReusableResponsesJSONRequestBody -} - -type ReusableResponsesResponseObject interface { - VisitReusableResponsesResponse(w http.ResponseWriter) error -} - -type ReusableResponses200JSONResponse struct{ ReusableresponseJSONResponse } - -func (response ReusableResponses200JSONResponse) VisitReusableResponsesResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/json") - w.Header().Set("header1", fmt.Sprint(response.Headers.Header1)) - w.Header().Set("header2", fmt.Sprint(response.Headers.Header2)) - w.WriteHeader(200) - - return json.NewEncoder(w).Encode(response.Body) -} - -type ReusableResponses400Response = BadrequestResponse - -func (response ReusableResponses400Response) VisitReusableResponsesResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type ReusableResponsesdefaultResponse struct { - StatusCode int -} - -func (response ReusableResponsesdefaultResponse) VisitReusableResponsesResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -type TextExampleRequestObject struct { - Body *TextExampleTextRequestBody -} - -type TextExampleResponseObject interface { - VisitTextExampleResponse(w http.ResponseWriter) error -} - -type TextExample200TextResponse string - -func (response TextExample200TextResponse) VisitTextExampleResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "text/plain") - w.WriteHeader(200) - - _, err := w.Write([]byte(response)) - return err -} - -type TextExample400Response = BadrequestResponse - -func (response TextExample400Response) VisitTextExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type TextExampledefaultResponse struct { - StatusCode int -} - -func (response TextExampledefaultResponse) VisitTextExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -type UnknownExampleRequestObject struct { - Body io.Reader -} - -type UnknownExampleResponseObject interface { - VisitUnknownExampleResponse(w http.ResponseWriter) error -} - -type UnknownExample200Videomp4Response struct { - Body io.Reader - ContentLength int64 -} - -func (response UnknownExample200Videomp4Response) VisitUnknownExampleResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "video/mp4") - if response.ContentLength != 0 { - w.Header().Set("Content-Length", fmt.Sprint(response.ContentLength)) - } - w.WriteHeader(200) - - if closer, ok := response.Body.(io.ReadCloser); ok { - defer closer.Close() - } - _, err := io.Copy(w, response.Body) - return err -} - -type UnknownExample400Response = BadrequestResponse - -func (response UnknownExample400Response) VisitUnknownExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type UnknownExampledefaultResponse struct { - StatusCode int -} - -func (response UnknownExampledefaultResponse) VisitUnknownExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -type UnspecifiedContentTypeRequestObject struct { - ContentType string - Body io.Reader -} - -type UnspecifiedContentTypeResponseObject interface { - VisitUnspecifiedContentTypeResponse(w http.ResponseWriter) error -} - -type UnspecifiedContentType200VideoResponse struct { - Body io.Reader - ContentType string - ContentLength int64 -} - -func (response UnspecifiedContentType200VideoResponse) VisitUnspecifiedContentTypeResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", response.ContentType) - if response.ContentLength != 0 { - w.Header().Set("Content-Length", fmt.Sprint(response.ContentLength)) - } - w.WriteHeader(200) - - if closer, ok := response.Body.(io.ReadCloser); ok { - defer closer.Close() - } - _, err := io.Copy(w, response.Body) - return err -} - -type UnspecifiedContentType400Response = BadrequestResponse - -func (response UnspecifiedContentType400Response) VisitUnspecifiedContentTypeResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type UnspecifiedContentType401Response struct { -} - -func (response UnspecifiedContentType401Response) VisitUnspecifiedContentTypeResponse(w http.ResponseWriter) error { - w.WriteHeader(401) - return nil -} - -type UnspecifiedContentType403Response struct { -} - -func (response UnspecifiedContentType403Response) VisitUnspecifiedContentTypeResponse(w http.ResponseWriter) error { - w.WriteHeader(403) - return nil -} - -type UnspecifiedContentTypedefaultResponse struct { - StatusCode int -} - -func (response UnspecifiedContentTypedefaultResponse) VisitUnspecifiedContentTypeResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -type URLEncodedExampleRequestObject struct { - Body *URLEncodedExampleFormdataRequestBody -} - -type URLEncodedExampleResponseObject interface { - VisitURLEncodedExampleResponse(w http.ResponseWriter) error -} - -type URLEncodedExample200FormdataResponse Example - -func (response URLEncodedExample200FormdataResponse) VisitURLEncodedExampleResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/x-www-form-urlencoded") - w.WriteHeader(200) - - if form, err := runtime.MarshalForm(response, nil); err != nil { - return err - } else { - _, err := w.Write([]byte(form.Encode())) - return err - } -} - -type URLEncodedExample400Response = BadrequestResponse - -func (response URLEncodedExample400Response) VisitURLEncodedExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type URLEncodedExampledefaultResponse struct { - StatusCode int -} - -func (response URLEncodedExampledefaultResponse) VisitURLEncodedExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -type HeadersExampleRequestObject struct { - Params HeadersExampleParams - Body *HeadersExampleJSONRequestBody -} - -type HeadersExampleResponseObject interface { - VisitHeadersExampleResponse(w http.ResponseWriter) error -} - -type HeadersExample200ResponseHeaders struct { - Header1 string - Header2 int -} - -type HeadersExample200JSONResponse struct { - Body Example - Headers HeadersExample200ResponseHeaders -} - -func (response HeadersExample200JSONResponse) VisitHeadersExampleResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/json") - w.Header().Set("header1", fmt.Sprint(response.Headers.Header1)) - w.Header().Set("header2", fmt.Sprint(response.Headers.Header2)) - w.WriteHeader(200) - - return json.NewEncoder(w).Encode(response.Body) -} - -type HeadersExample400Response = BadrequestResponse - -func (response HeadersExample400Response) VisitHeadersExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type HeadersExampledefaultResponse struct { - StatusCode int -} - -func (response HeadersExampledefaultResponse) VisitHeadersExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -type UnionExampleRequestObject struct { - Body *UnionExampleJSONRequestBody -} - -type UnionExampleResponseObject interface { - VisitUnionExampleResponse(w http.ResponseWriter) error -} - -type UnionExample200ResponseHeaders struct { - Header1 string - Header2 int -} - -type UnionExample200ApplicationAlternativePlusJSONResponse struct { - Body Example - Headers UnionExample200ResponseHeaders -} - -func (response UnionExample200ApplicationAlternativePlusJSONResponse) VisitUnionExampleResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/alternative+json") - w.Header().Set("header1", fmt.Sprint(response.Headers.Header1)) - w.Header().Set("header2", fmt.Sprint(response.Headers.Header2)) - w.WriteHeader(200) - - return json.NewEncoder(w).Encode(response.Body) -} - -type UnionExample200JSONResponse struct { - Body struct { - union json.RawMessage - } - Headers UnionExample200ResponseHeaders -} - -func (response UnionExample200JSONResponse) VisitUnionExampleResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/json") - w.Header().Set("header1", fmt.Sprint(response.Headers.Header1)) - w.Header().Set("header2", fmt.Sprint(response.Headers.Header2)) - w.WriteHeader(200) - - return json.NewEncoder(w).Encode(response.Body.union) -} - -type UnionExample400Response = BadrequestResponse - -func (response UnionExample400Response) VisitUnionExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type UnionExampledefaultResponse struct { - StatusCode int -} - -func (response UnionExampledefaultResponse) VisitUnionExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -// StrictServerInterface represents all server handlers. -type StrictServerInterface interface { - - // (POST /json) - JSONExample(ctx context.Context, request JSONExampleRequestObject) (JSONExampleResponseObject, error) - - // (POST /multipart) - MultipartExample(ctx context.Context, request MultipartExampleRequestObject) (MultipartExampleResponseObject, error) - - // (POST /multipart-related) - MultipartRelatedExample(ctx context.Context, request MultipartRelatedExampleRequestObject) (MultipartRelatedExampleResponseObject, error) - - // (POST /multiple) - MultipleRequestAndResponseTypes(ctx context.Context, request MultipleRequestAndResponseTypesRequestObject) (MultipleRequestAndResponseTypesResponseObject, error) - - // (POST /required-json-body) - RequiredJSONBody(ctx context.Context, request RequiredJSONBodyRequestObject) (RequiredJSONBodyResponseObject, error) - - // (POST /required-text-body) - RequiredTextBody(ctx context.Context, request RequiredTextBodyRequestObject) (RequiredTextBodyResponseObject, error) - - // (GET /reserved-go-keyword-parameters/{type}) - ReservedGoKeywordParameters(ctx context.Context, request ReservedGoKeywordParametersRequestObject) (ReservedGoKeywordParametersResponseObject, error) - - // (POST /reusable-responses) - ReusableResponses(ctx context.Context, request ReusableResponsesRequestObject) (ReusableResponsesResponseObject, error) - - // (POST /text) - TextExample(ctx context.Context, request TextExampleRequestObject) (TextExampleResponseObject, error) - - // (POST /unknown) - UnknownExample(ctx context.Context, request UnknownExampleRequestObject) (UnknownExampleResponseObject, error) - - // (POST /unspecified-content-type) - UnspecifiedContentType(ctx context.Context, request UnspecifiedContentTypeRequestObject) (UnspecifiedContentTypeResponseObject, error) - - // (POST /urlencoded) - URLEncodedExample(ctx context.Context, request URLEncodedExampleRequestObject) (URLEncodedExampleResponseObject, error) - - // (POST /with-headers) - HeadersExample(ctx context.Context, request HeadersExampleRequestObject) (HeadersExampleResponseObject, error) - - // (POST /with-union) - UnionExample(ctx context.Context, request UnionExampleRequestObject) (UnionExampleResponseObject, error) -} - -type StrictHandlerFunc = strictnethttp.StrictHTTPHandlerFunc -type StrictMiddlewareFunc = strictnethttp.StrictHTTPMiddlewareFunc - -type StrictHTTPServerOptions struct { - RequestErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) - ResponseErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) -} - -func NewStrictHandler(ssi StrictServerInterface, middlewares []StrictMiddlewareFunc) ServerInterface { - return &strictHandler{ssi: ssi, middlewares: middlewares, options: StrictHTTPServerOptions{ - RequestErrorHandlerFunc: func(w http.ResponseWriter, r *http.Request, err error) { - http.Error(w, err.Error(), http.StatusBadRequest) - }, - ResponseErrorHandlerFunc: func(w http.ResponseWriter, r *http.Request, err error) { - http.Error(w, err.Error(), http.StatusInternalServerError) - }, - }} -} - -func NewStrictHandlerWithOptions(ssi StrictServerInterface, middlewares []StrictMiddlewareFunc, options StrictHTTPServerOptions) ServerInterface { - return &strictHandler{ssi: ssi, middlewares: middlewares, options: options} -} - -type strictHandler struct { - ssi StrictServerInterface - middlewares []StrictMiddlewareFunc - options StrictHTTPServerOptions -} - -// JSONExample operation middleware -func (sh *strictHandler) JSONExample(w http.ResponseWriter, r *http.Request) { - var request JSONExampleRequestObject - - var body JSONExampleJSONRequestBody - if err := json.NewDecoder(r.Body).Decode(&body); err != nil { - if !errors.Is(err, io.EOF) { - sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't decode JSON body: %w", err)) - return - } - } else { - request.Body = &body - } - - handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { - return sh.ssi.JSONExample(ctx, request.(JSONExampleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "JSONExample") - } - - response, err := handler(r.Context(), w, r, request) - - if err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } else if validResponse, ok := response.(JSONExampleResponseObject); ok { - if err := validResponse.VisitJSONExampleResponse(w); err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } - } else if response != nil { - sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) - } -} - -// MultipartExample operation middleware -func (sh *strictHandler) MultipartExample(w http.ResponseWriter, r *http.Request) { - var request MultipartExampleRequestObject - - if reader, err := r.MultipartReader(); err != nil { - sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't decode multipart body: %w", err)) - return - } else { - request.Body = reader - } - - handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { - return sh.ssi.MultipartExample(ctx, request.(MultipartExampleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "MultipartExample") - } - - response, err := handler(r.Context(), w, r, request) - - if err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } else if validResponse, ok := response.(MultipartExampleResponseObject); ok { - if err := validResponse.VisitMultipartExampleResponse(w); err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } - } else if response != nil { - sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) - } -} - -// MultipartRelatedExample operation middleware -func (sh *strictHandler) MultipartRelatedExample(w http.ResponseWriter, r *http.Request) { - var request MultipartRelatedExampleRequestObject - - if _, params, err := mime.ParseMediaType(r.Header.Get("Content-Type")); err != nil { - sh.options.RequestErrorHandlerFunc(w, r, err) - return - } else if boundary := params["boundary"]; boundary == "" { - sh.options.RequestErrorHandlerFunc(w, r, http.ErrMissingBoundary) - return - } else { - request.Body = multipart.NewReader(r.Body, boundary) - } - - handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { - return sh.ssi.MultipartRelatedExample(ctx, request.(MultipartRelatedExampleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "MultipartRelatedExample") - } - - response, err := handler(r.Context(), w, r, request) - - if err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } else if validResponse, ok := response.(MultipartRelatedExampleResponseObject); ok { - if err := validResponse.VisitMultipartRelatedExampleResponse(w); err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } - } else if response != nil { - sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) - } -} - -// MultipleRequestAndResponseTypes operation middleware -func (sh *strictHandler) MultipleRequestAndResponseTypes(w http.ResponseWriter, r *http.Request) { - var request MultipleRequestAndResponseTypesRequestObject - - if strings.HasPrefix(r.Header.Get("Content-Type"), "application/json") { - - var body MultipleRequestAndResponseTypesJSONRequestBody - if err := json.NewDecoder(r.Body).Decode(&body); err != nil { - if !errors.Is(err, io.EOF) { - sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't decode JSON body: %w", err)) - return - } - } else { - request.JSONBody = &body - } - } - if strings.HasPrefix(r.Header.Get("Content-Type"), "application/x-www-form-urlencoded") { - if err := r.ParseForm(); err != nil { - sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't decode formdata: %w", err)) - return - } - var body MultipleRequestAndResponseTypesFormdataRequestBody - if err := runtime.BindForm(&body, r.Form, nil, nil); err != nil { - sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't bind formdata: %w", err)) - return - } - request.FormdataBody = &body - } - if strings.HasPrefix(r.Header.Get("Content-Type"), "image/png") { - request.Body = r.Body - } - if strings.HasPrefix(r.Header.Get("Content-Type"), "multipart/form-data") { - if reader, err := r.MultipartReader(); err != nil { - sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't decode multipart body: %w", err)) - return - } else { - request.MultipartBody = reader - } - } - if strings.HasPrefix(r.Header.Get("Content-Type"), "text/plain") { - data, err := io.ReadAll(r.Body) - if err != nil { - sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't read body: %w", err)) - return - } - if len(data) > 0 { - body := MultipleRequestAndResponseTypesTextRequestBody(data) - request.TextBody = &body - } - } - - handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { - return sh.ssi.MultipleRequestAndResponseTypes(ctx, request.(MultipleRequestAndResponseTypesRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "MultipleRequestAndResponseTypes") - } - - response, err := handler(r.Context(), w, r, request) - - if err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } else if validResponse, ok := response.(MultipleRequestAndResponseTypesResponseObject); ok { - if err := validResponse.VisitMultipleRequestAndResponseTypesResponse(w); err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } - } else if response != nil { - sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) - } -} - -// RequiredJSONBody operation middleware -func (sh *strictHandler) RequiredJSONBody(w http.ResponseWriter, r *http.Request) { - var request RequiredJSONBodyRequestObject - - var body RequiredJSONBodyJSONRequestBody - if err := json.NewDecoder(r.Body).Decode(&body); err != nil { - sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't decode JSON body: %w", err)) - return - } - request.Body = &body - - handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { - return sh.ssi.RequiredJSONBody(ctx, request.(RequiredJSONBodyRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "RequiredJSONBody") - } - - response, err := handler(r.Context(), w, r, request) - - if err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } else if validResponse, ok := response.(RequiredJSONBodyResponseObject); ok { - if err := validResponse.VisitRequiredJSONBodyResponse(w); err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } - } else if response != nil { - sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) - } -} - -// RequiredTextBody operation middleware -func (sh *strictHandler) RequiredTextBody(w http.ResponseWriter, r *http.Request) { - var request RequiredTextBodyRequestObject - - data, err := io.ReadAll(r.Body) - if err != nil { - sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't read body: %w", err)) - return - } - body := RequiredTextBodyTextRequestBody(data) - request.Body = &body - - handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { - return sh.ssi.RequiredTextBody(ctx, request.(RequiredTextBodyRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "RequiredTextBody") - } - - response, err := handler(r.Context(), w, r, request) - - if err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } else if validResponse, ok := response.(RequiredTextBodyResponseObject); ok { - if err := validResponse.VisitRequiredTextBodyResponse(w); err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } - } else if response != nil { - sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) - } -} - -// ReservedGoKeywordParameters operation middleware -func (sh *strictHandler) ReservedGoKeywordParameters(w http.ResponseWriter, r *http.Request, pType string) { - var request ReservedGoKeywordParametersRequestObject - - request.Type = pType - - handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { - return sh.ssi.ReservedGoKeywordParameters(ctx, request.(ReservedGoKeywordParametersRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "ReservedGoKeywordParameters") - } - - response, err := handler(r.Context(), w, r, request) - - if err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } else if validResponse, ok := response.(ReservedGoKeywordParametersResponseObject); ok { - if err := validResponse.VisitReservedGoKeywordParametersResponse(w); err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } - } else if response != nil { - sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) - } -} - -// ReusableResponses operation middleware -func (sh *strictHandler) ReusableResponses(w http.ResponseWriter, r *http.Request) { - var request ReusableResponsesRequestObject - - var body ReusableResponsesJSONRequestBody - if err := json.NewDecoder(r.Body).Decode(&body); err != nil { - if !errors.Is(err, io.EOF) { - sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't decode JSON body: %w", err)) - return - } - } else { - request.Body = &body - } - - handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { - return sh.ssi.ReusableResponses(ctx, request.(ReusableResponsesRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "ReusableResponses") - } - - response, err := handler(r.Context(), w, r, request) - - if err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } else if validResponse, ok := response.(ReusableResponsesResponseObject); ok { - if err := validResponse.VisitReusableResponsesResponse(w); err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } - } else if response != nil { - sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) - } -} - -// TextExample operation middleware -func (sh *strictHandler) TextExample(w http.ResponseWriter, r *http.Request) { - var request TextExampleRequestObject - - data, err := io.ReadAll(r.Body) - if err != nil { - sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't read body: %w", err)) - return - } - if len(data) > 0 { - body := TextExampleTextRequestBody(data) - request.Body = &body - } - - handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { - return sh.ssi.TextExample(ctx, request.(TextExampleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "TextExample") - } - - response, err := handler(r.Context(), w, r, request) - - if err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } else if validResponse, ok := response.(TextExampleResponseObject); ok { - if err := validResponse.VisitTextExampleResponse(w); err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } - } else if response != nil { - sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) - } -} - -// UnknownExample operation middleware -func (sh *strictHandler) UnknownExample(w http.ResponseWriter, r *http.Request) { - var request UnknownExampleRequestObject - - request.Body = r.Body - - handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { - return sh.ssi.UnknownExample(ctx, request.(UnknownExampleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "UnknownExample") - } - - response, err := handler(r.Context(), w, r, request) - - if err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } else if validResponse, ok := response.(UnknownExampleResponseObject); ok { - if err := validResponse.VisitUnknownExampleResponse(w); err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } - } else if response != nil { - sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) - } -} - -// UnspecifiedContentType operation middleware -func (sh *strictHandler) UnspecifiedContentType(w http.ResponseWriter, r *http.Request) { - var request UnspecifiedContentTypeRequestObject - - request.ContentType = r.Header.Get("Content-Type") - - request.Body = r.Body - - handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { - return sh.ssi.UnspecifiedContentType(ctx, request.(UnspecifiedContentTypeRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "UnspecifiedContentType") - } - - response, err := handler(r.Context(), w, r, request) - - if err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } else if validResponse, ok := response.(UnspecifiedContentTypeResponseObject); ok { - if err := validResponse.VisitUnspecifiedContentTypeResponse(w); err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } - } else if response != nil { - sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) - } -} - -// URLEncodedExample operation middleware -func (sh *strictHandler) URLEncodedExample(w http.ResponseWriter, r *http.Request) { - var request URLEncodedExampleRequestObject - - if err := r.ParseForm(); err != nil { - sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't decode formdata: %w", err)) - return - } - var body URLEncodedExampleFormdataRequestBody - if err := runtime.BindForm(&body, r.Form, nil, nil); err != nil { - sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't bind formdata: %w", err)) - return - } - request.Body = &body - - handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { - return sh.ssi.URLEncodedExample(ctx, request.(URLEncodedExampleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "URLEncodedExample") - } - - response, err := handler(r.Context(), w, r, request) - - if err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } else if validResponse, ok := response.(URLEncodedExampleResponseObject); ok { - if err := validResponse.VisitURLEncodedExampleResponse(w); err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } - } else if response != nil { - sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) - } -} - -// HeadersExample operation middleware -func (sh *strictHandler) HeadersExample(w http.ResponseWriter, r *http.Request, params HeadersExampleParams) { - var request HeadersExampleRequestObject - - request.Params = params - - var body HeadersExampleJSONRequestBody - if err := json.NewDecoder(r.Body).Decode(&body); err != nil { - if !errors.Is(err, io.EOF) { - sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't decode JSON body: %w", err)) - return - } - } else { - request.Body = &body - } - - handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { - return sh.ssi.HeadersExample(ctx, request.(HeadersExampleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "HeadersExample") - } - - response, err := handler(r.Context(), w, r, request) - - if err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } else if validResponse, ok := response.(HeadersExampleResponseObject); ok { - if err := validResponse.VisitHeadersExampleResponse(w); err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } - } else if response != nil { - sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) - } -} - -// UnionExample operation middleware -func (sh *strictHandler) UnionExample(w http.ResponseWriter, r *http.Request) { - var request UnionExampleRequestObject - - var body UnionExampleJSONRequestBody - if err := json.NewDecoder(r.Body).Decode(&body); err != nil { - if !errors.Is(err, io.EOF) { - sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't decode JSON body: %w", err)) - return - } - } else { - request.Body = &body - } - - handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { - return sh.ssi.UnionExample(ctx, request.(UnionExampleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "UnionExample") - } - - response, err := handler(r.Context(), w, r, request) - - if err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } else if validResponse, ok := response.(UnionExampleResponseObject); ok { - if err := validResponse.VisitUnionExampleResponse(w); err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } - } else if response != nil { - sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) - } -} - -// Base64 encoded, gzipped, json marshaled Swagger object -var swaggerSpec = []string{ - - "H4sIAAAAAAAC/+xZTXPbNhP+Kzt431NKmrbjE2+NJ5O2aeuObJ86PkDESkJCAiiwFK3R6L93QEBfFq1K", - "qT4ynt5Ecr/wPLuLBTRlha6MVqjIsXzKLDqjlcP2oc+Fxb9qdOSfBLrCSkNSK5azD1z04rdZwizWjvdL", - "nKt7+UIrQtWqcmNKWXCvmn1xXn/KXDHCivtf/7c4YDn7X7YMJQtfXYbPvDIlstlslryI4O4zS9gIuUDb", - "Rht+Xq3bpolBljNHVqoh80aC2HWnmFSEQ7TemxeNQXiBeRz5lBmrDVqSAaMxL2vs9hTf6P4XLCisQKqB", - "3sTyViviUjkQcjBAi4ogggfehgNXG6MtoYD+BLyHgsChHaNlCSNJPjB2v/oeYsCOJWyM1gVHVxeXF5ee", - "L21QcSNZzt63rxJmOI3aBS0IMrqL91/u734H6YDXpCtOsuBlOYGKWzfiJQqQirQPsS7IXbDWk22J/1lE", - "7Y8RSp81bQJ90GJyjIRp83Ilna8vL0+Ul7OE3QRnXTYWQWUrBdaaGfC67MD8UX1VulGA1mobV5ZVdUnS", - "cEurXK2j/dtcZBfIF/aygbZVKjjxI6F+KE/nBj61WHJCsQMBvSC5Hw8r5o/Kwr/xc1YOYj/u7FP3I904", - "GOkGSINAXkIjaQRzxRcNVirg4KQalgjzoJJOMkuM296PSvTiWh68jaP3s2TNynPaNE3aFlBtS1SFFt9G", - "YcJkxYeYGTVcV/e2ObGc9SfkU3ZzgztQISeM8JkyU3Kptu/eJ2rp/yF9sMIO5eofpUWRekbSfqyP7sKN", - "5QVeyg8ac90EnIZKOl+l4aMb6boUwMuGT1zoD5sTRy+q+8mjLcyjjx3BgffJcrI1vu0xZEGtz6zzUPuA", - "z/SP1O6R+PvSd+qa2p+i9kwg0qFOv+Kk0VakhlteIaF12dTHOfO2hthh8o+FJBRcQR9B8QoF8AGhhU8a", - "oknXwU/w+0l/DiJLU+2BY/GQ/zllHrz2EMIS5h2wPOD3ko5kC8BPx6VqjmY46qZrrl5L+Cgyh87iwPmB", - "pIvjDvyCp96KxHmOTNtzc+Pwf4qk9ky+Pnj7lrDLsH3AweN77wJ1ePk6ZlFrF9i+cY7ZAcWxFKizytzs", - "aflsoDqDhRxIFGlcRRpie60l3GpVWKT1A4jfDJUmWBiD/gRohBAQaPfHBqGqHYHhzoGktouUMtwVCdxo", - "Ho/LyG6Dp4dlO93G6rsjcfruXIzeXF7tr/L+yHmzdpB4pR57v34MMvvemB3sxLLneetwfs9Uzo2kUbpy", - "pdxdwj8FgeWeXqAc+4lICbBItVUoYCz5/Bp0ozajgSWtXbNQCGM5Dc2vt/cZiJKttq5Zsu0K/OkNX9Ae", - "84+DU+VpreS2i/pH/xniDP1yb5BafafX8LwktIqTHOMPh7m/2bSiFd4N2kp7wXKyo4ent5dVs4SFf45C", - "C6pt6fsEkcmzLPzjdOEaPhyivZA640Z6FP4OAAD//0nTejA+HAAA", -} - -// GetSwagger returns the content of the embedded swagger specification file -// or error if failed to decode -func decodeSpec() ([]byte, error) { - zipped, err := base64.StdEncoding.DecodeString(strings.Join(swaggerSpec, "")) - if err != nil { - return nil, fmt.Errorf("error base64 decoding spec: %w", err) - } - zr, err := gzip.NewReader(bytes.NewReader(zipped)) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - var buf bytes.Buffer - _, err = buf.ReadFrom(zr) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - - return buf.Bytes(), nil -} - -var rawSpec = decodeSpecCached() - -// a naive cached of a decoded swagger spec -func decodeSpecCached() func() ([]byte, error) { - data, err := decodeSpec() - return func() ([]byte, error) { - return data, err - } -} - -// Constructs a synthetic filesystem for resolving external references when loading openapi specifications. -func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { - res := make(map[string]func() ([]byte, error)) - if len(pathToFile) > 0 { - res[pathToFile] = rawSpec - } - - return res -} - -// GetSwagger returns the Swagger specification corresponding to the generated code -// in this file. The external references of Swagger specification are resolved. -// The logic of resolving external references is tightly connected to "import-mapping" feature. -// Externally referenced files must be embedded in the corresponding golang packages. -// Urls can be supported but this task was out of the scope. -func GetSwagger() (swagger *openapi3.T, err error) { - resolvePath := PathToRawSpec("") - - loader := openapi3.NewLoader() - loader.IsExternalRefsAllowed = true - loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() - pathToFile = path.Clean(pathToFile) - getSpec, ok := resolvePath[pathToFile] - if !ok { - err1 := fmt.Errorf("path not found: %s", pathToFile) - return nil, err1 - } - return getSpec() - } - var specData []byte - specData, err = rawSpec() - if err != nil { - return - } - swagger, err = loader.LoadFromData(specData) - if err != nil { - return - } - return -} diff --git a/internal/test/strict-server/gorilla/server.go b/internal/test/strict-server/gorilla/server.go deleted file mode 100644 index 2cb801e035..0000000000 --- a/internal/test/strict-server/gorilla/server.go +++ /dev/null @@ -1,128 +0,0 @@ -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=server.cfg.yaml ../strict-schema.yaml -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=types.cfg.yaml ../strict-schema.yaml - -package api - -import ( - "context" - "encoding/json" - "io" - "mime/multipart" -) - -type StrictServer struct { -} - -func (s StrictServer) JSONExample(ctx context.Context, request JSONExampleRequestObject) (JSONExampleResponseObject, error) { - return JSONExample200JSONResponse(*request.Body), nil -} - -func (s StrictServer) MultipartExample(ctx context.Context, request MultipartExampleRequestObject) (MultipartExampleResponseObject, error) { - return MultipartExample200MultipartResponse(func(writer *multipart.Writer) error { - for { - part, err := request.Body.NextPart() - if err == io.EOF { - return nil - } else if err != nil { - return err - } - w, err := writer.CreatePart(part.Header) - if err != nil { - return err - } - _, err = io.Copy(w, part) - if err != nil { - return err - } - if err = part.Close(); err != nil { - return err - } - } - }), nil -} - -func (s StrictServer) MultipleRequestAndResponseTypes(ctx context.Context, request MultipleRequestAndResponseTypesRequestObject) (MultipleRequestAndResponseTypesResponseObject, error) { - switch { - case request.Body != nil: - return MultipleRequestAndResponseTypes200ImagepngResponse{Body: request.Body}, nil - case request.JSONBody != nil: - return MultipleRequestAndResponseTypes200JSONResponse(*request.JSONBody), nil - case request.FormdataBody != nil: - return MultipleRequestAndResponseTypes200FormdataResponse(*request.FormdataBody), nil - case request.TextBody != nil: - return MultipleRequestAndResponseTypes200TextResponse(*request.TextBody), nil - case request.MultipartBody != nil: - return MultipleRequestAndResponseTypes200MultipartResponse(func(writer *multipart.Writer) error { - for { - part, err := request.MultipartBody.NextPart() - if err == io.EOF { - return nil - } else if err != nil { - return err - } - w, err := writer.CreatePart(part.Header) - if err != nil { - return err - } - _, err = io.Copy(w, part) - if err != nil { - return err - } - if err = part.Close(); err != nil { - return err - } - } - }), nil - default: - return MultipleRequestAndResponseTypes400Response{}, nil - } -} - -func (s StrictServer) TextExample(ctx context.Context, request TextExampleRequestObject) (TextExampleResponseObject, error) { - return TextExample200TextResponse(*request.Body), nil -} - -func (s StrictServer) UnknownExample(ctx context.Context, request UnknownExampleRequestObject) (UnknownExampleResponseObject, error) { - return UnknownExample200Videomp4Response{Body: request.Body}, nil -} - -func (s StrictServer) UnspecifiedContentType(ctx context.Context, request UnspecifiedContentTypeRequestObject) (UnspecifiedContentTypeResponseObject, error) { - return UnspecifiedContentType200VideoResponse{Body: request.Body, ContentType: request.ContentType}, nil -} - -func (s StrictServer) URLEncodedExample(ctx context.Context, request URLEncodedExampleRequestObject) (URLEncodedExampleResponseObject, error) { - return URLEncodedExample200FormdataResponse(*request.Body), nil -} - -func (s StrictServer) HeadersExample(ctx context.Context, request HeadersExampleRequestObject) (HeadersExampleResponseObject, error) { - return HeadersExample200JSONResponse{Body: *request.Body, Headers: HeadersExample200ResponseHeaders{Header1: request.Params.Header1, Header2: *request.Params.Header2}}, nil -} - -func (s StrictServer) ReusableResponses(ctx context.Context, request ReusableResponsesRequestObject) (ReusableResponsesResponseObject, error) { - return ReusableResponses200JSONResponse{ReusableresponseJSONResponse: ReusableresponseJSONResponse{Body: *request.Body}}, nil -} - -func (s StrictServer) RequiredJSONBody(ctx context.Context, request RequiredJSONBodyRequestObject) (RequiredJSONBodyResponseObject, error) { - return RequiredJSONBody200JSONResponse(*request.Body), nil -} - -func (s StrictServer) RequiredTextBody(ctx context.Context, request RequiredTextBodyRequestObject) (RequiredTextBodyResponseObject, error) { - return RequiredTextBody200TextResponse(*request.Body), nil -} - -func (s StrictServer) ReservedGoKeywordParameters(ctx context.Context, request ReservedGoKeywordParametersRequestObject) (ReservedGoKeywordParametersResponseObject, error) { - return ReservedGoKeywordParameters200TextResponse(""), nil -} - -func (s StrictServer) UnionExample(ctx context.Context, request UnionExampleRequestObject) (UnionExampleResponseObject, error) { - union, err := json.Marshal(*request.Body) - if err != nil { - return nil, err - } - - return UnionExample200JSONResponse{ - Body: struct{ union json.RawMessage }{ - union: union, - }, - }, nil -} diff --git a/internal/test/strict-server/gorilla/types.cfg.yaml b/internal/test/strict-server/gorilla/types.cfg.yaml deleted file mode 100644 index 2ed9740ea7..0000000000 --- a/internal/test/strict-server/gorilla/types.cfg.yaml +++ /dev/null @@ -1,5 +0,0 @@ -# yaml-language-server: $schema=../../../../configuration-schema.json -package: api -generate: - models: true -output: types.gen.go diff --git a/internal/test/strict-server/gorilla/types.gen.go b/internal/test/strict-server/gorilla/types.gen.go deleted file mode 100644 index fac014c4bb..0000000000 --- a/internal/test/strict-server/gorilla/types.gen.go +++ /dev/null @@ -1,69 +0,0 @@ -// Package api provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package api - -// Example defines model for example. -type Example struct { - Value *string `json:"value,omitempty"` -} - -// Reusableresponse defines model for reusableresponse. -type Reusableresponse = Example - -// MultipleRequestAndResponseTypesTextBody defines parameters for MultipleRequestAndResponseTypes. -type MultipleRequestAndResponseTypesTextBody = string - -// RequiredTextBodyTextBody defines parameters for RequiredTextBody. -type RequiredTextBodyTextBody = string - -// TextExampleTextBody defines parameters for TextExample. -type TextExampleTextBody = string - -// HeadersExampleParams defines parameters for HeadersExample. -type HeadersExampleParams struct { - Header1 string `json:"header1"` - Header2 *int `json:"header2,omitempty"` -} - -// JSONExampleJSONRequestBody defines body for JSONExample for application/json ContentType. -type JSONExampleJSONRequestBody = Example - -// MultipartExampleMultipartRequestBody defines body for MultipartExample for multipart/form-data ContentType. -type MultipartExampleMultipartRequestBody = Example - -// MultipartRelatedExampleMultipartRequestBody defines body for MultipartRelatedExample for multipart/related ContentType. -type MultipartRelatedExampleMultipartRequestBody = Example - -// MultipleRequestAndResponseTypesJSONRequestBody defines body for MultipleRequestAndResponseTypes for application/json ContentType. -type MultipleRequestAndResponseTypesJSONRequestBody = Example - -// MultipleRequestAndResponseTypesFormdataRequestBody defines body for MultipleRequestAndResponseTypes for application/x-www-form-urlencoded ContentType. -type MultipleRequestAndResponseTypesFormdataRequestBody = Example - -// MultipleRequestAndResponseTypesMultipartRequestBody defines body for MultipleRequestAndResponseTypes for multipart/form-data ContentType. -type MultipleRequestAndResponseTypesMultipartRequestBody = Example - -// MultipleRequestAndResponseTypesTextRequestBody defines body for MultipleRequestAndResponseTypes for text/plain ContentType. -type MultipleRequestAndResponseTypesTextRequestBody = MultipleRequestAndResponseTypesTextBody - -// RequiredJSONBodyJSONRequestBody defines body for RequiredJSONBody for application/json ContentType. -type RequiredJSONBodyJSONRequestBody = Example - -// RequiredTextBodyTextRequestBody defines body for RequiredTextBody for text/plain ContentType. -type RequiredTextBodyTextRequestBody = RequiredTextBodyTextBody - -// ReusableResponsesJSONRequestBody defines body for ReusableResponses for application/json ContentType. -type ReusableResponsesJSONRequestBody = Example - -// TextExampleTextRequestBody defines body for TextExample for text/plain ContentType. -type TextExampleTextRequestBody = TextExampleTextBody - -// URLEncodedExampleFormdataRequestBody defines body for URLEncodedExample for application/x-www-form-urlencoded ContentType. -type URLEncodedExampleFormdataRequestBody = Example - -// HeadersExampleJSONRequestBody defines body for HeadersExample for application/json ContentType. -type HeadersExampleJSONRequestBody = Example - -// UnionExampleJSONRequestBody defines body for UnionExample for application/json ContentType. -type UnionExampleJSONRequestBody = Example diff --git a/internal/test/strict-server/iris/server.cfg.yaml b/internal/test/strict-server/iris/server.cfg.yaml deleted file mode 100644 index 481f842dc6..0000000000 --- a/internal/test/strict-server/iris/server.cfg.yaml +++ /dev/null @@ -1,7 +0,0 @@ -# yaml-language-server: $schema=../../../../configuration-schema.json -package: api -generate: - iris-server: true - strict-server: true - embedded-spec: true -output: server.gen.go diff --git a/internal/test/strict-server/iris/server.gen.go b/internal/test/strict-server/iris/server.gen.go deleted file mode 100644 index 033e1dd769..0000000000 --- a/internal/test/strict-server/iris/server.gen.go +++ /dev/null @@ -1,1553 +0,0 @@ -// Package api provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package api - -import ( - "bytes" - "compress/gzip" - "context" - "encoding/base64" - "encoding/json" - "errors" - "fmt" - "io" - "mime" - "mime/multipart" - "net/http" - "net/url" - "path" - "strings" - - "github.com/getkin/kin-openapi/openapi3" - "github.com/kataras/iris/v12" - "github.com/oapi-codegen/runtime" - strictiris "github.com/oapi-codegen/runtime/strictmiddleware/iris" -) - -// ServerInterface represents all server handlers. -type ServerInterface interface { - - // (POST /json) - JSONExample(ctx iris.Context) - - // (POST /multipart) - MultipartExample(ctx iris.Context) - - // (POST /multipart-related) - MultipartRelatedExample(ctx iris.Context) - - // (POST /multiple) - MultipleRequestAndResponseTypes(ctx iris.Context) - - // (POST /required-json-body) - RequiredJSONBody(ctx iris.Context) - - // (POST /required-text-body) - RequiredTextBody(ctx iris.Context) - - // (GET /reserved-go-keyword-parameters/{type}) - ReservedGoKeywordParameters(ctx iris.Context, pType string) - - // (POST /reusable-responses) - ReusableResponses(ctx iris.Context) - - // (POST /text) - TextExample(ctx iris.Context) - - // (POST /unknown) - UnknownExample(ctx iris.Context) - - // (POST /unspecified-content-type) - UnspecifiedContentType(ctx iris.Context) - - // (POST /urlencoded) - URLEncodedExample(ctx iris.Context) - - // (POST /with-headers) - HeadersExample(ctx iris.Context, params HeadersExampleParams) - - // (POST /with-union) - UnionExample(ctx iris.Context) -} - -// ServerInterfaceWrapper converts echo contexts to parameters. -type ServerInterfaceWrapper struct { - Handler ServerInterface -} - -type MiddlewareFunc iris.Handler - -// JSONExample converts iris context to params. -func (w *ServerInterfaceWrapper) JSONExample(ctx iris.Context) { - - // Invoke the callback with all the unmarshaled arguments - w.Handler.JSONExample(ctx) -} - -// MultipartExample converts iris context to params. -func (w *ServerInterfaceWrapper) MultipartExample(ctx iris.Context) { - - // Invoke the callback with all the unmarshaled arguments - w.Handler.MultipartExample(ctx) -} - -// MultipartRelatedExample converts iris context to params. -func (w *ServerInterfaceWrapper) MultipartRelatedExample(ctx iris.Context) { - - // Invoke the callback with all the unmarshaled arguments - w.Handler.MultipartRelatedExample(ctx) -} - -// MultipleRequestAndResponseTypes converts iris context to params. -func (w *ServerInterfaceWrapper) MultipleRequestAndResponseTypes(ctx iris.Context) { - - // Invoke the callback with all the unmarshaled arguments - w.Handler.MultipleRequestAndResponseTypes(ctx) -} - -// RequiredJSONBody converts iris context to params. -func (w *ServerInterfaceWrapper) RequiredJSONBody(ctx iris.Context) { - - // Invoke the callback with all the unmarshaled arguments - w.Handler.RequiredJSONBody(ctx) -} - -// RequiredTextBody converts iris context to params. -func (w *ServerInterfaceWrapper) RequiredTextBody(ctx iris.Context) { - - // Invoke the callback with all the unmarshaled arguments - w.Handler.RequiredTextBody(ctx) -} - -// ReservedGoKeywordParameters converts iris context to params. -func (w *ServerInterfaceWrapper) ReservedGoKeywordParameters(ctx iris.Context) { - - var err error - - // ------------- Path parameter "type" ------------- - var pType string - - err = runtime.BindStyledParameterWithOptions("simple", "type", ctx.Params().Get("type"), &pType, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) - if err != nil { - ctx.StatusCode(http.StatusBadRequest) - ctx.Writef("Invalid format for parameter type: %s", err) - return - } - - // Invoke the callback with all the unmarshaled arguments - w.Handler.ReservedGoKeywordParameters(ctx, pType) -} - -// ReusableResponses converts iris context to params. -func (w *ServerInterfaceWrapper) ReusableResponses(ctx iris.Context) { - - // Invoke the callback with all the unmarshaled arguments - w.Handler.ReusableResponses(ctx) -} - -// TextExample converts iris context to params. -func (w *ServerInterfaceWrapper) TextExample(ctx iris.Context) { - - // Invoke the callback with all the unmarshaled arguments - w.Handler.TextExample(ctx) -} - -// UnknownExample converts iris context to params. -func (w *ServerInterfaceWrapper) UnknownExample(ctx iris.Context) { - - // Invoke the callback with all the unmarshaled arguments - w.Handler.UnknownExample(ctx) -} - -// UnspecifiedContentType converts iris context to params. -func (w *ServerInterfaceWrapper) UnspecifiedContentType(ctx iris.Context) { - - // Invoke the callback with all the unmarshaled arguments - w.Handler.UnspecifiedContentType(ctx) -} - -// URLEncodedExample converts iris context to params. -func (w *ServerInterfaceWrapper) URLEncodedExample(ctx iris.Context) { - - // Invoke the callback with all the unmarshaled arguments - w.Handler.URLEncodedExample(ctx) -} - -// HeadersExample converts iris context to params. -func (w *ServerInterfaceWrapper) HeadersExample(ctx iris.Context) { - - var err error - - // Parameter object where we will unmarshal all parameters from the context - var params HeadersExampleParams - - headers := ctx.Request().Header - // ------------- Required header parameter "header1" ------------- - if valueList, found := headers[http.CanonicalHeaderKey("header1")]; found { - var Header1 string - n := len(valueList) - if n != 1 { - ctx.StatusCode(http.StatusBadRequest) - ctx.Writef("Expected one value for header1, got %d", n) - return - } - - err = runtime.BindStyledParameterWithOptions("simple", "header1", valueList[0], &Header1, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: true, Type: "string", Format: ""}) - if err != nil { - ctx.StatusCode(http.StatusBadRequest) - ctx.Writef("Invalid format for parameter header1: %s", err) - return - } - - params.Header1 = Header1 - } else { - ctx.StatusCode(http.StatusBadRequest) - ctx.WriteString("Header header1 is required, but not found") - return - } - // ------------- Optional header parameter "header2" ------------- - if valueList, found := headers[http.CanonicalHeaderKey("header2")]; found { - var Header2 int - n := len(valueList) - if n != 1 { - ctx.StatusCode(http.StatusBadRequest) - ctx.Writef("Expected one value for header2, got %d", n) - return - } - - err = runtime.BindStyledParameterWithOptions("simple", "header2", valueList[0], &Header2, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: ""}) - if err != nil { - ctx.StatusCode(http.StatusBadRequest) - ctx.Writef("Invalid format for parameter header2: %s", err) - return - } - - params.Header2 = &Header2 - } - - // Invoke the callback with all the unmarshaled arguments - w.Handler.HeadersExample(ctx, params) -} - -// UnionExample converts iris context to params. -func (w *ServerInterfaceWrapper) UnionExample(ctx iris.Context) { - - // Invoke the callback with all the unmarshaled arguments - w.Handler.UnionExample(ctx) -} - -// IrisServerOption is the option for iris server -type IrisServerOptions struct { - BaseURL string - Middlewares []MiddlewareFunc -} - -// RegisterHandlers creates http.Handler with routing matching OpenAPI spec. -func RegisterHandlers(router *iris.Application, si ServerInterface) { - RegisterHandlersWithOptions(router, si, IrisServerOptions{}) -} - -// RegisterHandlersWithOptions creates http.Handler with additional options -func RegisterHandlersWithOptions(router *iris.Application, si ServerInterface, options IrisServerOptions) { - - wrapper := ServerInterfaceWrapper{ - Handler: si, - } - - router.Post(options.BaseURL+"/json", wrapper.JSONExample) - router.Post(options.BaseURL+"/multipart", wrapper.MultipartExample) - router.Post(options.BaseURL+"/multipart-related", wrapper.MultipartRelatedExample) - router.Post(options.BaseURL+"/multiple", wrapper.MultipleRequestAndResponseTypes) - router.Post(options.BaseURL+"/required-json-body", wrapper.RequiredJSONBody) - router.Post(options.BaseURL+"/required-text-body", wrapper.RequiredTextBody) - router.Get(options.BaseURL+"/reserved-go-keyword-parameters/:type", wrapper.ReservedGoKeywordParameters) - router.Post(options.BaseURL+"/reusable-responses", wrapper.ReusableResponses) - router.Post(options.BaseURL+"/text", wrapper.TextExample) - router.Post(options.BaseURL+"/unknown", wrapper.UnknownExample) - router.Post(options.BaseURL+"/unspecified-content-type", wrapper.UnspecifiedContentType) - router.Post(options.BaseURL+"/urlencoded", wrapper.URLEncodedExample) - router.Post(options.BaseURL+"/with-headers", wrapper.HeadersExample) - router.Post(options.BaseURL+"/with-union", wrapper.UnionExample) - - router.Build() -} - -type BadrequestResponse struct { -} - -type ReusableresponseResponseHeaders struct { - Header1 string - Header2 int -} -type ReusableresponseJSONResponse struct { - Body Example - - Headers ReusableresponseResponseHeaders -} - -type JSONExampleRequestObject struct { - Body *JSONExampleJSONRequestBody -} - -type JSONExampleResponseObject interface { - VisitJSONExampleResponse(ctx iris.Context) error -} - -type JSONExample200JSONResponse Example - -func (response JSONExample200JSONResponse) VisitJSONExampleResponse(ctx iris.Context) error { - ctx.ResponseWriter().Header().Set("Content-Type", "application/json") - ctx.StatusCode(200) - - return ctx.JSON(&response) -} - -type JSONExample400Response = BadrequestResponse - -func (response JSONExample400Response) VisitJSONExampleResponse(ctx iris.Context) error { - ctx.StatusCode(400) - return nil -} - -type JSONExampledefaultResponse struct { - StatusCode int -} - -func (response JSONExampledefaultResponse) VisitJSONExampleResponse(ctx iris.Context) error { - ctx.StatusCode(response.StatusCode) - return nil -} - -type MultipartExampleRequestObject struct { - Body *multipart.Reader -} - -type MultipartExampleResponseObject interface { - VisitMultipartExampleResponse(ctx iris.Context) error -} - -type MultipartExample200MultipartResponse func(writer *multipart.Writer) error - -func (response MultipartExample200MultipartResponse) VisitMultipartExampleResponse(ctx iris.Context) error { - writer := multipart.NewWriter(ctx.ResponseWriter()) - ctx.ResponseWriter().Header().Set("Content-Type", writer.FormDataContentType()) - ctx.StatusCode(200) - - defer writer.Close() - return response(writer) -} - -type MultipartExample400Response = BadrequestResponse - -func (response MultipartExample400Response) VisitMultipartExampleResponse(ctx iris.Context) error { - ctx.StatusCode(400) - return nil -} - -type MultipartExampledefaultResponse struct { - StatusCode int -} - -func (response MultipartExampledefaultResponse) VisitMultipartExampleResponse(ctx iris.Context) error { - ctx.StatusCode(response.StatusCode) - return nil -} - -type MultipartRelatedExampleRequestObject struct { - Body *multipart.Reader -} - -type MultipartRelatedExampleResponseObject interface { - VisitMultipartRelatedExampleResponse(ctx iris.Context) error -} - -type MultipartRelatedExample200MultipartResponse func(writer *multipart.Writer) error - -func (response MultipartRelatedExample200MultipartResponse) VisitMultipartRelatedExampleResponse(ctx iris.Context) error { - writer := multipart.NewWriter(ctx.ResponseWriter()) - ctx.ResponseWriter().Header().Set("Content-Type", mime.FormatMediaType("multipart/related", map[string]string{"boundary": writer.Boundary()})) - ctx.StatusCode(200) - - defer writer.Close() - return response(writer) -} - -type MultipartRelatedExample400Response = BadrequestResponse - -func (response MultipartRelatedExample400Response) VisitMultipartRelatedExampleResponse(ctx iris.Context) error { - ctx.StatusCode(400) - return nil -} - -type MultipartRelatedExampledefaultResponse struct { - StatusCode int -} - -func (response MultipartRelatedExampledefaultResponse) VisitMultipartRelatedExampleResponse(ctx iris.Context) error { - ctx.StatusCode(response.StatusCode) - return nil -} - -type MultipleRequestAndResponseTypesRequestObject struct { - JSONBody *MultipleRequestAndResponseTypesJSONRequestBody - FormdataBody *MultipleRequestAndResponseTypesFormdataRequestBody - Body io.Reader - MultipartBody *multipart.Reader - TextBody *MultipleRequestAndResponseTypesTextRequestBody -} - -type MultipleRequestAndResponseTypesResponseObject interface { - VisitMultipleRequestAndResponseTypesResponse(ctx iris.Context) error -} - -type MultipleRequestAndResponseTypes200JSONResponse Example - -func (response MultipleRequestAndResponseTypes200JSONResponse) VisitMultipleRequestAndResponseTypesResponse(ctx iris.Context) error { - ctx.ResponseWriter().Header().Set("Content-Type", "application/json") - ctx.StatusCode(200) - - return ctx.JSON(&response) -} - -type MultipleRequestAndResponseTypes200FormdataResponse Example - -func (response MultipleRequestAndResponseTypes200FormdataResponse) VisitMultipleRequestAndResponseTypesResponse(ctx iris.Context) error { - ctx.ResponseWriter().Header().Set("Content-Type", "application/x-www-form-urlencoded") - ctx.StatusCode(200) - - if form, err := runtime.MarshalForm(response, nil); err != nil { - return err - } else { - _, err := ctx.WriteString(form.Encode()) - return err - } -} - -type MultipleRequestAndResponseTypes200ImagepngResponse struct { - Body io.Reader - ContentLength int64 -} - -func (response MultipleRequestAndResponseTypes200ImagepngResponse) VisitMultipleRequestAndResponseTypesResponse(ctx iris.Context) error { - ctx.ResponseWriter().Header().Set("Content-Type", "image/png") - if response.ContentLength != 0 { - ctx.ResponseWriter().Header().Set("Content-Length", fmt.Sprint(response.ContentLength)) - } - ctx.StatusCode(200) - - if closer, ok := response.Body.(io.ReadCloser); ok { - defer closer.Close() - } - _, err := io.Copy(ctx.ResponseWriter(), response.Body) - return err -} - -type MultipleRequestAndResponseTypes200MultipartResponse func(writer *multipart.Writer) error - -func (response MultipleRequestAndResponseTypes200MultipartResponse) VisitMultipleRequestAndResponseTypesResponse(ctx iris.Context) error { - writer := multipart.NewWriter(ctx.ResponseWriter()) - ctx.ResponseWriter().Header().Set("Content-Type", writer.FormDataContentType()) - ctx.StatusCode(200) - - defer writer.Close() - return response(writer) -} - -type MultipleRequestAndResponseTypes200TextResponse string - -func (response MultipleRequestAndResponseTypes200TextResponse) VisitMultipleRequestAndResponseTypesResponse(ctx iris.Context) error { - ctx.ResponseWriter().Header().Set("Content-Type", "text/plain") - ctx.StatusCode(200) - - _, err := ctx.WriteString(string(response)) - return err -} - -type MultipleRequestAndResponseTypes400Response = BadrequestResponse - -func (response MultipleRequestAndResponseTypes400Response) VisitMultipleRequestAndResponseTypesResponse(ctx iris.Context) error { - ctx.StatusCode(400) - return nil -} - -type RequiredJSONBodyRequestObject struct { - Body *RequiredJSONBodyJSONRequestBody -} - -type RequiredJSONBodyResponseObject interface { - VisitRequiredJSONBodyResponse(ctx iris.Context) error -} - -type RequiredJSONBody200JSONResponse Example - -func (response RequiredJSONBody200JSONResponse) VisitRequiredJSONBodyResponse(ctx iris.Context) error { - ctx.ResponseWriter().Header().Set("Content-Type", "application/json") - ctx.StatusCode(200) - - return ctx.JSON(&response) -} - -type RequiredJSONBody400Response = BadrequestResponse - -func (response RequiredJSONBody400Response) VisitRequiredJSONBodyResponse(ctx iris.Context) error { - ctx.StatusCode(400) - return nil -} - -type RequiredJSONBodydefaultResponse struct { - StatusCode int -} - -func (response RequiredJSONBodydefaultResponse) VisitRequiredJSONBodyResponse(ctx iris.Context) error { - ctx.StatusCode(response.StatusCode) - return nil -} - -type RequiredTextBodyRequestObject struct { - Body *RequiredTextBodyTextRequestBody -} - -type RequiredTextBodyResponseObject interface { - VisitRequiredTextBodyResponse(ctx iris.Context) error -} - -type RequiredTextBody200TextResponse string - -func (response RequiredTextBody200TextResponse) VisitRequiredTextBodyResponse(ctx iris.Context) error { - ctx.ResponseWriter().Header().Set("Content-Type", "text/plain") - ctx.StatusCode(200) - - _, err := ctx.WriteString(string(response)) - return err -} - -type RequiredTextBody400Response = BadrequestResponse - -func (response RequiredTextBody400Response) VisitRequiredTextBodyResponse(ctx iris.Context) error { - ctx.StatusCode(400) - return nil -} - -type RequiredTextBodydefaultResponse struct { - StatusCode int -} - -func (response RequiredTextBodydefaultResponse) VisitRequiredTextBodyResponse(ctx iris.Context) error { - ctx.StatusCode(response.StatusCode) - return nil -} - -type ReservedGoKeywordParametersRequestObject struct { - Type string `json:"type"` -} - -type ReservedGoKeywordParametersResponseObject interface { - VisitReservedGoKeywordParametersResponse(ctx iris.Context) error -} - -type ReservedGoKeywordParameters200TextResponse string - -func (response ReservedGoKeywordParameters200TextResponse) VisitReservedGoKeywordParametersResponse(ctx iris.Context) error { - ctx.ResponseWriter().Header().Set("Content-Type", "text/plain") - ctx.StatusCode(200) - - _, err := ctx.WriteString(string(response)) - return err -} - -type ReusableResponsesRequestObject struct { - Body *ReusableResponsesJSONRequestBody -} - -type ReusableResponsesResponseObject interface { - VisitReusableResponsesResponse(ctx iris.Context) error -} - -type ReusableResponses200JSONResponse struct{ ReusableresponseJSONResponse } - -func (response ReusableResponses200JSONResponse) VisitReusableResponsesResponse(ctx iris.Context) error { - ctx.ResponseWriter().Header().Set("header1", fmt.Sprint(response.Headers.Header1)) - ctx.ResponseWriter().Header().Set("header2", fmt.Sprint(response.Headers.Header2)) - ctx.ResponseWriter().Header().Set("Content-Type", "application/json") - ctx.StatusCode(200) - - return ctx.JSON(&response.Body) -} - -type ReusableResponses400Response = BadrequestResponse - -func (response ReusableResponses400Response) VisitReusableResponsesResponse(ctx iris.Context) error { - ctx.StatusCode(400) - return nil -} - -type ReusableResponsesdefaultResponse struct { - StatusCode int -} - -func (response ReusableResponsesdefaultResponse) VisitReusableResponsesResponse(ctx iris.Context) error { - ctx.StatusCode(response.StatusCode) - return nil -} - -type TextExampleRequestObject struct { - Body *TextExampleTextRequestBody -} - -type TextExampleResponseObject interface { - VisitTextExampleResponse(ctx iris.Context) error -} - -type TextExample200TextResponse string - -func (response TextExample200TextResponse) VisitTextExampleResponse(ctx iris.Context) error { - ctx.ResponseWriter().Header().Set("Content-Type", "text/plain") - ctx.StatusCode(200) - - _, err := ctx.WriteString(string(response)) - return err -} - -type TextExample400Response = BadrequestResponse - -func (response TextExample400Response) VisitTextExampleResponse(ctx iris.Context) error { - ctx.StatusCode(400) - return nil -} - -type TextExampledefaultResponse struct { - StatusCode int -} - -func (response TextExampledefaultResponse) VisitTextExampleResponse(ctx iris.Context) error { - ctx.StatusCode(response.StatusCode) - return nil -} - -type UnknownExampleRequestObject struct { - Body io.Reader -} - -type UnknownExampleResponseObject interface { - VisitUnknownExampleResponse(ctx iris.Context) error -} - -type UnknownExample200Videomp4Response struct { - Body io.Reader - ContentLength int64 -} - -func (response UnknownExample200Videomp4Response) VisitUnknownExampleResponse(ctx iris.Context) error { - ctx.ResponseWriter().Header().Set("Content-Type", "video/mp4") - if response.ContentLength != 0 { - ctx.ResponseWriter().Header().Set("Content-Length", fmt.Sprint(response.ContentLength)) - } - ctx.StatusCode(200) - - if closer, ok := response.Body.(io.ReadCloser); ok { - defer closer.Close() - } - _, err := io.Copy(ctx.ResponseWriter(), response.Body) - return err -} - -type UnknownExample400Response = BadrequestResponse - -func (response UnknownExample400Response) VisitUnknownExampleResponse(ctx iris.Context) error { - ctx.StatusCode(400) - return nil -} - -type UnknownExampledefaultResponse struct { - StatusCode int -} - -func (response UnknownExampledefaultResponse) VisitUnknownExampleResponse(ctx iris.Context) error { - ctx.StatusCode(response.StatusCode) - return nil -} - -type UnspecifiedContentTypeRequestObject struct { - ContentType string - Body io.Reader -} - -type UnspecifiedContentTypeResponseObject interface { - VisitUnspecifiedContentTypeResponse(ctx iris.Context) error -} - -type UnspecifiedContentType200VideoResponse struct { - Body io.Reader - ContentType string - ContentLength int64 -} - -func (response UnspecifiedContentType200VideoResponse) VisitUnspecifiedContentTypeResponse(ctx iris.Context) error { - ctx.ResponseWriter().Header().Set("Content-Type", response.ContentType) - if response.ContentLength != 0 { - ctx.ResponseWriter().Header().Set("Content-Length", fmt.Sprint(response.ContentLength)) - } - ctx.StatusCode(200) - - if closer, ok := response.Body.(io.ReadCloser); ok { - defer closer.Close() - } - _, err := io.Copy(ctx.ResponseWriter(), response.Body) - return err -} - -type UnspecifiedContentType400Response = BadrequestResponse - -func (response UnspecifiedContentType400Response) VisitUnspecifiedContentTypeResponse(ctx iris.Context) error { - ctx.StatusCode(400) - return nil -} - -type UnspecifiedContentType401Response struct { -} - -func (response UnspecifiedContentType401Response) VisitUnspecifiedContentTypeResponse(ctx iris.Context) error { - ctx.StatusCode(401) - return nil -} - -type UnspecifiedContentType403Response struct { -} - -func (response UnspecifiedContentType403Response) VisitUnspecifiedContentTypeResponse(ctx iris.Context) error { - ctx.StatusCode(403) - return nil -} - -type UnspecifiedContentTypedefaultResponse struct { - StatusCode int -} - -func (response UnspecifiedContentTypedefaultResponse) VisitUnspecifiedContentTypeResponse(ctx iris.Context) error { - ctx.StatusCode(response.StatusCode) - return nil -} - -type URLEncodedExampleRequestObject struct { - Body *URLEncodedExampleFormdataRequestBody -} - -type URLEncodedExampleResponseObject interface { - VisitURLEncodedExampleResponse(ctx iris.Context) error -} - -type URLEncodedExample200FormdataResponse Example - -func (response URLEncodedExample200FormdataResponse) VisitURLEncodedExampleResponse(ctx iris.Context) error { - ctx.ResponseWriter().Header().Set("Content-Type", "application/x-www-form-urlencoded") - ctx.StatusCode(200) - - if form, err := runtime.MarshalForm(response, nil); err != nil { - return err - } else { - _, err := ctx.WriteString(form.Encode()) - return err - } -} - -type URLEncodedExample400Response = BadrequestResponse - -func (response URLEncodedExample400Response) VisitURLEncodedExampleResponse(ctx iris.Context) error { - ctx.StatusCode(400) - return nil -} - -type URLEncodedExampledefaultResponse struct { - StatusCode int -} - -func (response URLEncodedExampledefaultResponse) VisitURLEncodedExampleResponse(ctx iris.Context) error { - ctx.StatusCode(response.StatusCode) - return nil -} - -type HeadersExampleRequestObject struct { - Params HeadersExampleParams - Body *HeadersExampleJSONRequestBody -} - -type HeadersExampleResponseObject interface { - VisitHeadersExampleResponse(ctx iris.Context) error -} - -type HeadersExample200ResponseHeaders struct { - Header1 string - Header2 int -} - -type HeadersExample200JSONResponse struct { - Body Example - Headers HeadersExample200ResponseHeaders -} - -func (response HeadersExample200JSONResponse) VisitHeadersExampleResponse(ctx iris.Context) error { - ctx.ResponseWriter().Header().Set("header1", fmt.Sprint(response.Headers.Header1)) - ctx.ResponseWriter().Header().Set("header2", fmt.Sprint(response.Headers.Header2)) - ctx.ResponseWriter().Header().Set("Content-Type", "application/json") - ctx.StatusCode(200) - - return ctx.JSON(&response.Body) -} - -type HeadersExample400Response = BadrequestResponse - -func (response HeadersExample400Response) VisitHeadersExampleResponse(ctx iris.Context) error { - ctx.StatusCode(400) - return nil -} - -type HeadersExampledefaultResponse struct { - StatusCode int -} - -func (response HeadersExampledefaultResponse) VisitHeadersExampleResponse(ctx iris.Context) error { - ctx.StatusCode(response.StatusCode) - return nil -} - -type UnionExampleRequestObject struct { - Body *UnionExampleJSONRequestBody -} - -type UnionExampleResponseObject interface { - VisitUnionExampleResponse(ctx iris.Context) error -} - -type UnionExample200ResponseHeaders struct { - Header1 string - Header2 int -} - -type UnionExample200ApplicationAlternativePlusJSONResponse struct { - Body Example - Headers UnionExample200ResponseHeaders -} - -func (response UnionExample200ApplicationAlternativePlusJSONResponse) VisitUnionExampleResponse(ctx iris.Context) error { - ctx.ResponseWriter().Header().Set("header1", fmt.Sprint(response.Headers.Header1)) - ctx.ResponseWriter().Header().Set("header2", fmt.Sprint(response.Headers.Header2)) - ctx.ResponseWriter().Header().Set("Content-Type", "application/alternative+json") - ctx.StatusCode(200) - - return ctx.JSON(&response.Body) -} - -type UnionExample200JSONResponse struct { - Body struct { - union json.RawMessage - } - Headers UnionExample200ResponseHeaders -} - -func (response UnionExample200JSONResponse) VisitUnionExampleResponse(ctx iris.Context) error { - ctx.ResponseWriter().Header().Set("header1", fmt.Sprint(response.Headers.Header1)) - ctx.ResponseWriter().Header().Set("header2", fmt.Sprint(response.Headers.Header2)) - ctx.ResponseWriter().Header().Set("Content-Type", "application/json") - ctx.StatusCode(200) - - return ctx.JSON(&response.Body.union) -} - -type UnionExample400Response = BadrequestResponse - -func (response UnionExample400Response) VisitUnionExampleResponse(ctx iris.Context) error { - ctx.StatusCode(400) - return nil -} - -type UnionExampledefaultResponse struct { - StatusCode int -} - -func (response UnionExampledefaultResponse) VisitUnionExampleResponse(ctx iris.Context) error { - ctx.StatusCode(response.StatusCode) - return nil -} - -// StrictServerInterface represents all server handlers. -type StrictServerInterface interface { - - // (POST /json) - JSONExample(ctx context.Context, request JSONExampleRequestObject) (JSONExampleResponseObject, error) - - // (POST /multipart) - MultipartExample(ctx context.Context, request MultipartExampleRequestObject) (MultipartExampleResponseObject, error) - - // (POST /multipart-related) - MultipartRelatedExample(ctx context.Context, request MultipartRelatedExampleRequestObject) (MultipartRelatedExampleResponseObject, error) - - // (POST /multiple) - MultipleRequestAndResponseTypes(ctx context.Context, request MultipleRequestAndResponseTypesRequestObject) (MultipleRequestAndResponseTypesResponseObject, error) - - // (POST /required-json-body) - RequiredJSONBody(ctx context.Context, request RequiredJSONBodyRequestObject) (RequiredJSONBodyResponseObject, error) - - // (POST /required-text-body) - RequiredTextBody(ctx context.Context, request RequiredTextBodyRequestObject) (RequiredTextBodyResponseObject, error) - - // (GET /reserved-go-keyword-parameters/{type}) - ReservedGoKeywordParameters(ctx context.Context, request ReservedGoKeywordParametersRequestObject) (ReservedGoKeywordParametersResponseObject, error) - - // (POST /reusable-responses) - ReusableResponses(ctx context.Context, request ReusableResponsesRequestObject) (ReusableResponsesResponseObject, error) - - // (POST /text) - TextExample(ctx context.Context, request TextExampleRequestObject) (TextExampleResponseObject, error) - - // (POST /unknown) - UnknownExample(ctx context.Context, request UnknownExampleRequestObject) (UnknownExampleResponseObject, error) - - // (POST /unspecified-content-type) - UnspecifiedContentType(ctx context.Context, request UnspecifiedContentTypeRequestObject) (UnspecifiedContentTypeResponseObject, error) - - // (POST /urlencoded) - URLEncodedExample(ctx context.Context, request URLEncodedExampleRequestObject) (URLEncodedExampleResponseObject, error) - - // (POST /with-headers) - HeadersExample(ctx context.Context, request HeadersExampleRequestObject) (HeadersExampleResponseObject, error) - - // (POST /with-union) - UnionExample(ctx context.Context, request UnionExampleRequestObject) (UnionExampleResponseObject, error) -} - -type StrictHandlerFunc = strictiris.StrictIrisHandlerFunc -type StrictMiddlewareFunc = strictiris.StrictIrisMiddlewareFunc - -func NewStrictHandler(ssi StrictServerInterface, middlewares []StrictMiddlewareFunc) ServerInterface { - return &strictHandler{ssi: ssi, middlewares: middlewares} -} - -type strictHandler struct { - ssi StrictServerInterface - middlewares []StrictMiddlewareFunc -} - -// JSONExample operation middleware -func (sh *strictHandler) JSONExample(ctx iris.Context) { - var request JSONExampleRequestObject - - var body JSONExampleJSONRequestBody - if err := ctx.ReadJSON(&body); err != nil { - if !errors.Is(err, io.EOF) { - ctx.StopWithError(http.StatusBadRequest, err) - return - } - } else { - request.Body = &body - } - - handler := func(ctx iris.Context, request interface{}) (interface{}, error) { - return sh.ssi.JSONExample(ctx, request.(JSONExampleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "JSONExample") - } - - response, err := handler(ctx, request) - - if err != nil { - ctx.StopWithError(http.StatusBadRequest, err) - return - } else if validResponse, ok := response.(JSONExampleResponseObject); ok { - if err := validResponse.VisitJSONExampleResponse(ctx); err != nil { - ctx.StopWithError(http.StatusBadRequest, err) - return - } - } else if response != nil { - ctx.Writef("Unexpected response type: %T", response) - return - } -} - -// MultipartExample operation middleware -func (sh *strictHandler) MultipartExample(ctx iris.Context) { - var request MultipartExampleRequestObject - - if reader, err := ctx.Request().MultipartReader(); err == nil { - request.Body = reader - } else { - ctx.StopWithError(http.StatusBadRequest, err) - return - } - - handler := func(ctx iris.Context, request interface{}) (interface{}, error) { - return sh.ssi.MultipartExample(ctx, request.(MultipartExampleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "MultipartExample") - } - - response, err := handler(ctx, request) - - if err != nil { - ctx.StopWithError(http.StatusBadRequest, err) - return - } else if validResponse, ok := response.(MultipartExampleResponseObject); ok { - if err := validResponse.VisitMultipartExampleResponse(ctx); err != nil { - ctx.StopWithError(http.StatusBadRequest, err) - return - } - } else if response != nil { - ctx.Writef("Unexpected response type: %T", response) - return - } -} - -// MultipartRelatedExample operation middleware -func (sh *strictHandler) MultipartRelatedExample(ctx iris.Context) { - var request MultipartRelatedExampleRequestObject - - if _, params, err := mime.ParseMediaType(ctx.Request().Header.Get("Content-Type")); err != nil { - ctx.StopWithError(http.StatusBadRequest, err) - return - } else if boundary := params["boundary"]; boundary == "" { - ctx.StopWithError(http.StatusBadRequest, http.ErrMissingBoundary) - return - } else { - request.Body = multipart.NewReader(ctx.Request().Body, boundary) - } - - handler := func(ctx iris.Context, request interface{}) (interface{}, error) { - return sh.ssi.MultipartRelatedExample(ctx, request.(MultipartRelatedExampleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "MultipartRelatedExample") - } - - response, err := handler(ctx, request) - - if err != nil { - ctx.StopWithError(http.StatusBadRequest, err) - return - } else if validResponse, ok := response.(MultipartRelatedExampleResponseObject); ok { - if err := validResponse.VisitMultipartRelatedExampleResponse(ctx); err != nil { - ctx.StopWithError(http.StatusBadRequest, err) - return - } - } else if response != nil { - ctx.Writef("Unexpected response type: %T", response) - return - } -} - -// MultipleRequestAndResponseTypes operation middleware -func (sh *strictHandler) MultipleRequestAndResponseTypes(ctx iris.Context) { - var request MultipleRequestAndResponseTypesRequestObject - - if strings.HasPrefix(ctx.GetHeader("Content-Type"), "application/json") { - - var body MultipleRequestAndResponseTypesJSONRequestBody - if err := ctx.ReadJSON(&body); err != nil { - if !errors.Is(err, io.EOF) { - ctx.StopWithError(http.StatusBadRequest, err) - return - } - } else { - request.JSONBody = &body - } - } - if strings.HasPrefix(ctx.GetHeader("Content-Type"), "application/x-www-form-urlencoded") { - if err := ctx.Request().ParseForm(); err != nil { - ctx.StopWithError(http.StatusBadRequest, err) - return - } - var body MultipleRequestAndResponseTypesFormdataRequestBody - if err := runtime.BindForm(&body, ctx.Request().Form, nil, nil); err != nil { - ctx.StopWithError(http.StatusBadRequest, err) - return - } - request.FormdataBody = &body - } - if strings.HasPrefix(ctx.GetHeader("Content-Type"), "image/png") { - request.Body = ctx.Request().Body - } - if strings.HasPrefix(ctx.GetHeader("Content-Type"), "multipart/form-data") { - if reader, err := ctx.Request().MultipartReader(); err == nil { - request.MultipartBody = reader - } else { - ctx.StopWithError(http.StatusBadRequest, err) - return - } - } - if strings.HasPrefix(ctx.GetHeader("Content-Type"), "text/plain") { - data, err := io.ReadAll(ctx.Request().Body) - if err != nil { - ctx.StopWithError(http.StatusBadRequest, err) - return - } - if len(data) > 0 { - body := MultipleRequestAndResponseTypesTextRequestBody(data) - request.TextBody = &body - } - } - - handler := func(ctx iris.Context, request interface{}) (interface{}, error) { - return sh.ssi.MultipleRequestAndResponseTypes(ctx, request.(MultipleRequestAndResponseTypesRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "MultipleRequestAndResponseTypes") - } - - response, err := handler(ctx, request) - - if err != nil { - ctx.StopWithError(http.StatusBadRequest, err) - return - } else if validResponse, ok := response.(MultipleRequestAndResponseTypesResponseObject); ok { - if err := validResponse.VisitMultipleRequestAndResponseTypesResponse(ctx); err != nil { - ctx.StopWithError(http.StatusBadRequest, err) - return - } - } else if response != nil { - ctx.Writef("Unexpected response type: %T", response) - return - } -} - -// RequiredJSONBody operation middleware -func (sh *strictHandler) RequiredJSONBody(ctx iris.Context) { - var request RequiredJSONBodyRequestObject - - var body RequiredJSONBodyJSONRequestBody - if err := ctx.ReadJSON(&body); err != nil { - ctx.StopWithError(http.StatusBadRequest, err) - return - } - request.Body = &body - - handler := func(ctx iris.Context, request interface{}) (interface{}, error) { - return sh.ssi.RequiredJSONBody(ctx, request.(RequiredJSONBodyRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "RequiredJSONBody") - } - - response, err := handler(ctx, request) - - if err != nil { - ctx.StopWithError(http.StatusBadRequest, err) - return - } else if validResponse, ok := response.(RequiredJSONBodyResponseObject); ok { - if err := validResponse.VisitRequiredJSONBodyResponse(ctx); err != nil { - ctx.StopWithError(http.StatusBadRequest, err) - return - } - } else if response != nil { - ctx.Writef("Unexpected response type: %T", response) - return - } -} - -// RequiredTextBody operation middleware -func (sh *strictHandler) RequiredTextBody(ctx iris.Context) { - var request RequiredTextBodyRequestObject - - data, err := io.ReadAll(ctx.Request().Body) - if err != nil { - ctx.StopWithError(http.StatusBadRequest, err) - return - } - body := RequiredTextBodyTextRequestBody(data) - request.Body = &body - - handler := func(ctx iris.Context, request interface{}) (interface{}, error) { - return sh.ssi.RequiredTextBody(ctx, request.(RequiredTextBodyRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "RequiredTextBody") - } - - response, err := handler(ctx, request) - - if err != nil { - ctx.StopWithError(http.StatusBadRequest, err) - return - } else if validResponse, ok := response.(RequiredTextBodyResponseObject); ok { - if err := validResponse.VisitRequiredTextBodyResponse(ctx); err != nil { - ctx.StopWithError(http.StatusBadRequest, err) - return - } - } else if response != nil { - ctx.Writef("Unexpected response type: %T", response) - return - } -} - -// ReservedGoKeywordParameters operation middleware -func (sh *strictHandler) ReservedGoKeywordParameters(ctx iris.Context, pType string) { - var request ReservedGoKeywordParametersRequestObject - - request.Type = pType - - handler := func(ctx iris.Context, request interface{}) (interface{}, error) { - return sh.ssi.ReservedGoKeywordParameters(ctx, request.(ReservedGoKeywordParametersRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "ReservedGoKeywordParameters") - } - - response, err := handler(ctx, request) - - if err != nil { - ctx.StopWithError(http.StatusBadRequest, err) - return - } else if validResponse, ok := response.(ReservedGoKeywordParametersResponseObject); ok { - if err := validResponse.VisitReservedGoKeywordParametersResponse(ctx); err != nil { - ctx.StopWithError(http.StatusBadRequest, err) - return - } - } else if response != nil { - ctx.Writef("Unexpected response type: %T", response) - return - } -} - -// ReusableResponses operation middleware -func (sh *strictHandler) ReusableResponses(ctx iris.Context) { - var request ReusableResponsesRequestObject - - var body ReusableResponsesJSONRequestBody - if err := ctx.ReadJSON(&body); err != nil { - if !errors.Is(err, io.EOF) { - ctx.StopWithError(http.StatusBadRequest, err) - return - } - } else { - request.Body = &body - } - - handler := func(ctx iris.Context, request interface{}) (interface{}, error) { - return sh.ssi.ReusableResponses(ctx, request.(ReusableResponsesRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "ReusableResponses") - } - - response, err := handler(ctx, request) - - if err != nil { - ctx.StopWithError(http.StatusBadRequest, err) - return - } else if validResponse, ok := response.(ReusableResponsesResponseObject); ok { - if err := validResponse.VisitReusableResponsesResponse(ctx); err != nil { - ctx.StopWithError(http.StatusBadRequest, err) - return - } - } else if response != nil { - ctx.Writef("Unexpected response type: %T", response) - return - } -} - -// TextExample operation middleware -func (sh *strictHandler) TextExample(ctx iris.Context) { - var request TextExampleRequestObject - - data, err := io.ReadAll(ctx.Request().Body) - if err != nil { - ctx.StopWithError(http.StatusBadRequest, err) - return - } - if len(data) > 0 { - body := TextExampleTextRequestBody(data) - request.Body = &body - } - - handler := func(ctx iris.Context, request interface{}) (interface{}, error) { - return sh.ssi.TextExample(ctx, request.(TextExampleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "TextExample") - } - - response, err := handler(ctx, request) - - if err != nil { - ctx.StopWithError(http.StatusBadRequest, err) - return - } else if validResponse, ok := response.(TextExampleResponseObject); ok { - if err := validResponse.VisitTextExampleResponse(ctx); err != nil { - ctx.StopWithError(http.StatusBadRequest, err) - return - } - } else if response != nil { - ctx.Writef("Unexpected response type: %T", response) - return - } -} - -// UnknownExample operation middleware -func (sh *strictHandler) UnknownExample(ctx iris.Context) { - var request UnknownExampleRequestObject - - request.Body = ctx.Request().Body - - handler := func(ctx iris.Context, request interface{}) (interface{}, error) { - return sh.ssi.UnknownExample(ctx, request.(UnknownExampleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "UnknownExample") - } - - response, err := handler(ctx, request) - - if err != nil { - ctx.StopWithError(http.StatusBadRequest, err) - return - } else if validResponse, ok := response.(UnknownExampleResponseObject); ok { - if err := validResponse.VisitUnknownExampleResponse(ctx); err != nil { - ctx.StopWithError(http.StatusBadRequest, err) - return - } - } else if response != nil { - ctx.Writef("Unexpected response type: %T", response) - return - } -} - -// UnspecifiedContentType operation middleware -func (sh *strictHandler) UnspecifiedContentType(ctx iris.Context) { - var request UnspecifiedContentTypeRequestObject - - request.ContentType = ctx.GetContentTypeRequested() - - request.Body = ctx.Request().Body - - handler := func(ctx iris.Context, request interface{}) (interface{}, error) { - return sh.ssi.UnspecifiedContentType(ctx, request.(UnspecifiedContentTypeRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "UnspecifiedContentType") - } - - response, err := handler(ctx, request) - - if err != nil { - ctx.StopWithError(http.StatusBadRequest, err) - return - } else if validResponse, ok := response.(UnspecifiedContentTypeResponseObject); ok { - if err := validResponse.VisitUnspecifiedContentTypeResponse(ctx); err != nil { - ctx.StopWithError(http.StatusBadRequest, err) - return - } - } else if response != nil { - ctx.Writef("Unexpected response type: %T", response) - return - } -} - -// URLEncodedExample operation middleware -func (sh *strictHandler) URLEncodedExample(ctx iris.Context) { - var request URLEncodedExampleRequestObject - - if err := ctx.Request().ParseForm(); err != nil { - ctx.StopWithError(http.StatusBadRequest, err) - return - } - var body URLEncodedExampleFormdataRequestBody - if err := runtime.BindForm(&body, ctx.Request().Form, nil, nil); err != nil { - ctx.StopWithError(http.StatusBadRequest, err) - return - } - request.Body = &body - - handler := func(ctx iris.Context, request interface{}) (interface{}, error) { - return sh.ssi.URLEncodedExample(ctx, request.(URLEncodedExampleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "URLEncodedExample") - } - - response, err := handler(ctx, request) - - if err != nil { - ctx.StopWithError(http.StatusBadRequest, err) - return - } else if validResponse, ok := response.(URLEncodedExampleResponseObject); ok { - if err := validResponse.VisitURLEncodedExampleResponse(ctx); err != nil { - ctx.StopWithError(http.StatusBadRequest, err) - return - } - } else if response != nil { - ctx.Writef("Unexpected response type: %T", response) - return - } -} - -// HeadersExample operation middleware -func (sh *strictHandler) HeadersExample(ctx iris.Context, params HeadersExampleParams) { - var request HeadersExampleRequestObject - - request.Params = params - - var body HeadersExampleJSONRequestBody - if err := ctx.ReadJSON(&body); err != nil { - if !errors.Is(err, io.EOF) { - ctx.StopWithError(http.StatusBadRequest, err) - return - } - } else { - request.Body = &body - } - - handler := func(ctx iris.Context, request interface{}) (interface{}, error) { - return sh.ssi.HeadersExample(ctx, request.(HeadersExampleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "HeadersExample") - } - - response, err := handler(ctx, request) - - if err != nil { - ctx.StopWithError(http.StatusBadRequest, err) - return - } else if validResponse, ok := response.(HeadersExampleResponseObject); ok { - if err := validResponse.VisitHeadersExampleResponse(ctx); err != nil { - ctx.StopWithError(http.StatusBadRequest, err) - return - } - } else if response != nil { - ctx.Writef("Unexpected response type: %T", response) - return - } -} - -// UnionExample operation middleware -func (sh *strictHandler) UnionExample(ctx iris.Context) { - var request UnionExampleRequestObject - - var body UnionExampleJSONRequestBody - if err := ctx.ReadJSON(&body); err != nil { - if !errors.Is(err, io.EOF) { - ctx.StopWithError(http.StatusBadRequest, err) - return - } - } else { - request.Body = &body - } - - handler := func(ctx iris.Context, request interface{}) (interface{}, error) { - return sh.ssi.UnionExample(ctx, request.(UnionExampleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "UnionExample") - } - - response, err := handler(ctx, request) - - if err != nil { - ctx.StopWithError(http.StatusBadRequest, err) - return - } else if validResponse, ok := response.(UnionExampleResponseObject); ok { - if err := validResponse.VisitUnionExampleResponse(ctx); err != nil { - ctx.StopWithError(http.StatusBadRequest, err) - return - } - } else if response != nil { - ctx.Writef("Unexpected response type: %T", response) - return - } -} - -// Base64 encoded, gzipped, json marshaled Swagger object -var swaggerSpec = []string{ - - "H4sIAAAAAAAC/+xZTXPbNhP+Kzt431NKmrbjE2+NJ5O2aeuObJ86PkDESkJCAiiwFK3R6L93QEBfFq1K", - "qT4ynt5Ecr/wPLuLBTRlha6MVqjIsXzKLDqjlcP2oc+Fxb9qdOSfBLrCSkNSK5azD1z04rdZwizWjvdL", - "nKt7+UIrQtWqcmNKWXCvmn1xXn/KXDHCivtf/7c4YDn7X7YMJQtfXYbPvDIlstlslryI4O4zS9gIuUDb", - "Rht+Xq3bpolBljNHVqoh80aC2HWnmFSEQ7TemxeNQXiBeRz5lBmrDVqSAaMxL2vs9hTf6P4XLCisQKqB", - "3sTyViviUjkQcjBAi4ogggfehgNXG6MtoYD+BLyHgsChHaNlCSNJPjB2v/oeYsCOJWyM1gVHVxeXF5ee", - "L21QcSNZzt63rxJmOI3aBS0IMrqL91/u734H6YDXpCtOsuBlOYGKWzfiJQqQirQPsS7IXbDWk22J/1lE", - "7Y8RSp81bQJ90GJyjIRp83Ilna8vL0+Ul7OE3QRnXTYWQWUrBdaaGfC67MD8UX1VulGA1mobV5ZVdUnS", - "cEurXK2j/dtcZBfIF/aygbZVKjjxI6F+KE/nBj61WHJCsQMBvSC5Hw8r5o/Kwr/xc1YOYj/u7FP3I904", - "GOkGSINAXkIjaQRzxRcNVirg4KQalgjzoJJOMkuM296PSvTiWh68jaP3s2TNynPaNE3aFlBtS1SFFt9G", - "YcJkxYeYGTVcV/e2ObGc9SfkU3ZzgztQISeM8JkyU3Kptu/eJ2rp/yF9sMIO5eofpUWRekbSfqyP7sKN", - "5QVeyg8ac90EnIZKOl+l4aMb6boUwMuGT1zoD5sTRy+q+8mjLcyjjx3BgffJcrI1vu0xZEGtz6zzUPuA", - "z/SP1O6R+PvSd+qa2p+i9kwg0qFOv+Kk0VakhlteIaF12dTHOfO2hthh8o+FJBRcQR9B8QoF8AGhhU8a", - "oknXwU/w+0l/DiJLU+2BY/GQ/zllHrz2EMIS5h2wPOD3ko5kC8BPx6VqjmY46qZrrl5L+Cgyh87iwPmB", - "pIvjDvyCp96KxHmOTNtzc+Pwf4qk9ky+Pnj7lrDLsH3AweN77wJ1ePk6ZlFrF9i+cY7ZAcWxFKizytzs", - "aflsoDqDhRxIFGlcRRpie60l3GpVWKT1A4jfDJUmWBiD/gRohBAQaPfHBqGqHYHhzoGktouUMtwVCdxo", - "Ho/LyG6Dp4dlO93G6rsjcfruXIzeXF7tr/L+yHmzdpB4pR57v34MMvvemB3sxLLneetwfs9Uzo2kUbpy", - "pdxdwj8FgeWeXqAc+4lICbBItVUoYCz5/Bp0ozajgSWtXbNQCGM5Dc2vt/cZiJKttq5Zsu0K/OkNX9Ae", - "84+DU+VpreS2i/pH/xniDP1yb5BafafX8LwktIqTHOMPh7m/2bSiFd4N2kp7wXKyo4ent5dVs4SFf45C", - "C6pt6fsEkcmzLPzjdOEaPhyivZA640Z6FP4OAAD//0nTejA+HAAA", -} - -// GetSwagger returns the content of the embedded swagger specification file -// or error if failed to decode -func decodeSpec() ([]byte, error) { - zipped, err := base64.StdEncoding.DecodeString(strings.Join(swaggerSpec, "")) - if err != nil { - return nil, fmt.Errorf("error base64 decoding spec: %w", err) - } - zr, err := gzip.NewReader(bytes.NewReader(zipped)) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - var buf bytes.Buffer - _, err = buf.ReadFrom(zr) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - - return buf.Bytes(), nil -} - -var rawSpec = decodeSpecCached() - -// a naive cached of a decoded swagger spec -func decodeSpecCached() func() ([]byte, error) { - data, err := decodeSpec() - return func() ([]byte, error) { - return data, err - } -} - -// Constructs a synthetic filesystem for resolving external references when loading openapi specifications. -func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { - res := make(map[string]func() ([]byte, error)) - if len(pathToFile) > 0 { - res[pathToFile] = rawSpec - } - - return res -} - -// GetSwagger returns the Swagger specification corresponding to the generated code -// in this file. The external references of Swagger specification are resolved. -// The logic of resolving external references is tightly connected to "import-mapping" feature. -// Externally referenced files must be embedded in the corresponding golang packages. -// Urls can be supported but this task was out of the scope. -func GetSwagger() (swagger *openapi3.T, err error) { - resolvePath := PathToRawSpec("") - - loader := openapi3.NewLoader() - loader.IsExternalRefsAllowed = true - loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() - pathToFile = path.Clean(pathToFile) - getSpec, ok := resolvePath[pathToFile] - if !ok { - err1 := fmt.Errorf("path not found: %s", pathToFile) - return nil, err1 - } - return getSpec() - } - var specData []byte - specData, err = rawSpec() - if err != nil { - return - } - swagger, err = loader.LoadFromData(specData) - if err != nil { - return - } - return -} diff --git a/internal/test/strict-server/iris/server.go b/internal/test/strict-server/iris/server.go deleted file mode 100644 index f87df99759..0000000000 --- a/internal/test/strict-server/iris/server.go +++ /dev/null @@ -1,151 +0,0 @@ -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=server.cfg.yaml ../strict-schema.yaml -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=types.cfg.yaml ../strict-schema.yaml - -package api - -import ( - "context" - "encoding/json" - "io" - "mime/multipart" -) - -type StrictServer struct{} - -func (s StrictServer) JSONExample(ctx context.Context, request JSONExampleRequestObject) (JSONExampleResponseObject, error) { - return JSONExample200JSONResponse(*request.Body), nil -} - -func (s StrictServer) MultipartExample(ctx context.Context, request MultipartExampleRequestObject) (MultipartExampleResponseObject, error) { - return MultipartExample200MultipartResponse(func(writer *multipart.Writer) error { - for { - part, err := request.Body.NextPart() - if err == io.EOF { - return nil - } else if err != nil { - return err - } - w, err := writer.CreatePart(part.Header) - if err != nil { - return err - } - _, err = io.Copy(w, part) - if err != nil { - return err - } - if err = part.Close(); err != nil { - return err - } - } - }), nil -} - -func (s StrictServer) MultipartRelatedExample(ctx context.Context, request MultipartRelatedExampleRequestObject) (MultipartRelatedExampleResponseObject, error) { - return MultipartRelatedExample200MultipartResponse(func(writer *multipart.Writer) error { - for { - part, err := request.Body.NextPart() - if err == io.EOF { - return nil - } else if err != nil { - return err - } - w, err := writer.CreatePart(part.Header) - if err != nil { - return err - } - _, err = io.Copy(w, part) - if err != nil { - return err - } - if err = part.Close(); err != nil { - return err - } - } - }), nil -} - -func (s StrictServer) MultipleRequestAndResponseTypes(ctx context.Context, request MultipleRequestAndResponseTypesRequestObject) (MultipleRequestAndResponseTypesResponseObject, error) { - switch { - case request.Body != nil: - return MultipleRequestAndResponseTypes200ImagepngResponse{Body: request.Body}, nil - case request.JSONBody != nil: - return MultipleRequestAndResponseTypes200JSONResponse(*request.JSONBody), nil - case request.FormdataBody != nil: - return MultipleRequestAndResponseTypes200FormdataResponse(*request.FormdataBody), nil - case request.TextBody != nil: - return MultipleRequestAndResponseTypes200TextResponse(*request.TextBody), nil - case request.MultipartBody != nil: - return MultipleRequestAndResponseTypes200MultipartResponse(func(writer *multipart.Writer) error { - for { - part, err := request.MultipartBody.NextPart() - if err == io.EOF { - return nil - } else if err != nil { - return err - } - w, err := writer.CreatePart(part.Header) - if err != nil { - return err - } - _, err = io.Copy(w, part) - if err != nil { - return err - } - if err = part.Close(); err != nil { - return err - } - } - }), nil - default: - return MultipleRequestAndResponseTypes400Response{}, nil - } -} - -func (s StrictServer) TextExample(ctx context.Context, request TextExampleRequestObject) (TextExampleResponseObject, error) { - return TextExample200TextResponse(*request.Body), nil -} - -func (s StrictServer) UnknownExample(ctx context.Context, request UnknownExampleRequestObject) (UnknownExampleResponseObject, error) { - return UnknownExample200Videomp4Response{Body: request.Body}, nil -} - -func (s StrictServer) UnspecifiedContentType(ctx context.Context, request UnspecifiedContentTypeRequestObject) (UnspecifiedContentTypeResponseObject, error) { - return UnspecifiedContentType200VideoResponse{Body: request.Body, ContentType: request.ContentType}, nil -} - -func (s StrictServer) URLEncodedExample(ctx context.Context, request URLEncodedExampleRequestObject) (URLEncodedExampleResponseObject, error) { - return URLEncodedExample200FormdataResponse(*request.Body), nil -} - -func (s StrictServer) HeadersExample(ctx context.Context, request HeadersExampleRequestObject) (HeadersExampleResponseObject, error) { - return HeadersExample200JSONResponse{Body: *request.Body, Headers: HeadersExample200ResponseHeaders{Header1: request.Params.Header1, Header2: *request.Params.Header2}}, nil -} - -func (s StrictServer) ReusableResponses(ctx context.Context, request ReusableResponsesRequestObject) (ReusableResponsesResponseObject, error) { - return ReusableResponses200JSONResponse{ReusableresponseJSONResponse: ReusableresponseJSONResponse{Body: *request.Body}}, nil -} - -func (s StrictServer) RequiredJSONBody(ctx context.Context, request RequiredJSONBodyRequestObject) (RequiredJSONBodyResponseObject, error) { - return RequiredJSONBody200JSONResponse(*request.Body), nil -} - -func (s StrictServer) RequiredTextBody(ctx context.Context, request RequiredTextBodyRequestObject) (RequiredTextBodyResponseObject, error) { - return RequiredTextBody200TextResponse(*request.Body), nil -} - -func (s StrictServer) ReservedGoKeywordParameters(ctx context.Context, request ReservedGoKeywordParametersRequestObject) (ReservedGoKeywordParametersResponseObject, error) { - return ReservedGoKeywordParameters200TextResponse(""), nil -} - -func (s StrictServer) UnionExample(ctx context.Context, request UnionExampleRequestObject) (UnionExampleResponseObject, error) { - union, err := json.Marshal(*request.Body) - if err != nil { - return nil, err - } - - return UnionExample200JSONResponse{ - Body: struct{ union json.RawMessage }{ - union: union, - }, - }, nil -} diff --git a/internal/test/strict-server/iris/types.cfg.yaml b/internal/test/strict-server/iris/types.cfg.yaml deleted file mode 100644 index 2ed9740ea7..0000000000 --- a/internal/test/strict-server/iris/types.cfg.yaml +++ /dev/null @@ -1,5 +0,0 @@ -# yaml-language-server: $schema=../../../../configuration-schema.json -package: api -generate: - models: true -output: types.gen.go diff --git a/internal/test/strict-server/iris/types.gen.go b/internal/test/strict-server/iris/types.gen.go deleted file mode 100644 index fac014c4bb..0000000000 --- a/internal/test/strict-server/iris/types.gen.go +++ /dev/null @@ -1,69 +0,0 @@ -// Package api provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package api - -// Example defines model for example. -type Example struct { - Value *string `json:"value,omitempty"` -} - -// Reusableresponse defines model for reusableresponse. -type Reusableresponse = Example - -// MultipleRequestAndResponseTypesTextBody defines parameters for MultipleRequestAndResponseTypes. -type MultipleRequestAndResponseTypesTextBody = string - -// RequiredTextBodyTextBody defines parameters for RequiredTextBody. -type RequiredTextBodyTextBody = string - -// TextExampleTextBody defines parameters for TextExample. -type TextExampleTextBody = string - -// HeadersExampleParams defines parameters for HeadersExample. -type HeadersExampleParams struct { - Header1 string `json:"header1"` - Header2 *int `json:"header2,omitempty"` -} - -// JSONExampleJSONRequestBody defines body for JSONExample for application/json ContentType. -type JSONExampleJSONRequestBody = Example - -// MultipartExampleMultipartRequestBody defines body for MultipartExample for multipart/form-data ContentType. -type MultipartExampleMultipartRequestBody = Example - -// MultipartRelatedExampleMultipartRequestBody defines body for MultipartRelatedExample for multipart/related ContentType. -type MultipartRelatedExampleMultipartRequestBody = Example - -// MultipleRequestAndResponseTypesJSONRequestBody defines body for MultipleRequestAndResponseTypes for application/json ContentType. -type MultipleRequestAndResponseTypesJSONRequestBody = Example - -// MultipleRequestAndResponseTypesFormdataRequestBody defines body for MultipleRequestAndResponseTypes for application/x-www-form-urlencoded ContentType. -type MultipleRequestAndResponseTypesFormdataRequestBody = Example - -// MultipleRequestAndResponseTypesMultipartRequestBody defines body for MultipleRequestAndResponseTypes for multipart/form-data ContentType. -type MultipleRequestAndResponseTypesMultipartRequestBody = Example - -// MultipleRequestAndResponseTypesTextRequestBody defines body for MultipleRequestAndResponseTypes for text/plain ContentType. -type MultipleRequestAndResponseTypesTextRequestBody = MultipleRequestAndResponseTypesTextBody - -// RequiredJSONBodyJSONRequestBody defines body for RequiredJSONBody for application/json ContentType. -type RequiredJSONBodyJSONRequestBody = Example - -// RequiredTextBodyTextRequestBody defines body for RequiredTextBody for text/plain ContentType. -type RequiredTextBodyTextRequestBody = RequiredTextBodyTextBody - -// ReusableResponsesJSONRequestBody defines body for ReusableResponses for application/json ContentType. -type ReusableResponsesJSONRequestBody = Example - -// TextExampleTextRequestBody defines body for TextExample for text/plain ContentType. -type TextExampleTextRequestBody = TextExampleTextBody - -// URLEncodedExampleFormdataRequestBody defines body for URLEncodedExample for application/x-www-form-urlencoded ContentType. -type URLEncodedExampleFormdataRequestBody = Example - -// HeadersExampleJSONRequestBody defines body for HeadersExample for application/json ContentType. -type HeadersExampleJSONRequestBody = Example - -// UnionExampleJSONRequestBody defines body for UnionExample for application/json ContentType. -type UnionExampleJSONRequestBody = Example diff --git a/internal/test/strict-server/stdhttp/Makefile b/internal/test/strict-server/stdhttp/Makefile deleted file mode 100644 index 5ec0edd058..0000000000 --- a/internal/test/strict-server/stdhttp/Makefile +++ /dev/null @@ -1,17 +0,0 @@ -lint: - $(GOBIN)/golangci-lint run ./... - -lint-ci: - $(GOBIN)/golangci-lint run ./... --output.text.path=stdout --timeout=5m - -generate: - go generate ./... - -test: - go test -cover ./... - -tidy: - go mod tidy - -tidy-ci: - tidied -verbose diff --git a/internal/test/strict-server/stdhttp/go.mod b/internal/test/strict-server/stdhttp/go.mod deleted file mode 100644 index 19a1b1cfb5..0000000000 --- a/internal/test/strict-server/stdhttp/go.mod +++ /dev/null @@ -1,42 +0,0 @@ -module github.com/oapi-codegen/oapi-codegen/v2/internal/test/strict-server/stdhttp - -go 1.24.3 - -replace github.com/oapi-codegen/oapi-codegen/v2 => ../../../../ - -replace github.com/oapi-codegen/oapi-codegen/v2/internal/test => ../.. - -require ( - github.com/getkin/kin-openapi v0.133.0 - github.com/oapi-codegen/oapi-codegen/v2 v2.0.0-00010101000000-000000000000 - github.com/oapi-codegen/oapi-codegen/v2/internal/test v0.0.0-00010101000000-000000000000 - github.com/oapi-codegen/runtime v1.2.0 - github.com/oapi-codegen/testutil v1.1.0 - github.com/stretchr/testify v1.11.1 -) - -require ( - github.com/apapsch/go-jsonmerge/v2 v2.0.0 // indirect - github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect - github.com/dprotaso/go-yit v0.0.0-20220510233725-9ba8df137936 // indirect - github.com/go-openapi/jsonpointer v0.22.4 // indirect - github.com/go-openapi/swag/jsonname v0.25.4 // indirect - github.com/google/uuid v1.6.0 // indirect - github.com/josharian/intern v1.0.0 // indirect - github.com/mailru/easyjson v0.9.1 // indirect - github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 // indirect - github.com/oasdiff/yaml v0.0.0-20250309154309-f31be36b4037 // indirect - github.com/oasdiff/yaml3 v0.0.0-20250309153720-d2182401db90 // indirect - github.com/perimeterx/marshmallow v1.1.5 // indirect - github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect - github.com/speakeasy-api/jsonpath v0.6.0 // indirect - github.com/speakeasy-api/openapi-overlay v0.10.3 // indirect - github.com/vmware-labs/yaml-jsonpath v0.3.2 // indirect - github.com/woodsbury/decimal128 v1.4.0 // indirect - golang.org/x/mod v0.33.0 // indirect - golang.org/x/sync v0.19.0 // indirect - golang.org/x/text v0.34.0 // indirect - golang.org/x/tools v0.42.0 // indirect - gopkg.in/yaml.v2 v2.4.0 // indirect - gopkg.in/yaml.v3 v3.0.1 // indirect -) diff --git a/internal/test/strict-server/stdhttp/go.sum b/internal/test/strict-server/stdhttp/go.sum deleted file mode 100644 index 4680d9a4bb..0000000000 --- a/internal/test/strict-server/stdhttp/go.sum +++ /dev/null @@ -1,185 +0,0 @@ -github.com/RaveNoX/go-jsoncommentstrip v1.0.0/go.mod h1:78ihd09MekBnJnxpICcwzCMzGrKSKYe4AqU6PDYYpjk= -github.com/apapsch/go-jsonmerge/v2 v2.0.0 h1:axGnT1gRIfimI7gJifB699GoE/oq+F2MU7Dml6nw9rQ= -github.com/apapsch/go-jsonmerge/v2 v2.0.0/go.mod h1:lvDnEdqiQrp0O42VQGgmlKpxL1AP2+08jFMw88y4klk= -github.com/bmatcuk/doublestar v1.1.1/go.mod h1:UD6OnuiIn0yFxxA2le/rnRU1G4RaI4UvFv1sNto9p6w= -github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= -github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= -github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= -github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= -github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/dprotaso/go-yit v0.0.0-20191028211022-135eb7262960/go.mod h1:9HQzr9D/0PGwMEbC3d5AB7oi67+h4TsQqItC1GVYG58= -github.com/dprotaso/go-yit v0.0.0-20220510233725-9ba8df137936 h1:PRxIJD8XjimM5aTknUK9w6DHLDox2r2M3DI4i2pnd3w= -github.com/dprotaso/go-yit v0.0.0-20220510233725-9ba8df137936/go.mod h1:ttYvX5qlB+mlV1okblJqcSMtR4c52UKxDiX9GRBS8+Q= -github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= -github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4= -github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= -github.com/getkin/kin-openapi v0.133.0 h1:pJdmNohVIJ97r4AUFtEXRXwESr8b0bD721u/Tz6k8PQ= -github.com/getkin/kin-openapi v0.133.0/go.mod h1:boAciF6cXk5FhPqe/NQeBTeenbjqU4LhWBf09ILVvWE= -github.com/go-openapi/jsonpointer v0.22.4 h1:dZtK82WlNpVLDW2jlA1YCiVJFVqkED1MegOUy9kR5T4= -github.com/go-openapi/jsonpointer v0.22.4/go.mod h1:elX9+UgznpFhgBuaMQ7iu4lvvX1nvNsesQ3oxmYTw80= -github.com/go-openapi/swag/jsonname v0.25.4 h1:bZH0+MsS03MbnwBXYhuTttMOqk+5KcQ9869Vye1bNHI= -github.com/go-openapi/swag/jsonname v0.25.4/go.mod h1:GPVEk9CWVhNvWhZgrnvRA6utbAltopbKwDu8mXNUMag= -github.com/go-openapi/testify/v2 v2.0.2 h1:X999g3jeLcoY8qctY/c/Z8iBHTbwLz7R2WXd6Ub6wls= -github.com/go-openapi/testify/v2 v2.0.2/go.mod h1:HCPmvFFnheKK2BuwSA0TbbdxJ3I16pjwMkYkP4Ywn54= -github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE= -github.com/go-test/deep v1.0.8 h1:TDsG77qcSprGbC6vTN8OuXp5g+J+b5Pcguhf7Zt61VM= -github.com/go-test/deep v1.0.8/go.mod h1:5C2ZWiW0ErCdrYzpqxLbTX7MG14M9iiw8DgHncVwcsE= -github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= -github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= -github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= -github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= -github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= -github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= -github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= -github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= -github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= -github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= -github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= -github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= -github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= -github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= -github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= -github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= -github.com/juju/gnuflag v0.0.0-20171113085948-2ce1bb71843d/go.mod h1:2PavIy+JPciBPrBUjwbNvtwB6RQlve+hkpll6QSNmOE= -github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= -github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= -github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= -github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= -github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= -github.com/mailru/easyjson v0.9.1 h1:LbtsOm5WAswyWbvTEOqhypdPeZzHavpZx96/n553mR8= -github.com/mailru/easyjson v0.9.1/go.mod h1:1+xMtQp2MRNVL/V1bOzuP3aP8VNwRW55fQUto+XFtTU= -github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 h1:RWengNIwukTxcDr9M+97sNutRR1RKhG96O6jWumTTnw= -github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826/go.mod h1:TaXosZuwdSHYgviHp1DAtfrULt5eUgsSMsZf+YrPgl8= -github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= -github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE= -github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU= -github.com/oapi-codegen/runtime v1.2.0 h1:RvKc1CVS1QeKSNzO97FBQbSMZyQ8s6rZd+LpmzwHMP4= -github.com/oapi-codegen/runtime v1.2.0/go.mod h1:Y7ZhmmlE8ikZOmuHRRndiIm7nf3xcVv+YMweKgG1DT0= -github.com/oapi-codegen/testutil v1.1.0 h1:EufqpNg43acR3qzr3ObhXmWg3Sl2kwtRnUN5GYY4d5g= -github.com/oapi-codegen/testutil v1.1.0/go.mod h1:ttCaYbHvJtHuiyeBF0tPIX+4uhEPTeizXKx28okijLw= -github.com/oasdiff/yaml v0.0.0-20250309154309-f31be36b4037 h1:G7ERwszslrBzRxj//JalHPu/3yz+De2J+4aLtSRlHiY= -github.com/oasdiff/yaml v0.0.0-20250309154309-f31be36b4037/go.mod h1:2bpvgLBZEtENV5scfDFEtB/5+1M4hkQhDQrccEJ/qGw= -github.com/oasdiff/yaml3 v0.0.0-20250309153720-d2182401db90 h1:bQx3WeLcUWy+RletIKwUIt4x3t8n2SxavmoclizMb8c= -github.com/oasdiff/yaml3 v0.0.0-20250309153720-d2182401db90/go.mod h1:y5+oSEHCPT/DGrS++Wc/479ERge0zTFxaF8PbGKcg2o= -github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= -github.com/onsi/ginkgo v1.10.2/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= -github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= -github.com/onsi/ginkgo v1.16.4 h1:29JGrr5oVBm5ulCWet69zQkzWipVXIol6ygQUe/EzNc= -github.com/onsi/ginkgo v1.16.4/go.mod h1:dX+/inL/fNMqNlz0e9LfyB9TswhZpCVdJM/Z6Vvnwo0= -github.com/onsi/ginkgo/v2 v2.1.3/go.mod h1:vw5CSIxN1JObi/U8gcbwft7ZxR2dgaR70JSE3/PpL4c= -github.com/onsi/gomega v1.7.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= -github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= -github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= -github.com/onsi/gomega v1.17.0/go.mod h1:HnhC7FXeEQY45zxNK3PPoIUhzk/80Xly9PcubAlGdZY= -github.com/onsi/gomega v1.19.0 h1:4ieX6qQjPP/BfC3mpsAtIGGlxTWPeA3Inl/7DtXw1tw= -github.com/onsi/gomega v1.19.0/go.mod h1:LY+I3pBVzYsTBU1AnDwOSxaYi9WoWiqgwooUqq9yPro= -github.com/perimeterx/marshmallow v1.1.5 h1:a2LALqQ1BlHM8PZblsDdidgv1mWi1DgC2UmX50IvK2s= -github.com/perimeterx/marshmallow v1.1.5/go.mod h1:dsXbUu8CRzfYP5a87xpp0xq9S3u0Vchtcl8we9tYaXw= -github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= -github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/sergi/go-diff v1.1.0 h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0= -github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= -github.com/speakeasy-api/jsonpath v0.6.0 h1:IhtFOV9EbXplhyRqsVhHoBmmYjblIRh5D1/g8DHMXJ8= -github.com/speakeasy-api/jsonpath v0.6.0/go.mod h1:ymb2iSkyOycmzKwbEAYPJV/yi2rSmvBCLZJcyD+VVWw= -github.com/speakeasy-api/openapi-overlay v0.10.3 h1:70een4vwHyslIp796vM+ox6VISClhtXsCjrQNhxwvWs= -github.com/speakeasy-api/openapi-overlay v0.10.3/go.mod h1:RJjV0jbUHqXLS0/Mxv5XE7LAnJHqHw+01RDdpoGqiyY= -github.com/spkg/bom v0.0.0-20160624110644-59b7046e48ad/go.mod h1:qLr4V1qq6nMqFKkMo8ZTx3f+BZEkzsRUY10Xsm2mwU0= -github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= -github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= -github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= -github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= -github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= -github.com/ugorji/go/codec v1.3.0 h1:Qd2W2sQawAfG8XSvzwhBeoGq71zXOC/Q1E9y/wUcsUA= -github.com/ugorji/go/codec v1.3.0/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4= -github.com/vmware-labs/yaml-jsonpath v0.3.2 h1:/5QKeCBGdsInyDCyVNLbXyilb61MXGi9NP674f9Hobk= -github.com/vmware-labs/yaml-jsonpath v0.3.2/go.mod h1:U6whw1z03QyqgWdgXxvVnQ90zN1BWz5V+51Ewf8k+rQ= -github.com/woodsbury/decimal128 v1.4.0 h1:xJATj7lLu4f2oObouMt2tgGiElE5gO6mSWUjQsBgUlc= -github.com/woodsbury/decimal128 v1.4.0/go.mod h1:BP46FUrVjVhdTbKT+XuQh2xfQaGki9LMIRJSFuh6THU= -github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.33.0 h1:tHFzIWbBifEmbwtGz65eaWyGiGZatSrT9prnU8DbVL8= -golang.org/x/mod v0.33.0/go.mod h1:swjeQEj+6r7fODbD2cqrnje9PnziFuw4bmLbBZFrQ5w= -golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= -golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT/9KSuxbyM7479/AVlXFRxuMCk= -golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= -golang.org/x/net v0.50.0 h1:ucWh9eiCGyDR3vtzso0WMQinm2Dnt8cFMuQa9K33J60= -golang.org/x/net v0.50.0/go.mod h1:UgoSli3F/pBgdJBHCTc+tp3gmrU4XswgGRgtnwWTfyM= -golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4= -golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= -golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k= -golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= -golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= -golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= -golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk= -golang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA= -golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k= -golang.org/x/tools v0.42.0/go.mod h1:Ma6lCIwGZvHK6XtgbswSoWroEkhugApmsXyrUmBhfr0= -golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= -google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= -google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= -google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= -google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= -google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= -google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo= -gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= -gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= -gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= -gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= -gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= -gopkg.in/yaml.v3 v3.0.0-20191026110619-0b21df46bc1d/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= -gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/internal/test/strict-server/stdhttp/server.cfg.yaml b/internal/test/strict-server/stdhttp/server.cfg.yaml deleted file mode 100644 index fb4ed1a461..0000000000 --- a/internal/test/strict-server/stdhttp/server.cfg.yaml +++ /dev/null @@ -1,7 +0,0 @@ -# yaml-language-server: $schema=../../../../configuration-schema.json -package: api -generate: - std-http-server: true - strict-server: true - embedded-spec: true -output: server.gen.go diff --git a/internal/test/strict-server/stdhttp/server.gen.go b/internal/test/strict-server/stdhttp/server.gen.go deleted file mode 100644 index 2d6b8642ee..0000000000 --- a/internal/test/strict-server/stdhttp/server.gen.go +++ /dev/null @@ -1,1730 +0,0 @@ -//go:build go1.22 - -// Package api provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package api - -import ( - "bytes" - "compress/gzip" - "context" - "encoding/base64" - "encoding/json" - "errors" - "fmt" - "io" - "mime" - "mime/multipart" - "net/http" - "net/url" - "path" - "strings" - - "github.com/getkin/kin-openapi/openapi3" - "github.com/oapi-codegen/runtime" - strictnethttp "github.com/oapi-codegen/runtime/strictmiddleware/nethttp" -) - -// ServerInterface represents all server handlers. -type ServerInterface interface { - - // (POST /json) - JSONExample(w http.ResponseWriter, r *http.Request) - - // (POST /multipart) - MultipartExample(w http.ResponseWriter, r *http.Request) - - // (POST /multipart-related) - MultipartRelatedExample(w http.ResponseWriter, r *http.Request) - - // (POST /multiple) - MultipleRequestAndResponseTypes(w http.ResponseWriter, r *http.Request) - - // (POST /required-json-body) - RequiredJSONBody(w http.ResponseWriter, r *http.Request) - - // (POST /required-text-body) - RequiredTextBody(w http.ResponseWriter, r *http.Request) - - // (GET /reserved-go-keyword-parameters/{type}) - ReservedGoKeywordParameters(w http.ResponseWriter, r *http.Request, pType string) - - // (POST /reusable-responses) - ReusableResponses(w http.ResponseWriter, r *http.Request) - - // (POST /text) - TextExample(w http.ResponseWriter, r *http.Request) - - // (POST /unknown) - UnknownExample(w http.ResponseWriter, r *http.Request) - - // (POST /unspecified-content-type) - UnspecifiedContentType(w http.ResponseWriter, r *http.Request) - - // (POST /urlencoded) - URLEncodedExample(w http.ResponseWriter, r *http.Request) - - // (POST /with-headers) - HeadersExample(w http.ResponseWriter, r *http.Request, params HeadersExampleParams) - - // (POST /with-union) - UnionExample(w http.ResponseWriter, r *http.Request) -} - -// ServerInterfaceWrapper converts contexts to parameters. -type ServerInterfaceWrapper struct { - Handler ServerInterface - HandlerMiddlewares []MiddlewareFunc - ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) -} - -type MiddlewareFunc func(http.Handler) http.Handler - -// JSONExample operation middleware -func (siw *ServerInterfaceWrapper) JSONExample(w http.ResponseWriter, r *http.Request) { - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.JSONExample(w, r) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -// MultipartExample operation middleware -func (siw *ServerInterfaceWrapper) MultipartExample(w http.ResponseWriter, r *http.Request) { - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.MultipartExample(w, r) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -// MultipartRelatedExample operation middleware -func (siw *ServerInterfaceWrapper) MultipartRelatedExample(w http.ResponseWriter, r *http.Request) { - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.MultipartRelatedExample(w, r) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -// MultipleRequestAndResponseTypes operation middleware -func (siw *ServerInterfaceWrapper) MultipleRequestAndResponseTypes(w http.ResponseWriter, r *http.Request) { - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.MultipleRequestAndResponseTypes(w, r) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -// RequiredJSONBody operation middleware -func (siw *ServerInterfaceWrapper) RequiredJSONBody(w http.ResponseWriter, r *http.Request) { - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.RequiredJSONBody(w, r) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -// RequiredTextBody operation middleware -func (siw *ServerInterfaceWrapper) RequiredTextBody(w http.ResponseWriter, r *http.Request) { - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.RequiredTextBody(w, r) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -// ReservedGoKeywordParameters operation middleware -func (siw *ServerInterfaceWrapper) ReservedGoKeywordParameters(w http.ResponseWriter, r *http.Request) { - - var err error - - // ------------- Path parameter "type" ------------- - var pType string - - err = runtime.BindStyledParameterWithOptions("simple", "type", r.PathValue("type"), &pType, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) - if err != nil { - siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "type", Err: err}) - return - } - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.ReservedGoKeywordParameters(w, r, pType) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -// ReusableResponses operation middleware -func (siw *ServerInterfaceWrapper) ReusableResponses(w http.ResponseWriter, r *http.Request) { - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.ReusableResponses(w, r) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -// TextExample operation middleware -func (siw *ServerInterfaceWrapper) TextExample(w http.ResponseWriter, r *http.Request) { - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.TextExample(w, r) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -// UnknownExample operation middleware -func (siw *ServerInterfaceWrapper) UnknownExample(w http.ResponseWriter, r *http.Request) { - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.UnknownExample(w, r) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -// UnspecifiedContentType operation middleware -func (siw *ServerInterfaceWrapper) UnspecifiedContentType(w http.ResponseWriter, r *http.Request) { - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.UnspecifiedContentType(w, r) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -// URLEncodedExample operation middleware -func (siw *ServerInterfaceWrapper) URLEncodedExample(w http.ResponseWriter, r *http.Request) { - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.URLEncodedExample(w, r) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -// HeadersExample operation middleware -func (siw *ServerInterfaceWrapper) HeadersExample(w http.ResponseWriter, r *http.Request) { - - var err error - - // Parameter object where we will unmarshal all parameters from the context - var params HeadersExampleParams - - headers := r.Header - - // ------------- Required header parameter "header1" ------------- - if valueList, found := headers[http.CanonicalHeaderKey("header1")]; found { - var Header1 string - n := len(valueList) - if n != 1 { - siw.ErrorHandlerFunc(w, r, &TooManyValuesForParamError{ParamName: "header1", Count: n}) - return - } - - err = runtime.BindStyledParameterWithOptions("simple", "header1", valueList[0], &Header1, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: true, Type: "string", Format: ""}) - if err != nil { - siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "header1", Err: err}) - return - } - - params.Header1 = Header1 - - } else { - err := fmt.Errorf("Header parameter header1 is required, but not found") - siw.ErrorHandlerFunc(w, r, &RequiredHeaderError{ParamName: "header1", Err: err}) - return - } - - // ------------- Optional header parameter "header2" ------------- - if valueList, found := headers[http.CanonicalHeaderKey("header2")]; found { - var Header2 int - n := len(valueList) - if n != 1 { - siw.ErrorHandlerFunc(w, r, &TooManyValuesForParamError{ParamName: "header2", Count: n}) - return - } - - err = runtime.BindStyledParameterWithOptions("simple", "header2", valueList[0], &Header2, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: ""}) - if err != nil { - siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "header2", Err: err}) - return - } - - params.Header2 = &Header2 - - } - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.HeadersExample(w, r, params) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -// UnionExample operation middleware -func (siw *ServerInterfaceWrapper) UnionExample(w http.ResponseWriter, r *http.Request) { - - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - siw.Handler.UnionExample(w, r) - })) - - for _, middleware := range siw.HandlerMiddlewares { - handler = middleware(handler) - } - - handler.ServeHTTP(w, r) -} - -type UnescapedCookieParamError struct { - ParamName string - Err error -} - -func (e *UnescapedCookieParamError) Error() string { - return fmt.Sprintf("error unescaping cookie parameter '%s'", e.ParamName) -} - -func (e *UnescapedCookieParamError) Unwrap() error { - return e.Err -} - -type UnmarshalingParamError struct { - ParamName string - Err error -} - -func (e *UnmarshalingParamError) Error() string { - return fmt.Sprintf("Error unmarshaling parameter %s as JSON: %s", e.ParamName, e.Err.Error()) -} - -func (e *UnmarshalingParamError) Unwrap() error { - return e.Err -} - -type RequiredParamError struct { - ParamName string -} - -func (e *RequiredParamError) Error() string { - return fmt.Sprintf("Query argument %s is required, but not found", e.ParamName) -} - -type RequiredHeaderError struct { - ParamName string - Err error -} - -func (e *RequiredHeaderError) Error() string { - return fmt.Sprintf("Header parameter %s is required, but not found", e.ParamName) -} - -func (e *RequiredHeaderError) Unwrap() error { - return e.Err -} - -type InvalidParamFormatError struct { - ParamName string - Err error -} - -func (e *InvalidParamFormatError) Error() string { - return fmt.Sprintf("Invalid format for parameter %s: %s", e.ParamName, e.Err.Error()) -} - -func (e *InvalidParamFormatError) Unwrap() error { - return e.Err -} - -type TooManyValuesForParamError struct { - ParamName string - Count int -} - -func (e *TooManyValuesForParamError) Error() string { - return fmt.Sprintf("Expected one value for %s, got %d", e.ParamName, e.Count) -} - -// Handler creates http.Handler with routing matching OpenAPI spec. -func Handler(si ServerInterface) http.Handler { - return HandlerWithOptions(si, StdHTTPServerOptions{}) -} - -// ServeMux is an abstraction of http.ServeMux. -type ServeMux interface { - HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request)) - ServeHTTP(w http.ResponseWriter, r *http.Request) -} - -type StdHTTPServerOptions struct { - BaseURL string - BaseRouter ServeMux - Middlewares []MiddlewareFunc - ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) -} - -// HandlerFromMux creates http.Handler with routing matching OpenAPI spec based on the provided mux. -func HandlerFromMux(si ServerInterface, m ServeMux) http.Handler { - return HandlerWithOptions(si, StdHTTPServerOptions{ - BaseRouter: m, - }) -} - -func HandlerFromMuxWithBaseURL(si ServerInterface, m ServeMux, baseURL string) http.Handler { - return HandlerWithOptions(si, StdHTTPServerOptions{ - BaseURL: baseURL, - BaseRouter: m, - }) -} - -// HandlerWithOptions creates http.Handler with additional options -func HandlerWithOptions(si ServerInterface, options StdHTTPServerOptions) http.Handler { - m := options.BaseRouter - - if m == nil { - m = http.NewServeMux() - } - if options.ErrorHandlerFunc == nil { - options.ErrorHandlerFunc = func(w http.ResponseWriter, r *http.Request, err error) { - http.Error(w, err.Error(), http.StatusBadRequest) - } - } - - wrapper := ServerInterfaceWrapper{ - Handler: si, - HandlerMiddlewares: options.Middlewares, - ErrorHandlerFunc: options.ErrorHandlerFunc, - } - - m.HandleFunc("POST "+options.BaseURL+"/json", wrapper.JSONExample) - m.HandleFunc("POST "+options.BaseURL+"/multipart", wrapper.MultipartExample) - m.HandleFunc("POST "+options.BaseURL+"/multipart-related", wrapper.MultipartRelatedExample) - m.HandleFunc("POST "+options.BaseURL+"/multiple", wrapper.MultipleRequestAndResponseTypes) - m.HandleFunc("POST "+options.BaseURL+"/required-json-body", wrapper.RequiredJSONBody) - m.HandleFunc("POST "+options.BaseURL+"/required-text-body", wrapper.RequiredTextBody) - m.HandleFunc("GET "+options.BaseURL+"/reserved-go-keyword-parameters/{type}", wrapper.ReservedGoKeywordParameters) - m.HandleFunc("POST "+options.BaseURL+"/reusable-responses", wrapper.ReusableResponses) - m.HandleFunc("POST "+options.BaseURL+"/text", wrapper.TextExample) - m.HandleFunc("POST "+options.BaseURL+"/unknown", wrapper.UnknownExample) - m.HandleFunc("POST "+options.BaseURL+"/unspecified-content-type", wrapper.UnspecifiedContentType) - m.HandleFunc("POST "+options.BaseURL+"/urlencoded", wrapper.URLEncodedExample) - m.HandleFunc("POST "+options.BaseURL+"/with-headers", wrapper.HeadersExample) - m.HandleFunc("POST "+options.BaseURL+"/with-union", wrapper.UnionExample) - - return m -} - -type BadrequestResponse struct { -} - -type ReusableresponseResponseHeaders struct { - Header1 string - Header2 int -} -type ReusableresponseJSONResponse struct { - Body Example - - Headers ReusableresponseResponseHeaders -} - -type JSONExampleRequestObject struct { - Body *JSONExampleJSONRequestBody -} - -type JSONExampleResponseObject interface { - VisitJSONExampleResponse(w http.ResponseWriter) error -} - -type JSONExample200JSONResponse Example - -func (response JSONExample200JSONResponse) VisitJSONExampleResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(200) - - return json.NewEncoder(w).Encode(response) -} - -type JSONExample400Response = BadrequestResponse - -func (response JSONExample400Response) VisitJSONExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type JSONExampledefaultResponse struct { - StatusCode int -} - -func (response JSONExampledefaultResponse) VisitJSONExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -type MultipartExampleRequestObject struct { - Body *multipart.Reader -} - -type MultipartExampleResponseObject interface { - VisitMultipartExampleResponse(w http.ResponseWriter) error -} - -type MultipartExample200MultipartResponse func(writer *multipart.Writer) error - -func (response MultipartExample200MultipartResponse) VisitMultipartExampleResponse(w http.ResponseWriter) error { - writer := multipart.NewWriter(w) - w.Header().Set("Content-Type", writer.FormDataContentType()) - w.WriteHeader(200) - - defer writer.Close() - return response(writer) -} - -type MultipartExample400Response = BadrequestResponse - -func (response MultipartExample400Response) VisitMultipartExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type MultipartExampledefaultResponse struct { - StatusCode int -} - -func (response MultipartExampledefaultResponse) VisitMultipartExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -type MultipartRelatedExampleRequestObject struct { - Body *multipart.Reader -} - -type MultipartRelatedExampleResponseObject interface { - VisitMultipartRelatedExampleResponse(w http.ResponseWriter) error -} - -type MultipartRelatedExample200MultipartResponse func(writer *multipart.Writer) error - -func (response MultipartRelatedExample200MultipartResponse) VisitMultipartRelatedExampleResponse(w http.ResponseWriter) error { - writer := multipart.NewWriter(w) - w.Header().Set("Content-Type", mime.FormatMediaType("multipart/related", map[string]string{"boundary": writer.Boundary()})) - w.WriteHeader(200) - - defer writer.Close() - return response(writer) -} - -type MultipartRelatedExample400Response = BadrequestResponse - -func (response MultipartRelatedExample400Response) VisitMultipartRelatedExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type MultipartRelatedExampledefaultResponse struct { - StatusCode int -} - -func (response MultipartRelatedExampledefaultResponse) VisitMultipartRelatedExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -type MultipleRequestAndResponseTypesRequestObject struct { - JSONBody *MultipleRequestAndResponseTypesJSONRequestBody - FormdataBody *MultipleRequestAndResponseTypesFormdataRequestBody - Body io.Reader - MultipartBody *multipart.Reader - TextBody *MultipleRequestAndResponseTypesTextRequestBody -} - -type MultipleRequestAndResponseTypesResponseObject interface { - VisitMultipleRequestAndResponseTypesResponse(w http.ResponseWriter) error -} - -type MultipleRequestAndResponseTypes200JSONResponse Example - -func (response MultipleRequestAndResponseTypes200JSONResponse) VisitMultipleRequestAndResponseTypesResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(200) - - return json.NewEncoder(w).Encode(response) -} - -type MultipleRequestAndResponseTypes200FormdataResponse Example - -func (response MultipleRequestAndResponseTypes200FormdataResponse) VisitMultipleRequestAndResponseTypesResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/x-www-form-urlencoded") - w.WriteHeader(200) - - if form, err := runtime.MarshalForm(response, nil); err != nil { - return err - } else { - _, err := w.Write([]byte(form.Encode())) - return err - } -} - -type MultipleRequestAndResponseTypes200ImagepngResponse struct { - Body io.Reader - ContentLength int64 -} - -func (response MultipleRequestAndResponseTypes200ImagepngResponse) VisitMultipleRequestAndResponseTypesResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "image/png") - if response.ContentLength != 0 { - w.Header().Set("Content-Length", fmt.Sprint(response.ContentLength)) - } - w.WriteHeader(200) - - if closer, ok := response.Body.(io.ReadCloser); ok { - defer closer.Close() - } - _, err := io.Copy(w, response.Body) - return err -} - -type MultipleRequestAndResponseTypes200MultipartResponse func(writer *multipart.Writer) error - -func (response MultipleRequestAndResponseTypes200MultipartResponse) VisitMultipleRequestAndResponseTypesResponse(w http.ResponseWriter) error { - writer := multipart.NewWriter(w) - w.Header().Set("Content-Type", writer.FormDataContentType()) - w.WriteHeader(200) - - defer writer.Close() - return response(writer) -} - -type MultipleRequestAndResponseTypes200TextResponse string - -func (response MultipleRequestAndResponseTypes200TextResponse) VisitMultipleRequestAndResponseTypesResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "text/plain") - w.WriteHeader(200) - - _, err := w.Write([]byte(response)) - return err -} - -type MultipleRequestAndResponseTypes400Response = BadrequestResponse - -func (response MultipleRequestAndResponseTypes400Response) VisitMultipleRequestAndResponseTypesResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type RequiredJSONBodyRequestObject struct { - Body *RequiredJSONBodyJSONRequestBody -} - -type RequiredJSONBodyResponseObject interface { - VisitRequiredJSONBodyResponse(w http.ResponseWriter) error -} - -type RequiredJSONBody200JSONResponse Example - -func (response RequiredJSONBody200JSONResponse) VisitRequiredJSONBodyResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(200) - - return json.NewEncoder(w).Encode(response) -} - -type RequiredJSONBody400Response = BadrequestResponse - -func (response RequiredJSONBody400Response) VisitRequiredJSONBodyResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type RequiredJSONBodydefaultResponse struct { - StatusCode int -} - -func (response RequiredJSONBodydefaultResponse) VisitRequiredJSONBodyResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -type RequiredTextBodyRequestObject struct { - Body *RequiredTextBodyTextRequestBody -} - -type RequiredTextBodyResponseObject interface { - VisitRequiredTextBodyResponse(w http.ResponseWriter) error -} - -type RequiredTextBody200TextResponse string - -func (response RequiredTextBody200TextResponse) VisitRequiredTextBodyResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "text/plain") - w.WriteHeader(200) - - _, err := w.Write([]byte(response)) - return err -} - -type RequiredTextBody400Response = BadrequestResponse - -func (response RequiredTextBody400Response) VisitRequiredTextBodyResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type RequiredTextBodydefaultResponse struct { - StatusCode int -} - -func (response RequiredTextBodydefaultResponse) VisitRequiredTextBodyResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -type ReservedGoKeywordParametersRequestObject struct { - Type string `json:"type"` -} - -type ReservedGoKeywordParametersResponseObject interface { - VisitReservedGoKeywordParametersResponse(w http.ResponseWriter) error -} - -type ReservedGoKeywordParameters200TextResponse string - -func (response ReservedGoKeywordParameters200TextResponse) VisitReservedGoKeywordParametersResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "text/plain") - w.WriteHeader(200) - - _, err := w.Write([]byte(response)) - return err -} - -type ReusableResponsesRequestObject struct { - Body *ReusableResponsesJSONRequestBody -} - -type ReusableResponsesResponseObject interface { - VisitReusableResponsesResponse(w http.ResponseWriter) error -} - -type ReusableResponses200JSONResponse struct{ ReusableresponseJSONResponse } - -func (response ReusableResponses200JSONResponse) VisitReusableResponsesResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/json") - w.Header().Set("header1", fmt.Sprint(response.Headers.Header1)) - w.Header().Set("header2", fmt.Sprint(response.Headers.Header2)) - w.WriteHeader(200) - - return json.NewEncoder(w).Encode(response.Body) -} - -type ReusableResponses400Response = BadrequestResponse - -func (response ReusableResponses400Response) VisitReusableResponsesResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type ReusableResponsesdefaultResponse struct { - StatusCode int -} - -func (response ReusableResponsesdefaultResponse) VisitReusableResponsesResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -type TextExampleRequestObject struct { - Body *TextExampleTextRequestBody -} - -type TextExampleResponseObject interface { - VisitTextExampleResponse(w http.ResponseWriter) error -} - -type TextExample200TextResponse string - -func (response TextExample200TextResponse) VisitTextExampleResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "text/plain") - w.WriteHeader(200) - - _, err := w.Write([]byte(response)) - return err -} - -type TextExample400Response = BadrequestResponse - -func (response TextExample400Response) VisitTextExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type TextExampledefaultResponse struct { - StatusCode int -} - -func (response TextExampledefaultResponse) VisitTextExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -type UnknownExampleRequestObject struct { - Body io.Reader -} - -type UnknownExampleResponseObject interface { - VisitUnknownExampleResponse(w http.ResponseWriter) error -} - -type UnknownExample200Videomp4Response struct { - Body io.Reader - ContentLength int64 -} - -func (response UnknownExample200Videomp4Response) VisitUnknownExampleResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "video/mp4") - if response.ContentLength != 0 { - w.Header().Set("Content-Length", fmt.Sprint(response.ContentLength)) - } - w.WriteHeader(200) - - if closer, ok := response.Body.(io.ReadCloser); ok { - defer closer.Close() - } - _, err := io.Copy(w, response.Body) - return err -} - -type UnknownExample400Response = BadrequestResponse - -func (response UnknownExample400Response) VisitUnknownExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type UnknownExampledefaultResponse struct { - StatusCode int -} - -func (response UnknownExampledefaultResponse) VisitUnknownExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -type UnspecifiedContentTypeRequestObject struct { - ContentType string - Body io.Reader -} - -type UnspecifiedContentTypeResponseObject interface { - VisitUnspecifiedContentTypeResponse(w http.ResponseWriter) error -} - -type UnspecifiedContentType200VideoResponse struct { - Body io.Reader - ContentType string - ContentLength int64 -} - -func (response UnspecifiedContentType200VideoResponse) VisitUnspecifiedContentTypeResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", response.ContentType) - if response.ContentLength != 0 { - w.Header().Set("Content-Length", fmt.Sprint(response.ContentLength)) - } - w.WriteHeader(200) - - if closer, ok := response.Body.(io.ReadCloser); ok { - defer closer.Close() - } - _, err := io.Copy(w, response.Body) - return err -} - -type UnspecifiedContentType400Response = BadrequestResponse - -func (response UnspecifiedContentType400Response) VisitUnspecifiedContentTypeResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type UnspecifiedContentType401Response struct { -} - -func (response UnspecifiedContentType401Response) VisitUnspecifiedContentTypeResponse(w http.ResponseWriter) error { - w.WriteHeader(401) - return nil -} - -type UnspecifiedContentType403Response struct { -} - -func (response UnspecifiedContentType403Response) VisitUnspecifiedContentTypeResponse(w http.ResponseWriter) error { - w.WriteHeader(403) - return nil -} - -type UnspecifiedContentTypedefaultResponse struct { - StatusCode int -} - -func (response UnspecifiedContentTypedefaultResponse) VisitUnspecifiedContentTypeResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -type URLEncodedExampleRequestObject struct { - Body *URLEncodedExampleFormdataRequestBody -} - -type URLEncodedExampleResponseObject interface { - VisitURLEncodedExampleResponse(w http.ResponseWriter) error -} - -type URLEncodedExample200FormdataResponse Example - -func (response URLEncodedExample200FormdataResponse) VisitURLEncodedExampleResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/x-www-form-urlencoded") - w.WriteHeader(200) - - if form, err := runtime.MarshalForm(response, nil); err != nil { - return err - } else { - _, err := w.Write([]byte(form.Encode())) - return err - } -} - -type URLEncodedExample400Response = BadrequestResponse - -func (response URLEncodedExample400Response) VisitURLEncodedExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type URLEncodedExampledefaultResponse struct { - StatusCode int -} - -func (response URLEncodedExampledefaultResponse) VisitURLEncodedExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -type HeadersExampleRequestObject struct { - Params HeadersExampleParams - Body *HeadersExampleJSONRequestBody -} - -type HeadersExampleResponseObject interface { - VisitHeadersExampleResponse(w http.ResponseWriter) error -} - -type HeadersExample200ResponseHeaders struct { - Header1 string - Header2 int -} - -type HeadersExample200JSONResponse struct { - Body Example - Headers HeadersExample200ResponseHeaders -} - -func (response HeadersExample200JSONResponse) VisitHeadersExampleResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/json") - w.Header().Set("header1", fmt.Sprint(response.Headers.Header1)) - w.Header().Set("header2", fmt.Sprint(response.Headers.Header2)) - w.WriteHeader(200) - - return json.NewEncoder(w).Encode(response.Body) -} - -type HeadersExample400Response = BadrequestResponse - -func (response HeadersExample400Response) VisitHeadersExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type HeadersExampledefaultResponse struct { - StatusCode int -} - -func (response HeadersExampledefaultResponse) VisitHeadersExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -type UnionExampleRequestObject struct { - Body *UnionExampleJSONRequestBody -} - -type UnionExampleResponseObject interface { - VisitUnionExampleResponse(w http.ResponseWriter) error -} - -type UnionExample200ResponseHeaders struct { - Header1 string - Header2 int -} - -type UnionExample200ApplicationAlternativePlusJSONResponse struct { - Body Example - Headers UnionExample200ResponseHeaders -} - -func (response UnionExample200ApplicationAlternativePlusJSONResponse) VisitUnionExampleResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/alternative+json") - w.Header().Set("header1", fmt.Sprint(response.Headers.Header1)) - w.Header().Set("header2", fmt.Sprint(response.Headers.Header2)) - w.WriteHeader(200) - - return json.NewEncoder(w).Encode(response.Body) -} - -type UnionExample200JSONResponse struct { - Body struct { - union json.RawMessage - } - Headers UnionExample200ResponseHeaders -} - -func (response UnionExample200JSONResponse) VisitUnionExampleResponse(w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/json") - w.Header().Set("header1", fmt.Sprint(response.Headers.Header1)) - w.Header().Set("header2", fmt.Sprint(response.Headers.Header2)) - w.WriteHeader(200) - - return json.NewEncoder(w).Encode(response.Body.union) -} - -type UnionExample400Response = BadrequestResponse - -func (response UnionExample400Response) VisitUnionExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(400) - return nil -} - -type UnionExampledefaultResponse struct { - StatusCode int -} - -func (response UnionExampledefaultResponse) VisitUnionExampleResponse(w http.ResponseWriter) error { - w.WriteHeader(response.StatusCode) - return nil -} - -// StrictServerInterface represents all server handlers. -type StrictServerInterface interface { - - // (POST /json) - JSONExample(ctx context.Context, request JSONExampleRequestObject) (JSONExampleResponseObject, error) - - // (POST /multipart) - MultipartExample(ctx context.Context, request MultipartExampleRequestObject) (MultipartExampleResponseObject, error) - - // (POST /multipart-related) - MultipartRelatedExample(ctx context.Context, request MultipartRelatedExampleRequestObject) (MultipartRelatedExampleResponseObject, error) - - // (POST /multiple) - MultipleRequestAndResponseTypes(ctx context.Context, request MultipleRequestAndResponseTypesRequestObject) (MultipleRequestAndResponseTypesResponseObject, error) - - // (POST /required-json-body) - RequiredJSONBody(ctx context.Context, request RequiredJSONBodyRequestObject) (RequiredJSONBodyResponseObject, error) - - // (POST /required-text-body) - RequiredTextBody(ctx context.Context, request RequiredTextBodyRequestObject) (RequiredTextBodyResponseObject, error) - - // (GET /reserved-go-keyword-parameters/{type}) - ReservedGoKeywordParameters(ctx context.Context, request ReservedGoKeywordParametersRequestObject) (ReservedGoKeywordParametersResponseObject, error) - - // (POST /reusable-responses) - ReusableResponses(ctx context.Context, request ReusableResponsesRequestObject) (ReusableResponsesResponseObject, error) - - // (POST /text) - TextExample(ctx context.Context, request TextExampleRequestObject) (TextExampleResponseObject, error) - - // (POST /unknown) - UnknownExample(ctx context.Context, request UnknownExampleRequestObject) (UnknownExampleResponseObject, error) - - // (POST /unspecified-content-type) - UnspecifiedContentType(ctx context.Context, request UnspecifiedContentTypeRequestObject) (UnspecifiedContentTypeResponseObject, error) - - // (POST /urlencoded) - URLEncodedExample(ctx context.Context, request URLEncodedExampleRequestObject) (URLEncodedExampleResponseObject, error) - - // (POST /with-headers) - HeadersExample(ctx context.Context, request HeadersExampleRequestObject) (HeadersExampleResponseObject, error) - - // (POST /with-union) - UnionExample(ctx context.Context, request UnionExampleRequestObject) (UnionExampleResponseObject, error) -} - -type StrictHandlerFunc = strictnethttp.StrictHTTPHandlerFunc -type StrictMiddlewareFunc = strictnethttp.StrictHTTPMiddlewareFunc - -type StrictHTTPServerOptions struct { - RequestErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) - ResponseErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) -} - -func NewStrictHandler(ssi StrictServerInterface, middlewares []StrictMiddlewareFunc) ServerInterface { - return &strictHandler{ssi: ssi, middlewares: middlewares, options: StrictHTTPServerOptions{ - RequestErrorHandlerFunc: func(w http.ResponseWriter, r *http.Request, err error) { - http.Error(w, err.Error(), http.StatusBadRequest) - }, - ResponseErrorHandlerFunc: func(w http.ResponseWriter, r *http.Request, err error) { - http.Error(w, err.Error(), http.StatusInternalServerError) - }, - }} -} - -func NewStrictHandlerWithOptions(ssi StrictServerInterface, middlewares []StrictMiddlewareFunc, options StrictHTTPServerOptions) ServerInterface { - return &strictHandler{ssi: ssi, middlewares: middlewares, options: options} -} - -type strictHandler struct { - ssi StrictServerInterface - middlewares []StrictMiddlewareFunc - options StrictHTTPServerOptions -} - -// JSONExample operation middleware -func (sh *strictHandler) JSONExample(w http.ResponseWriter, r *http.Request) { - var request JSONExampleRequestObject - - var body JSONExampleJSONRequestBody - if err := json.NewDecoder(r.Body).Decode(&body); err != nil { - if !errors.Is(err, io.EOF) { - sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't decode JSON body: %w", err)) - return - } - } else { - request.Body = &body - } - - handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { - return sh.ssi.JSONExample(ctx, request.(JSONExampleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "JSONExample") - } - - response, err := handler(r.Context(), w, r, request) - - if err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } else if validResponse, ok := response.(JSONExampleResponseObject); ok { - if err := validResponse.VisitJSONExampleResponse(w); err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } - } else if response != nil { - sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) - } -} - -// MultipartExample operation middleware -func (sh *strictHandler) MultipartExample(w http.ResponseWriter, r *http.Request) { - var request MultipartExampleRequestObject - - if reader, err := r.MultipartReader(); err != nil { - sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't decode multipart body: %w", err)) - return - } else { - request.Body = reader - } - - handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { - return sh.ssi.MultipartExample(ctx, request.(MultipartExampleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "MultipartExample") - } - - response, err := handler(r.Context(), w, r, request) - - if err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } else if validResponse, ok := response.(MultipartExampleResponseObject); ok { - if err := validResponse.VisitMultipartExampleResponse(w); err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } - } else if response != nil { - sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) - } -} - -// MultipartRelatedExample operation middleware -func (sh *strictHandler) MultipartRelatedExample(w http.ResponseWriter, r *http.Request) { - var request MultipartRelatedExampleRequestObject - - if _, params, err := mime.ParseMediaType(r.Header.Get("Content-Type")); err != nil { - sh.options.RequestErrorHandlerFunc(w, r, err) - return - } else if boundary := params["boundary"]; boundary == "" { - sh.options.RequestErrorHandlerFunc(w, r, http.ErrMissingBoundary) - return - } else { - request.Body = multipart.NewReader(r.Body, boundary) - } - - handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { - return sh.ssi.MultipartRelatedExample(ctx, request.(MultipartRelatedExampleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "MultipartRelatedExample") - } - - response, err := handler(r.Context(), w, r, request) - - if err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } else if validResponse, ok := response.(MultipartRelatedExampleResponseObject); ok { - if err := validResponse.VisitMultipartRelatedExampleResponse(w); err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } - } else if response != nil { - sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) - } -} - -// MultipleRequestAndResponseTypes operation middleware -func (sh *strictHandler) MultipleRequestAndResponseTypes(w http.ResponseWriter, r *http.Request) { - var request MultipleRequestAndResponseTypesRequestObject - - if strings.HasPrefix(r.Header.Get("Content-Type"), "application/json") { - - var body MultipleRequestAndResponseTypesJSONRequestBody - if err := json.NewDecoder(r.Body).Decode(&body); err != nil { - if !errors.Is(err, io.EOF) { - sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't decode JSON body: %w", err)) - return - } - } else { - request.JSONBody = &body - } - } - if strings.HasPrefix(r.Header.Get("Content-Type"), "application/x-www-form-urlencoded") { - if err := r.ParseForm(); err != nil { - sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't decode formdata: %w", err)) - return - } - var body MultipleRequestAndResponseTypesFormdataRequestBody - if err := runtime.BindForm(&body, r.Form, nil, nil); err != nil { - sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't bind formdata: %w", err)) - return - } - request.FormdataBody = &body - } - if strings.HasPrefix(r.Header.Get("Content-Type"), "image/png") { - request.Body = r.Body - } - if strings.HasPrefix(r.Header.Get("Content-Type"), "multipart/form-data") { - if reader, err := r.MultipartReader(); err != nil { - sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't decode multipart body: %w", err)) - return - } else { - request.MultipartBody = reader - } - } - if strings.HasPrefix(r.Header.Get("Content-Type"), "text/plain") { - data, err := io.ReadAll(r.Body) - if err != nil { - sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't read body: %w", err)) - return - } - if len(data) > 0 { - body := MultipleRequestAndResponseTypesTextRequestBody(data) - request.TextBody = &body - } - } - - handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { - return sh.ssi.MultipleRequestAndResponseTypes(ctx, request.(MultipleRequestAndResponseTypesRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "MultipleRequestAndResponseTypes") - } - - response, err := handler(r.Context(), w, r, request) - - if err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } else if validResponse, ok := response.(MultipleRequestAndResponseTypesResponseObject); ok { - if err := validResponse.VisitMultipleRequestAndResponseTypesResponse(w); err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } - } else if response != nil { - sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) - } -} - -// RequiredJSONBody operation middleware -func (sh *strictHandler) RequiredJSONBody(w http.ResponseWriter, r *http.Request) { - var request RequiredJSONBodyRequestObject - - var body RequiredJSONBodyJSONRequestBody - if err := json.NewDecoder(r.Body).Decode(&body); err != nil { - sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't decode JSON body: %w", err)) - return - } - request.Body = &body - - handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { - return sh.ssi.RequiredJSONBody(ctx, request.(RequiredJSONBodyRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "RequiredJSONBody") - } - - response, err := handler(r.Context(), w, r, request) - - if err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } else if validResponse, ok := response.(RequiredJSONBodyResponseObject); ok { - if err := validResponse.VisitRequiredJSONBodyResponse(w); err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } - } else if response != nil { - sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) - } -} - -// RequiredTextBody operation middleware -func (sh *strictHandler) RequiredTextBody(w http.ResponseWriter, r *http.Request) { - var request RequiredTextBodyRequestObject - - data, err := io.ReadAll(r.Body) - if err != nil { - sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't read body: %w", err)) - return - } - body := RequiredTextBodyTextRequestBody(data) - request.Body = &body - - handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { - return sh.ssi.RequiredTextBody(ctx, request.(RequiredTextBodyRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "RequiredTextBody") - } - - response, err := handler(r.Context(), w, r, request) - - if err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } else if validResponse, ok := response.(RequiredTextBodyResponseObject); ok { - if err := validResponse.VisitRequiredTextBodyResponse(w); err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } - } else if response != nil { - sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) - } -} - -// ReservedGoKeywordParameters operation middleware -func (sh *strictHandler) ReservedGoKeywordParameters(w http.ResponseWriter, r *http.Request, pType string) { - var request ReservedGoKeywordParametersRequestObject - - request.Type = pType - - handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { - return sh.ssi.ReservedGoKeywordParameters(ctx, request.(ReservedGoKeywordParametersRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "ReservedGoKeywordParameters") - } - - response, err := handler(r.Context(), w, r, request) - - if err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } else if validResponse, ok := response.(ReservedGoKeywordParametersResponseObject); ok { - if err := validResponse.VisitReservedGoKeywordParametersResponse(w); err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } - } else if response != nil { - sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) - } -} - -// ReusableResponses operation middleware -func (sh *strictHandler) ReusableResponses(w http.ResponseWriter, r *http.Request) { - var request ReusableResponsesRequestObject - - var body ReusableResponsesJSONRequestBody - if err := json.NewDecoder(r.Body).Decode(&body); err != nil { - if !errors.Is(err, io.EOF) { - sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't decode JSON body: %w", err)) - return - } - } else { - request.Body = &body - } - - handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { - return sh.ssi.ReusableResponses(ctx, request.(ReusableResponsesRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "ReusableResponses") - } - - response, err := handler(r.Context(), w, r, request) - - if err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } else if validResponse, ok := response.(ReusableResponsesResponseObject); ok { - if err := validResponse.VisitReusableResponsesResponse(w); err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } - } else if response != nil { - sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) - } -} - -// TextExample operation middleware -func (sh *strictHandler) TextExample(w http.ResponseWriter, r *http.Request) { - var request TextExampleRequestObject - - data, err := io.ReadAll(r.Body) - if err != nil { - sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't read body: %w", err)) - return - } - if len(data) > 0 { - body := TextExampleTextRequestBody(data) - request.Body = &body - } - - handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { - return sh.ssi.TextExample(ctx, request.(TextExampleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "TextExample") - } - - response, err := handler(r.Context(), w, r, request) - - if err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } else if validResponse, ok := response.(TextExampleResponseObject); ok { - if err := validResponse.VisitTextExampleResponse(w); err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } - } else if response != nil { - sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) - } -} - -// UnknownExample operation middleware -func (sh *strictHandler) UnknownExample(w http.ResponseWriter, r *http.Request) { - var request UnknownExampleRequestObject - - request.Body = r.Body - - handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { - return sh.ssi.UnknownExample(ctx, request.(UnknownExampleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "UnknownExample") - } - - response, err := handler(r.Context(), w, r, request) - - if err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } else if validResponse, ok := response.(UnknownExampleResponseObject); ok { - if err := validResponse.VisitUnknownExampleResponse(w); err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } - } else if response != nil { - sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) - } -} - -// UnspecifiedContentType operation middleware -func (sh *strictHandler) UnspecifiedContentType(w http.ResponseWriter, r *http.Request) { - var request UnspecifiedContentTypeRequestObject - - request.ContentType = r.Header.Get("Content-Type") - - request.Body = r.Body - - handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { - return sh.ssi.UnspecifiedContentType(ctx, request.(UnspecifiedContentTypeRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "UnspecifiedContentType") - } - - response, err := handler(r.Context(), w, r, request) - - if err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } else if validResponse, ok := response.(UnspecifiedContentTypeResponseObject); ok { - if err := validResponse.VisitUnspecifiedContentTypeResponse(w); err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } - } else if response != nil { - sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) - } -} - -// URLEncodedExample operation middleware -func (sh *strictHandler) URLEncodedExample(w http.ResponseWriter, r *http.Request) { - var request URLEncodedExampleRequestObject - - if err := r.ParseForm(); err != nil { - sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't decode formdata: %w", err)) - return - } - var body URLEncodedExampleFormdataRequestBody - if err := runtime.BindForm(&body, r.Form, nil, nil); err != nil { - sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't bind formdata: %w", err)) - return - } - request.Body = &body - - handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { - return sh.ssi.URLEncodedExample(ctx, request.(URLEncodedExampleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "URLEncodedExample") - } - - response, err := handler(r.Context(), w, r, request) - - if err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } else if validResponse, ok := response.(URLEncodedExampleResponseObject); ok { - if err := validResponse.VisitURLEncodedExampleResponse(w); err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } - } else if response != nil { - sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) - } -} - -// HeadersExample operation middleware -func (sh *strictHandler) HeadersExample(w http.ResponseWriter, r *http.Request, params HeadersExampleParams) { - var request HeadersExampleRequestObject - - request.Params = params - - var body HeadersExampleJSONRequestBody - if err := json.NewDecoder(r.Body).Decode(&body); err != nil { - if !errors.Is(err, io.EOF) { - sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't decode JSON body: %w", err)) - return - } - } else { - request.Body = &body - } - - handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { - return sh.ssi.HeadersExample(ctx, request.(HeadersExampleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "HeadersExample") - } - - response, err := handler(r.Context(), w, r, request) - - if err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } else if validResponse, ok := response.(HeadersExampleResponseObject); ok { - if err := validResponse.VisitHeadersExampleResponse(w); err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } - } else if response != nil { - sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) - } -} - -// UnionExample operation middleware -func (sh *strictHandler) UnionExample(w http.ResponseWriter, r *http.Request) { - var request UnionExampleRequestObject - - var body UnionExampleJSONRequestBody - if err := json.NewDecoder(r.Body).Decode(&body); err != nil { - if !errors.Is(err, io.EOF) { - sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't decode JSON body: %w", err)) - return - } - } else { - request.Body = &body - } - - handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { - return sh.ssi.UnionExample(ctx, request.(UnionExampleRequestObject)) - } - for _, middleware := range sh.middlewares { - handler = middleware(handler, "UnionExample") - } - - response, err := handler(r.Context(), w, r, request) - - if err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } else if validResponse, ok := response.(UnionExampleResponseObject); ok { - if err := validResponse.VisitUnionExampleResponse(w); err != nil { - sh.options.ResponseErrorHandlerFunc(w, r, err) - } - } else if response != nil { - sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) - } -} - -// Base64 encoded, gzipped, json marshaled Swagger object -var swaggerSpec = []string{ - - "H4sIAAAAAAAC/+xZTXPbNhP+Kzt431NKmrbjE2+NJ5O2aeuObJ86PkDESkJCAiiwFK3R6L93QEBfFq1K", - "qT4ynt5Ecr/wPLuLBTRlha6MVqjIsXzKLDqjlcP2oc+Fxb9qdOSfBLrCSkNSK5azD1z04rdZwizWjvdL", - "nKt7+UIrQtWqcmNKWXCvmn1xXn/KXDHCivtf/7c4YDn7X7YMJQtfXYbPvDIlstlslryI4O4zS9gIuUDb", - "Rht+Xq3bpolBljNHVqoh80aC2HWnmFSEQ7TemxeNQXiBeRz5lBmrDVqSAaMxL2vs9hTf6P4XLCisQKqB", - "3sTyViviUjkQcjBAi4ogggfehgNXG6MtoYD+BLyHgsChHaNlCSNJPjB2v/oeYsCOJWyM1gVHVxeXF5ee", - "L21QcSNZzt63rxJmOI3aBS0IMrqL91/u734H6YDXpCtOsuBlOYGKWzfiJQqQirQPsS7IXbDWk22J/1lE", - "7Y8RSp81bQJ90GJyjIRp83Ilna8vL0+Ul7OE3QRnXTYWQWUrBdaaGfC67MD8UX1VulGA1mobV5ZVdUnS", - "cEurXK2j/dtcZBfIF/aygbZVKjjxI6F+KE/nBj61WHJCsQMBvSC5Hw8r5o/Kwr/xc1YOYj/u7FP3I904", - "GOkGSINAXkIjaQRzxRcNVirg4KQalgjzoJJOMkuM296PSvTiWh68jaP3s2TNynPaNE3aFlBtS1SFFt9G", - "YcJkxYeYGTVcV/e2ObGc9SfkU3ZzgztQISeM8JkyU3Kptu/eJ2rp/yF9sMIO5eofpUWRekbSfqyP7sKN", - "5QVeyg8ac90EnIZKOl+l4aMb6boUwMuGT1zoD5sTRy+q+8mjLcyjjx3BgffJcrI1vu0xZEGtz6zzUPuA", - "z/SP1O6R+PvSd+qa2p+i9kwg0qFOv+Kk0VakhlteIaF12dTHOfO2hthh8o+FJBRcQR9B8QoF8AGhhU8a", - "oknXwU/w+0l/DiJLU+2BY/GQ/zllHrz2EMIS5h2wPOD3ko5kC8BPx6VqjmY46qZrrl5L+Cgyh87iwPmB", - "pIvjDvyCp96KxHmOTNtzc+Pwf4qk9ky+Pnj7lrDLsH3AweN77wJ1ePk6ZlFrF9i+cY7ZAcWxFKizytzs", - "aflsoDqDhRxIFGlcRRpie60l3GpVWKT1A4jfDJUmWBiD/gRohBAQaPfHBqGqHYHhzoGktouUMtwVCdxo", - "Ho/LyG6Dp4dlO93G6rsjcfruXIzeXF7tr/L+yHmzdpB4pR57v34MMvvemB3sxLLneetwfs9Uzo2kUbpy", - "pdxdwj8FgeWeXqAc+4lICbBItVUoYCz5/Bp0ozajgSWtXbNQCGM5Dc2vt/cZiJKttq5Zsu0K/OkNX9Ae", - "84+DU+VpreS2i/pH/xniDP1yb5BafafX8LwktIqTHOMPh7m/2bSiFd4N2kp7wXKyo4ent5dVs4SFf45C", - "C6pt6fsEkcmzLPzjdOEaPhyivZA640Z6FP4OAAD//0nTejA+HAAA", -} - -// GetSwagger returns the content of the embedded swagger specification file -// or error if failed to decode -func decodeSpec() ([]byte, error) { - zipped, err := base64.StdEncoding.DecodeString(strings.Join(swaggerSpec, "")) - if err != nil { - return nil, fmt.Errorf("error base64 decoding spec: %w", err) - } - zr, err := gzip.NewReader(bytes.NewReader(zipped)) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - var buf bytes.Buffer - _, err = buf.ReadFrom(zr) - if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) - } - - return buf.Bytes(), nil -} - -var rawSpec = decodeSpecCached() - -// a naive cached of a decoded swagger spec -func decodeSpecCached() func() ([]byte, error) { - data, err := decodeSpec() - return func() ([]byte, error) { - return data, err - } -} - -// Constructs a synthetic filesystem for resolving external references when loading openapi specifications. -func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { - res := make(map[string]func() ([]byte, error)) - if len(pathToFile) > 0 { - res[pathToFile] = rawSpec - } - - return res -} - -// GetSwagger returns the Swagger specification corresponding to the generated code -// in this file. The external references of Swagger specification are resolved. -// The logic of resolving external references is tightly connected to "import-mapping" feature. -// Externally referenced files must be embedded in the corresponding golang packages. -// Urls can be supported but this task was out of the scope. -func GetSwagger() (swagger *openapi3.T, err error) { - resolvePath := PathToRawSpec("") - - loader := openapi3.NewLoader() - loader.IsExternalRefsAllowed = true - loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() - pathToFile = path.Clean(pathToFile) - getSpec, ok := resolvePath[pathToFile] - if !ok { - err1 := fmt.Errorf("path not found: %s", pathToFile) - return nil, err1 - } - return getSpec() - } - var specData []byte - specData, err = rawSpec() - if err != nil { - return - } - swagger, err = loader.LoadFromData(specData) - if err != nil { - return - } - return -} diff --git a/internal/test/strict-server/stdhttp/server.go b/internal/test/strict-server/stdhttp/server.go deleted file mode 100644 index 4f39f939cc..0000000000 --- a/internal/test/strict-server/stdhttp/server.go +++ /dev/null @@ -1,154 +0,0 @@ -//go:build go1.22 - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=server.cfg.yaml ../strict-schema.yaml -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=types.cfg.yaml ../strict-schema.yaml - -package api - -import ( - "context" - "encoding/json" - "io" - "mime/multipart" -) - -type StrictServer struct { -} - -func (s StrictServer) JSONExample(ctx context.Context, request JSONExampleRequestObject) (JSONExampleResponseObject, error) { - return JSONExample200JSONResponse(*request.Body), nil -} - -func (s StrictServer) MultipartExample(ctx context.Context, request MultipartExampleRequestObject) (MultipartExampleResponseObject, error) { - return MultipartExample200MultipartResponse(func(writer *multipart.Writer) error { - for { - part, err := request.Body.NextPart() - if err == io.EOF { - return nil - } else if err != nil { - return err - } - w, err := writer.CreatePart(part.Header) - if err != nil { - return err - } - _, err = io.Copy(w, part) - if err != nil { - return err - } - if err = part.Close(); err != nil { - return err - } - } - }), nil -} - -func (s StrictServer) MultipartRelatedExample(ctx context.Context, request MultipartRelatedExampleRequestObject) (MultipartRelatedExampleResponseObject, error) { - return MultipartRelatedExample200MultipartResponse(func(writer *multipart.Writer) error { - for { - part, err := request.Body.NextPart() - if err == io.EOF { - return nil - } else if err != nil { - return err - } - w, err := writer.CreatePart(part.Header) - if err != nil { - return err - } - _, err = io.Copy(w, part) - if err != nil { - return err - } - if err = part.Close(); err != nil { - return err - } - } - }), nil -} - -func (s StrictServer) MultipleRequestAndResponseTypes(ctx context.Context, request MultipleRequestAndResponseTypesRequestObject) (MultipleRequestAndResponseTypesResponseObject, error) { - switch { - case request.Body != nil: - return MultipleRequestAndResponseTypes200ImagepngResponse{Body: request.Body}, nil - case request.JSONBody != nil: - return MultipleRequestAndResponseTypes200JSONResponse(*request.JSONBody), nil - case request.FormdataBody != nil: - return MultipleRequestAndResponseTypes200FormdataResponse(*request.FormdataBody), nil - case request.TextBody != nil: - return MultipleRequestAndResponseTypes200TextResponse(*request.TextBody), nil - case request.MultipartBody != nil: - return MultipleRequestAndResponseTypes200MultipartResponse(func(writer *multipart.Writer) error { - for { - part, err := request.MultipartBody.NextPart() - if err == io.EOF { - return nil - } else if err != nil { - return err - } - w, err := writer.CreatePart(part.Header) - if err != nil { - return err - } - _, err = io.Copy(w, part) - if err != nil { - return err - } - if err = part.Close(); err != nil { - return err - } - } - }), nil - default: - return MultipleRequestAndResponseTypes400Response{}, nil - } -} - -func (s StrictServer) TextExample(ctx context.Context, request TextExampleRequestObject) (TextExampleResponseObject, error) { - return TextExample200TextResponse(*request.Body), nil -} - -func (s StrictServer) UnknownExample(ctx context.Context, request UnknownExampleRequestObject) (UnknownExampleResponseObject, error) { - return UnknownExample200Videomp4Response{Body: request.Body}, nil -} - -func (s StrictServer) UnspecifiedContentType(ctx context.Context, request UnspecifiedContentTypeRequestObject) (UnspecifiedContentTypeResponseObject, error) { - return UnspecifiedContentType200VideoResponse{Body: request.Body, ContentType: request.ContentType}, nil -} - -func (s StrictServer) URLEncodedExample(ctx context.Context, request URLEncodedExampleRequestObject) (URLEncodedExampleResponseObject, error) { - return URLEncodedExample200FormdataResponse(*request.Body), nil -} - -func (s StrictServer) HeadersExample(ctx context.Context, request HeadersExampleRequestObject) (HeadersExampleResponseObject, error) { - return HeadersExample200JSONResponse{Body: *request.Body, Headers: HeadersExample200ResponseHeaders{Header1: request.Params.Header1, Header2: *request.Params.Header2}}, nil -} - -func (s StrictServer) ReusableResponses(ctx context.Context, request ReusableResponsesRequestObject) (ReusableResponsesResponseObject, error) { - return ReusableResponses200JSONResponse{ReusableresponseJSONResponse: ReusableresponseJSONResponse{Body: *request.Body}}, nil -} - -func (s StrictServer) RequiredJSONBody(ctx context.Context, request RequiredJSONBodyRequestObject) (RequiredJSONBodyResponseObject, error) { - return RequiredJSONBody200JSONResponse(*request.Body), nil -} - -func (s StrictServer) RequiredTextBody(ctx context.Context, request RequiredTextBodyRequestObject) (RequiredTextBodyResponseObject, error) { - return RequiredTextBody200TextResponse(*request.Body), nil -} - -func (s StrictServer) ReservedGoKeywordParameters(ctx context.Context, request ReservedGoKeywordParametersRequestObject) (ReservedGoKeywordParametersResponseObject, error) { - return ReservedGoKeywordParameters200TextResponse(""), nil -} - -func (s StrictServer) UnionExample(ctx context.Context, request UnionExampleRequestObject) (UnionExampleResponseObject, error) { - union, err := json.Marshal(*request.Body) - if err != nil { - return nil, err - } - - return UnionExample200JSONResponse{ - Body: struct{ union json.RawMessage }{ - union: union, - }, - }, nil -} diff --git a/internal/test/strict-server/stdhttp/std_strict_test.go b/internal/test/strict-server/stdhttp/std_strict_test.go deleted file mode 100644 index 40d362a54a..0000000000 --- a/internal/test/strict-server/stdhttp/std_strict_test.go +++ /dev/null @@ -1,229 +0,0 @@ -//go:build go1.22 - -package api - -import ( - "bytes" - "encoding/json" - "io" - "mime" - "mime/multipart" - "net/http" - "net/url" - "strings" - "testing" - - "github.com/stretchr/testify/assert" - - clientAPI "github.com/oapi-codegen/oapi-codegen/v2/internal/test/strict-server/client" - "github.com/oapi-codegen/runtime" - "github.com/oapi-codegen/testutil" -) - -func TestStdHTTPServer(t *testing.T) { - server := StrictServer{} - strictHandler := NewStrictHandler(server, nil) - m := http.NewServeMux() - HandlerFromMux(strictHandler, m) - testImpl(t, m) -} - -func testImpl(t *testing.T, handler http.Handler) { - t.Run("JSONExample", func(t *testing.T) { - value := "123" - requestBody := clientAPI.Example{Value: &value} - rr := testutil.NewRequest().Post("/json").WithJsonBody(requestBody).GoWithHTTPHandler(t, handler).Recorder - assert.Equal(t, http.StatusOK, rr.Code) - assert.True(t, strings.HasPrefix(rr.Header().Get("Content-Type"), "application/json")) - var responseBody clientAPI.Example - err := json.NewDecoder(rr.Body).Decode(&responseBody) - assert.NoError(t, err) - assert.Equal(t, requestBody, responseBody) - }) - t.Run("URLEncodedExample", func(t *testing.T) { - value := "456" - requestBody := clientAPI.Example{Value: &value} - requestBodyEncoded, err := runtime.MarshalForm(&requestBody, nil) - assert.NoError(t, err) - rr := testutil.NewRequest().Post("/urlencoded").WithContentType("application/x-www-form-urlencoded").WithBody([]byte(requestBodyEncoded.Encode())).GoWithHTTPHandler(t, handler).Recorder - assert.Equal(t, http.StatusOK, rr.Code) - assert.Equal(t, "application/x-www-form-urlencoded", rr.Header().Get("Content-Type")) - values, err := url.ParseQuery(rr.Body.String()) - assert.NoError(t, err) - var responseBody clientAPI.Example - err = runtime.BindForm(&responseBody, values, nil, nil) - assert.NoError(t, err) - assert.Equal(t, requestBody, responseBody) - }) - t.Run("MultipartExample", func(t *testing.T) { - value := "789" - fieldName := "value" - var writer bytes.Buffer - mw := multipart.NewWriter(&writer) - field, err := mw.CreateFormField(fieldName) - assert.NoError(t, err) - _, _ = field.Write([]byte(value)) - assert.NoError(t, mw.Close()) - rr := testutil.NewRequest().Post("/multipart").WithContentType(mw.FormDataContentType()).WithBody(writer.Bytes()).GoWithHTTPHandler(t, handler).Recorder - assert.Equal(t, http.StatusOK, rr.Code) - contentType, params, err := mime.ParseMediaType(rr.Header().Get("Content-Type")) - assert.NoError(t, err) - assert.Equal(t, "multipart/form-data", contentType) - reader := multipart.NewReader(rr.Body, params["boundary"]) - part, err := reader.NextPart() - assert.NoError(t, err) - assert.Equal(t, part.FormName(), fieldName) - readValue, err := io.ReadAll(part) - assert.NoError(t, err) - assert.Equal(t, value, string(readValue)) - _, err = reader.NextPart() - assert.Equal(t, io.EOF, err) - }) - t.Run("MultipartRelatedExample", func(t *testing.T) { - value := "789" - fieldName := "value" - var writer bytes.Buffer - mw := multipart.NewWriter(&writer) - field, err := mw.CreateFormField(fieldName) - assert.NoError(t, err) - _, _ = field.Write([]byte(value)) - assert.NoError(t, mw.Close()) - rr := testutil.NewRequest().Post("/multipart-related").WithContentType(mime.FormatMediaType("multipart/related", map[string]string{"boundary": mw.Boundary()})).WithBody(writer.Bytes()).GoWithHTTPHandler(t, handler).Recorder - assert.Equal(t, http.StatusOK, rr.Code) - contentType, params, err := mime.ParseMediaType(rr.Header().Get("Content-Type")) - assert.NoError(t, err) - assert.Equal(t, "multipart/related", contentType) - reader := multipart.NewReader(rr.Body, params["boundary"]) - part, err := reader.NextPart() - assert.NoError(t, err) - assert.Equal(t, part.FormName(), fieldName) - readValue, err := io.ReadAll(part) - assert.NoError(t, err) - assert.Equal(t, value, string(readValue)) - _, err = reader.NextPart() - assert.Equal(t, io.EOF, err) - }) - t.Run("TextExample", func(t *testing.T) { - value := "text" - rr := testutil.NewRequest().Post("/text").WithContentType("text/plain").WithBody([]byte(value)).GoWithHTTPHandler(t, handler).Recorder - assert.Equal(t, http.StatusOK, rr.Code) - assert.Equal(t, "text/plain", rr.Header().Get("Content-Type")) - assert.Equal(t, value, rr.Body.String()) - }) - t.Run("UnknownExample", func(t *testing.T) { - data := []byte("unknown data") - rr := testutil.NewRequest().Post("/unknown").WithContentType("image/png").WithBody(data).GoWithHTTPHandler(t, handler).Recorder - assert.Equal(t, http.StatusOK, rr.Code) - assert.Equal(t, "video/mp4", rr.Header().Get("Content-Type")) - assert.Equal(t, data, rr.Body.Bytes()) - }) - t.Run("MultipleRequestAndResponseTypesJSON", func(t *testing.T) { - value := "123" - requestBody := clientAPI.Example{Value: &value} - rr := testutil.NewRequest().Post("/multiple").WithJsonBody(requestBody).GoWithHTTPHandler(t, handler).Recorder - assert.Equal(t, http.StatusOK, rr.Code) - assert.True(t, strings.HasPrefix(rr.Header().Get("Content-Type"), "application/json")) - var responseBody clientAPI.Example - err := json.NewDecoder(rr.Body).Decode(&responseBody) - assert.NoError(t, err) - assert.Equal(t, requestBody, responseBody) - }) - t.Run("MultipleRequestAndResponseTypesFormdata", func(t *testing.T) { - value := "456" - requestBody := clientAPI.Example{Value: &value} - requestBodyEncoded, err := runtime.MarshalForm(&requestBody, nil) - assert.NoError(t, err) - rr := testutil.NewRequest().Post("/multiple").WithContentType("application/x-www-form-urlencoded").WithBody([]byte(requestBodyEncoded.Encode())).GoWithHTTPHandler(t, handler).Recorder - assert.Equal(t, http.StatusOK, rr.Code) - assert.Equal(t, "application/x-www-form-urlencoded", rr.Header().Get("Content-Type")) - values, err := url.ParseQuery(rr.Body.String()) - assert.NoError(t, err) - var responseBody clientAPI.Example - err = runtime.BindForm(&responseBody, values, nil, nil) - assert.NoError(t, err) - assert.Equal(t, requestBody, responseBody) - }) - t.Run("MultipleRequestAndResponseTypesMultipart", func(t *testing.T) { - value := "789" - fieldName := "value" - var writer bytes.Buffer - mw := multipart.NewWriter(&writer) - field, err := mw.CreateFormField(fieldName) - assert.NoError(t, err) - _, _ = field.Write([]byte(value)) - assert.NoError(t, mw.Close()) - rr := testutil.NewRequest().Post("/multiple").WithContentType(mw.FormDataContentType()).WithBody(writer.Bytes()).GoWithHTTPHandler(t, handler).Recorder - assert.Equal(t, http.StatusOK, rr.Code) - contentType, params, err := mime.ParseMediaType(rr.Header().Get("Content-Type")) - assert.NoError(t, err) - assert.Equal(t, "multipart/form-data", contentType) - reader := multipart.NewReader(rr.Body, params["boundary"]) - part, err := reader.NextPart() - assert.NoError(t, err) - assert.Equal(t, part.FormName(), fieldName) - readValue, err := io.ReadAll(part) - assert.NoError(t, err) - assert.Equal(t, value, string(readValue)) - _, err = reader.NextPart() - assert.Equal(t, io.EOF, err) - }) - t.Run("MultipleRequestAndResponseTypesText", func(t *testing.T) { - value := "text" - rr := testutil.NewRequest().Post("/multiple").WithContentType("text/plain").WithBody([]byte(value)).GoWithHTTPHandler(t, handler).Recorder - assert.Equal(t, http.StatusOK, rr.Code) - assert.Equal(t, "text/plain", rr.Header().Get("Content-Type")) - assert.Equal(t, value, rr.Body.String()) - }) - t.Run("MultipleRequestAndResponseTypesImage", func(t *testing.T) { - data := []byte("unknown data") - rr := testutil.NewRequest().Post("/multiple").WithContentType("image/png").WithBody(data).GoWithHTTPHandler(t, handler).Recorder - assert.Equal(t, http.StatusOK, rr.Code) - assert.Equal(t, "image/png", rr.Header().Get("Content-Type")) - assert.Equal(t, data, rr.Body.Bytes()) - }) - t.Run("HeadersExample", func(t *testing.T) { - header1 := "value1" - header2 := "890" - value := "asdf" - requestBody := clientAPI.Example{Value: &value} - rr := testutil.NewRequest().Post("/with-headers").WithHeader("header1", header1).WithHeader("header2", header2).WithJsonBody(requestBody).GoWithHTTPHandler(t, handler).Recorder - assert.Equal(t, http.StatusOK, rr.Code) - assert.True(t, strings.HasPrefix(rr.Header().Get("Content-Type"), "application/json")) - var responseBody clientAPI.Example - err := json.NewDecoder(rr.Body).Decode(&responseBody) - assert.NoError(t, err) - assert.Equal(t, requestBody, responseBody) - assert.Equal(t, header1, rr.Header().Get("header1")) - assert.Equal(t, header2, rr.Header().Get("header2")) - }) - t.Run("UnspecifiedContentType", func(t *testing.T) { - data := []byte("image data") - contentType := "image/jpeg" - rr := testutil.NewRequest().Post("/unspecified-content-type").WithContentType(contentType).WithBody(data).GoWithHTTPHandler(t, handler).Recorder - assert.Equal(t, http.StatusOK, rr.Code) - assert.Equal(t, contentType, rr.Header().Get("Content-Type")) - assert.Equal(t, data, rr.Body.Bytes()) - }) - t.Run("ReusableResponses", func(t *testing.T) { - value := "jkl;" - requestBody := clientAPI.Example{Value: &value} - rr := testutil.NewRequest().Post("/reusable-responses").WithJsonBody(requestBody).GoWithHTTPHandler(t, handler).Recorder - assert.Equal(t, http.StatusOK, rr.Code) - assert.True(t, strings.HasPrefix(rr.Header().Get("Content-Type"), "application/json")) - var responseBody clientAPI.Example - err := json.NewDecoder(rr.Body).Decode(&responseBody) - assert.NoError(t, err) - assert.Equal(t, requestBody, responseBody) - }) - t.Run("UnionResponses", func(t *testing.T) { - value := "union" - requestBody := clientAPI.Example{Value: &value} - rr := testutil.NewRequest().Post("/with-union").WithJsonBody(requestBody).GoWithHTTPHandler(t, handler).Recorder - assert.Equal(t, http.StatusOK, rr.Code) - assert.True(t, strings.HasPrefix(rr.Header().Get("Content-Type"), "application/json")) - var responseBody clientAPI.Example - err := json.NewDecoder(rr.Body).Decode(&responseBody) - assert.NoError(t, err) - assert.Equal(t, requestBody, responseBody) - }) -} diff --git a/internal/test/strict-server/stdhttp/tools/tools.go b/internal/test/strict-server/stdhttp/tools/tools.go deleted file mode 100644 index 8615cb4c57..0000000000 --- a/internal/test/strict-server/stdhttp/tools/tools.go +++ /dev/null @@ -1,8 +0,0 @@ -//go:build tools -// +build tools - -package tools - -import ( - _ "github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen" -) diff --git a/internal/test/strict-server/stdhttp/types.cfg.yaml b/internal/test/strict-server/stdhttp/types.cfg.yaml deleted file mode 100644 index 2ed9740ea7..0000000000 --- a/internal/test/strict-server/stdhttp/types.cfg.yaml +++ /dev/null @@ -1,5 +0,0 @@ -# yaml-language-server: $schema=../../../../configuration-schema.json -package: api -generate: - models: true -output: types.gen.go diff --git a/internal/test/strict-server/stdhttp/types.gen.go b/internal/test/strict-server/stdhttp/types.gen.go deleted file mode 100644 index fac014c4bb..0000000000 --- a/internal/test/strict-server/stdhttp/types.gen.go +++ /dev/null @@ -1,69 +0,0 @@ -// Package api provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package api - -// Example defines model for example. -type Example struct { - Value *string `json:"value,omitempty"` -} - -// Reusableresponse defines model for reusableresponse. -type Reusableresponse = Example - -// MultipleRequestAndResponseTypesTextBody defines parameters for MultipleRequestAndResponseTypes. -type MultipleRequestAndResponseTypesTextBody = string - -// RequiredTextBodyTextBody defines parameters for RequiredTextBody. -type RequiredTextBodyTextBody = string - -// TextExampleTextBody defines parameters for TextExample. -type TextExampleTextBody = string - -// HeadersExampleParams defines parameters for HeadersExample. -type HeadersExampleParams struct { - Header1 string `json:"header1"` - Header2 *int `json:"header2,omitempty"` -} - -// JSONExampleJSONRequestBody defines body for JSONExample for application/json ContentType. -type JSONExampleJSONRequestBody = Example - -// MultipartExampleMultipartRequestBody defines body for MultipartExample for multipart/form-data ContentType. -type MultipartExampleMultipartRequestBody = Example - -// MultipartRelatedExampleMultipartRequestBody defines body for MultipartRelatedExample for multipart/related ContentType. -type MultipartRelatedExampleMultipartRequestBody = Example - -// MultipleRequestAndResponseTypesJSONRequestBody defines body for MultipleRequestAndResponseTypes for application/json ContentType. -type MultipleRequestAndResponseTypesJSONRequestBody = Example - -// MultipleRequestAndResponseTypesFormdataRequestBody defines body for MultipleRequestAndResponseTypes for application/x-www-form-urlencoded ContentType. -type MultipleRequestAndResponseTypesFormdataRequestBody = Example - -// MultipleRequestAndResponseTypesMultipartRequestBody defines body for MultipleRequestAndResponseTypes for multipart/form-data ContentType. -type MultipleRequestAndResponseTypesMultipartRequestBody = Example - -// MultipleRequestAndResponseTypesTextRequestBody defines body for MultipleRequestAndResponseTypes for text/plain ContentType. -type MultipleRequestAndResponseTypesTextRequestBody = MultipleRequestAndResponseTypesTextBody - -// RequiredJSONBodyJSONRequestBody defines body for RequiredJSONBody for application/json ContentType. -type RequiredJSONBodyJSONRequestBody = Example - -// RequiredTextBodyTextRequestBody defines body for RequiredTextBody for text/plain ContentType. -type RequiredTextBodyTextRequestBody = RequiredTextBodyTextBody - -// ReusableResponsesJSONRequestBody defines body for ReusableResponses for application/json ContentType. -type ReusableResponsesJSONRequestBody = Example - -// TextExampleTextRequestBody defines body for TextExample for text/plain ContentType. -type TextExampleTextRequestBody = TextExampleTextBody - -// URLEncodedExampleFormdataRequestBody defines body for URLEncodedExample for application/x-www-form-urlencoded ContentType. -type URLEncodedExampleFormdataRequestBody = Example - -// HeadersExampleJSONRequestBody defines body for HeadersExample for application/json ContentType. -type HeadersExampleJSONRequestBody = Example - -// UnionExampleJSONRequestBody defines body for UnionExample for application/json ContentType. -type UnionExampleJSONRequestBody = Example diff --git a/internal/test/strict-server/strict-schema.yaml b/internal/test/strict-server/strict-schema.yaml deleted file mode 100644 index 8b18edd541..0000000000 --- a/internal/test/strict-server/strict-schema.yaml +++ /dev/null @@ -1,363 +0,0 @@ -openapi: "3.0.0" -info: - version: 1.0.0 - title: Strict server examples - description: Contains different content types supported by strict server -servers: - - url: http://strict.swagger.io/api -paths: - /json: - post: - operationId: JSONExample - description: JSON is automatically marshaled into structs. - requestBody: - content: - application/json: - schema: - $ref: "#/components/schemas/example" - responses: - 200: - description: OK - content: - application/json: - schema: - $ref: "#/components/schemas/example" - 400: - $ref: "#/components/responses/badrequest" - default: - description: Unknown error - /urlencoded: - post: - operationId: URLEncodedExample - requestBody: - content: - application/x-www-form-urlencoded: - schema: - $ref: "#/components/schemas/example" - responses: - 200: - description: OK - content: - application/x-www-form-urlencoded: - schema: - $ref: "#/components/schemas/example" - 400: - $ref: "#/components/responses/badrequest" - default: - description: Unknown error - /multipart: - post: - operationId: MultipartExample - requestBody: - content: - multipart/form-data: - schema: - $ref: "#/components/schemas/example" - responses: - 200: - description: OK - content: - multipart/form-data: - schema: - $ref: "#/components/schemas/example" - 400: - $ref: "#/components/responses/badrequest" - default: - description: Unknown error - /multipart-related: - post: - operationId: MultipartRelatedExample - requestBody: - content: - multipart/related: - schema: - $ref: "#/components/schemas/example" - responses: - 200: - description: OK - content: - multipart/related: - schema: - $ref: "#/components/schemas/example" - 400: - $ref: "#/components/responses/badrequest" - default: - description: Unknown error - /text: - post: - operationId: TextExample - requestBody: - content: - text/plain: - schema: - type: string - responses: - 200: - description: OK - content: - text/plain: - schema: - type: string - 400: - $ref: "#/components/responses/badrequest" - default: - description: Unknown error - /unknown: - post: - operationId: UnknownExample - requestBody: - content: - image/png: - schema: - type: string - format: byte - responses: - 200: - description: OK - content: - video/mp4: - schema: - type: string - format: byte - 400: - $ref: "#/components/responses/badrequest" - default: - description: Unknown error - /multiple: - post: - operationId: MultipleRequestAndResponseTypes - description: Shows how to deal with multiple content types in a single request - requestBody: - content: - application/json: - schema: - $ref: "#/components/schemas/example" - application/x-www-form-urlencoded: - schema: - $ref: "#/components/schemas/example" - multipart/form-data: - schema: - $ref: "#/components/schemas/example" - text/plain: - schema: - type: string - image/png: - schema: - type: string - format: byte - responses: - 200: - description: OK - content: - application/json: - schema: - $ref: "#/components/schemas/example" - application/x-www-form-urlencoded: - schema: - $ref: "#/components/schemas/example" - multipart/form-data: - schema: - $ref: "#/components/schemas/example" - text/plain: - schema: - type: string - image/png: - schema: - type: string - format: byte - 400: - $ref: "#/components/responses/badrequest" - /with-headers: - post: - operationId: HeadersExample - description: Headers can be received and returned via structs - parameters: - - name: header1 - in: header - required: true - schema: - type: string - - name: header2 - in: header - required: false - schema: - type: integer - requestBody: - content: - application/json: - schema: - $ref: "#/components/schemas/example" - responses: - 200: - description: OK - headers: - header1: - schema: - type: string - header2: - schema: - type: integer - content: - application/json: - schema: - $ref: "#/components/schemas/example" - 400: - $ref: "#/components/responses/badrequest" - default: - description: Unknown error - /reusable-responses: - post: - operationId: ReusableResponses - description: Responses can be refs to components/responses - requestBody: - content: - application/json: - schema: - $ref: "#/components/schemas/example" - responses: - 200: - $ref: "#/components/responses/reusableresponse" - 400: - $ref: "#/components/responses/badrequest" - default: - description: Unknown error - /unspecified-content-type: - post: - operationId: UnspecifiedContentType - description: Concrete content type is not specified by the schema, so we must pass it to client code - requestBody: - content: - image/*: - schema: - type: string - format: byte - responses: - 200: - description: OK - content: - video/*: - schema: - type: string - format: byte - 400: - $ref: "#/components/responses/badrequest" - 401: - $ref: "#/components/responses/badrequest" - 403: - $ref: "#/components/responses/badrequest" - default: - description: Unknown error - /required-json-body: - post: - operationId: RequiredJSONBody - description: Request body is required, so missing body should always error. - requestBody: - required: true - content: - application/json: - schema: - $ref: "#/components/schemas/example" - responses: - 200: - description: OK - content: - application/json: - schema: - $ref: "#/components/schemas/example" - 400: - $ref: "#/components/responses/badrequest" - default: - description: Unknown error - /required-text-body: - post: - operationId: RequiredTextBody - description: Request body is required, so missing body should always error. - requestBody: - required: true - content: - text/plain: - schema: - type: string - responses: - 200: - description: OK - content: - text/plain: - schema: - type: string - 400: - $ref: "#/components/responses/badrequest" - default: - description: Unknown error - /reserved-go-keyword-parameters/{type}: - get: - operationId: ReservedGoKeywordParameters - description: Parameters can be named after Go keywords - parameters: - - name: type - in: path - required: true - schema: - type: string - responses: - 200: - description: OK - content: - text/plain: - schema: - type: string - /with-union: - post: - operationId: UnionExample - description: Union type - requestBody: - content: - application/json: - schema: - $ref: "#/components/schemas/example" - responses: - 200: - description: OK - headers: - header1: - schema: - type: string - header2: - schema: - type: integer - content: - application/json: - schema: - oneOf: - - type: string - - $ref: "#/components/schemas/example" - application/alternative+json: - schema: - $ref: "#/components/schemas/example" - 400: - $ref: "#/components/responses/badrequest" - default: - description: Unknown error -components: - responses: - badrequest: - description: BadRequest - reusableresponse: - description: OK - headers: - header1: - schema: - type: string - header2: - schema: - type: integer - content: - application/json: - schema: - $ref: "#/components/schemas/example" - schemas: - example: - type: object - properties: - value: - type: string diff --git a/internal/test/strict-server/strict_test.go b/internal/test/strict-server/strict_test.go deleted file mode 100644 index 03cade9cc9..0000000000 --- a/internal/test/strict-server/strict_test.go +++ /dev/null @@ -1,261 +0,0 @@ -package strictserver - -import ( - "bytes" - "encoding/json" - "io" - "mime" - "mime/multipart" - "net/http" - "net/url" - "strings" - "testing" - - "github.com/gin-gonic/gin" - "github.com/go-chi/chi/v5" - "github.com/kataras/iris/v12" - "github.com/labstack/echo/v4" - "github.com/stretchr/testify/assert" - - chiAPI "github.com/oapi-codegen/oapi-codegen/v2/internal/test/strict-server/chi" - clientAPI "github.com/oapi-codegen/oapi-codegen/v2/internal/test/strict-server/client" - echoAPI "github.com/oapi-codegen/oapi-codegen/v2/internal/test/strict-server/echo" - ginAPI "github.com/oapi-codegen/oapi-codegen/v2/internal/test/strict-server/gin" - irisAPI "github.com/oapi-codegen/oapi-codegen/v2/internal/test/strict-server/iris" - - "github.com/oapi-codegen/runtime" - "github.com/oapi-codegen/testutil" -) - -func TestIrisServer(t *testing.T) { - server := irisAPI.StrictServer{} - strictHandler := irisAPI.NewStrictHandler(server, nil) - i := iris.New() - irisAPI.RegisterHandlers(i, strictHandler) - testImpl(t, i) -} - -func TestChiServer(t *testing.T) { - server := chiAPI.StrictServer{} - strictHandler := chiAPI.NewStrictHandler(server, nil) - r := chi.NewRouter() - handler := chiAPI.HandlerFromMux(strictHandler, r) - testImpl(t, handler) -} - -func TestEchoServer(t *testing.T) { - server := echoAPI.StrictServer{} - strictHandler := echoAPI.NewStrictHandler(server, nil) - e := echo.New() - echoAPI.RegisterHandlers(e, strictHandler) - testImpl(t, e) -} - -func TestGinServer(t *testing.T) { - server := ginAPI.StrictServer{} - strictHandler := ginAPI.NewStrictHandler(server, nil) - gin.SetMode(gin.ReleaseMode) - r := gin.New() - ginAPI.RegisterHandlers(r, strictHandler) - testImpl(t, r) -} - -func testImpl(t *testing.T, handler http.Handler) { - t.Run("JSONExample", func(t *testing.T) { - value := "123" - requestBody := clientAPI.Example{Value: &value} - rr := testutil.NewRequest().Post("/json").WithJsonBody(requestBody).GoWithHTTPHandler(t, handler).Recorder - assert.Equal(t, http.StatusOK, rr.Code) - assert.True(t, strings.HasPrefix(rr.Header().Get("Content-Type"), "application/json")) - var responseBody clientAPI.Example - err := json.NewDecoder(rr.Body).Decode(&responseBody) - assert.NoError(t, err) - assert.Equal(t, requestBody, responseBody) - }) - t.Run("URLEncodedExample", func(t *testing.T) { - value := "456" - requestBody := clientAPI.Example{Value: &value} - requestBodyEncoded, err := runtime.MarshalForm(&requestBody, nil) - assert.NoError(t, err) - rr := testutil.NewRequest().Post("/urlencoded").WithContentType("application/x-www-form-urlencoded").WithBody([]byte(requestBodyEncoded.Encode())).GoWithHTTPHandler(t, handler).Recorder - assert.Equal(t, http.StatusOK, rr.Code) - assert.Equal(t, "application/x-www-form-urlencoded", rr.Header().Get("Content-Type")) - values, err := url.ParseQuery(rr.Body.String()) - assert.NoError(t, err) - var responseBody clientAPI.Example - err = runtime.BindForm(&responseBody, values, nil, nil) - assert.NoError(t, err) - assert.Equal(t, requestBody, responseBody) - }) - t.Run("MultipartExample", func(t *testing.T) { - value := "789" - fieldName := "value" - var writer bytes.Buffer - mw := multipart.NewWriter(&writer) - field, err := mw.CreateFormField(fieldName) - assert.NoError(t, err) - _, _ = field.Write([]byte(value)) - assert.NoError(t, mw.Close()) - rr := testutil.NewRequest().Post("/multipart").WithContentType(mw.FormDataContentType()).WithBody(writer.Bytes()).GoWithHTTPHandler(t, handler).Recorder - assert.Equal(t, http.StatusOK, rr.Code) - contentType, params, err := mime.ParseMediaType(rr.Header().Get("Content-Type")) - assert.NoError(t, err) - assert.Equal(t, "multipart/form-data", contentType) - reader := multipart.NewReader(rr.Body, params["boundary"]) - part, err := reader.NextPart() - assert.NoError(t, err) - assert.Equal(t, part.FormName(), fieldName) - readValue, err := io.ReadAll(part) - assert.NoError(t, err) - assert.Equal(t, value, string(readValue)) - _, err = reader.NextPart() - assert.Equal(t, io.EOF, err) - }) - t.Run("MultipartRelatedExample", func(t *testing.T) { - value := "789" - fieldName := "value" - var writer bytes.Buffer - mw := multipart.NewWriter(&writer) - field, err := mw.CreateFormField(fieldName) - assert.NoError(t, err) - _, _ = field.Write([]byte(value)) - assert.NoError(t, mw.Close()) - rr := testutil.NewRequest().Post("/multipart-related").WithContentType(mime.FormatMediaType("multipart/related", map[string]string{"boundary": mw.Boundary()})).WithBody(writer.Bytes()).GoWithHTTPHandler(t, handler).Recorder - assert.Equal(t, http.StatusOK, rr.Code) - contentType, params, err := mime.ParseMediaType(rr.Header().Get("Content-Type")) - assert.NoError(t, err) - assert.Equal(t, "multipart/related", contentType) - reader := multipart.NewReader(rr.Body, params["boundary"]) - part, err := reader.NextPart() - assert.NoError(t, err) - assert.Equal(t, part.FormName(), fieldName) - readValue, err := io.ReadAll(part) - assert.NoError(t, err) - assert.Equal(t, value, string(readValue)) - _, err = reader.NextPart() - assert.Equal(t, io.EOF, err) - }) - t.Run("TextExample", func(t *testing.T) { - value := "text" - rr := testutil.NewRequest().Post("/text").WithContentType("text/plain").WithBody([]byte(value)).GoWithHTTPHandler(t, handler).Recorder - assert.Equal(t, http.StatusOK, rr.Code) - assert.Equal(t, "text/plain", rr.Header().Get("Content-Type")) - assert.Equal(t, value, rr.Body.String()) - }) - t.Run("UnknownExample", func(t *testing.T) { - data := []byte("unknown data") - rr := testutil.NewRequest().Post("/unknown").WithContentType("image/png").WithBody(data).GoWithHTTPHandler(t, handler).Recorder - assert.Equal(t, http.StatusOK, rr.Code) - assert.Equal(t, "video/mp4", rr.Header().Get("Content-Type")) - assert.Equal(t, data, rr.Body.Bytes()) - }) - t.Run("MultipleRequestAndResponseTypesJSON", func(t *testing.T) { - value := "123" - requestBody := clientAPI.Example{Value: &value} - rr := testutil.NewRequest().Post("/multiple").WithJsonBody(requestBody).GoWithHTTPHandler(t, handler).Recorder - assert.Equal(t, http.StatusOK, rr.Code) - assert.True(t, strings.HasPrefix(rr.Header().Get("Content-Type"), "application/json")) - var responseBody clientAPI.Example - err := json.NewDecoder(rr.Body).Decode(&responseBody) - assert.NoError(t, err) - assert.Equal(t, requestBody, responseBody) - }) - t.Run("MultipleRequestAndResponseTypesFormdata", func(t *testing.T) { - value := "456" - requestBody := clientAPI.Example{Value: &value} - requestBodyEncoded, err := runtime.MarshalForm(&requestBody, nil) - assert.NoError(t, err) - rr := testutil.NewRequest().Post("/multiple").WithContentType("application/x-www-form-urlencoded").WithBody([]byte(requestBodyEncoded.Encode())).GoWithHTTPHandler(t, handler).Recorder - assert.Equal(t, http.StatusOK, rr.Code) - assert.Equal(t, "application/x-www-form-urlencoded", rr.Header().Get("Content-Type")) - values, err := url.ParseQuery(rr.Body.String()) - assert.NoError(t, err) - var responseBody clientAPI.Example - err = runtime.BindForm(&responseBody, values, nil, nil) - assert.NoError(t, err) - assert.Equal(t, requestBody, responseBody) - }) - t.Run("MultipleRequestAndResponseTypesMultipart", func(t *testing.T) { - value := "789" - fieldName := "value" - var writer bytes.Buffer - mw := multipart.NewWriter(&writer) - field, err := mw.CreateFormField(fieldName) - assert.NoError(t, err) - _, _ = field.Write([]byte(value)) - assert.NoError(t, mw.Close()) - rr := testutil.NewRequest().Post("/multiple").WithContentType(mw.FormDataContentType()).WithBody(writer.Bytes()).GoWithHTTPHandler(t, handler).Recorder - assert.Equal(t, http.StatusOK, rr.Code) - contentType, params, err := mime.ParseMediaType(rr.Header().Get("Content-Type")) - assert.NoError(t, err) - assert.Equal(t, "multipart/form-data", contentType) - reader := multipart.NewReader(rr.Body, params["boundary"]) - part, err := reader.NextPart() - assert.NoError(t, err) - assert.Equal(t, part.FormName(), fieldName) - readValue, err := io.ReadAll(part) - assert.NoError(t, err) - assert.Equal(t, value, string(readValue)) - _, err = reader.NextPart() - assert.Equal(t, io.EOF, err) - }) - t.Run("MultipleRequestAndResponseTypesText", func(t *testing.T) { - value := "text" - rr := testutil.NewRequest().Post("/multiple").WithContentType("text/plain").WithBody([]byte(value)).GoWithHTTPHandler(t, handler).Recorder - assert.Equal(t, http.StatusOK, rr.Code) - assert.Equal(t, "text/plain", rr.Header().Get("Content-Type")) - assert.Equal(t, value, rr.Body.String()) - }) - t.Run("MultipleRequestAndResponseTypesImage", func(t *testing.T) { - data := []byte("unknown data") - rr := testutil.NewRequest().Post("/multiple").WithContentType("image/png").WithBody(data).GoWithHTTPHandler(t, handler).Recorder - assert.Equal(t, http.StatusOK, rr.Code) - assert.Equal(t, "image/png", rr.Header().Get("Content-Type")) - assert.Equal(t, data, rr.Body.Bytes()) - }) - t.Run("HeadersExample", func(t *testing.T) { - header1 := "value1" - header2 := "890" - value := "asdf" - requestBody := clientAPI.Example{Value: &value} - rr := testutil.NewRequest().Post("/with-headers").WithHeader("header1", header1).WithHeader("header2", header2).WithJsonBody(requestBody).GoWithHTTPHandler(t, handler).Recorder - assert.Equal(t, http.StatusOK, rr.Code) - assert.True(t, strings.HasPrefix(rr.Header().Get("Content-Type"), "application/json")) - var responseBody clientAPI.Example - err := json.NewDecoder(rr.Body).Decode(&responseBody) - assert.NoError(t, err) - assert.Equal(t, requestBody, responseBody) - assert.Equal(t, header1, rr.Header().Get("header1")) - assert.Equal(t, header2, rr.Header().Get("header2")) - }) - t.Run("UnspecifiedContentType", func(t *testing.T) { - data := []byte("image data") - contentType := "image/jpeg" - rr := testutil.NewRequest().Post("/unspecified-content-type").WithContentType(contentType).WithBody(data).GoWithHTTPHandler(t, handler).Recorder - assert.Equal(t, http.StatusOK, rr.Code) - assert.Equal(t, contentType, rr.Header().Get("Content-Type")) - assert.Equal(t, data, rr.Body.Bytes()) - }) - t.Run("ReusableResponses", func(t *testing.T) { - value := "jkl;" - requestBody := clientAPI.Example{Value: &value} - rr := testutil.NewRequest().Post("/reusable-responses").WithJsonBody(requestBody).GoWithHTTPHandler(t, handler).Recorder - assert.Equal(t, http.StatusOK, rr.Code) - assert.True(t, strings.HasPrefix(rr.Header().Get("Content-Type"), "application/json")) - var responseBody clientAPI.Example - err := json.NewDecoder(rr.Body).Decode(&responseBody) - assert.NoError(t, err) - assert.Equal(t, requestBody, responseBody) - }) - t.Run("UnionResponses", func(t *testing.T) { - value := "union" - requestBody := clientAPI.Example{Value: &value} - rr := testutil.NewRequest().Post("/with-union").WithJsonBody(requestBody).GoWithHTTPHandler(t, handler).Recorder - assert.Equal(t, http.StatusOK, rr.Code) - assert.True(t, strings.HasPrefix(rr.Header().Get("Content-Type"), "application/json")) - var responseBody clientAPI.Example - err := json.NewDecoder(rr.Body).Decode(&responseBody) - assert.NoError(t, err) - assert.Equal(t, requestBody, responseBody) - }) -} diff --git a/internal/test/test-schema.yaml b/internal/test/test-schema.yaml deleted file mode 100644 index cc34a9fb56..0000000000 --- a/internal/test/test-schema.yaml +++ /dev/null @@ -1,369 +0,0 @@ -openapi: "3.0.1" -info: - version: 1.0.0 - title: Test Server - license: - name: MIT -servers: - - url: http://openapitest.deepmap.ai -paths: - /response-with-reference: - get: - summary: get response with reference - operationId: getResponseWithReference - responses: - '200': - $ref: "#/components/responses/ResponseWithReference" - /reserved-keyword: - get: - summary: get with reserved keyword - operationId: getReservedKeyword - responses: - '200': - description: example of a response with a reserved keyword - content: - application/json: - schema: - $ref: "#/components/schemas/ReservedKeyword" - /every-type-optional: - get: - summary: get every type optional - operationId: getEveryTypeOptional - responses: - '200': - description: a example of every type with an optional value - content: - application/json: - schema: - $ref: "#/components/schemas/EveryTypeOptional" - /get-simple: - get: - summary: Get resource via simple path - operationId: getSimple - responses: - '200': - description: A simple response for a simple path - content: - application/json: - schema: - $ref: "#/components/schemas/some_object" - /get-with-type/{content_type}: - get: - summary: Get an object by ID - operationId: getWithContentType - parameters: - - name: content_type - in: path - required: true - description: Get with a parameter and multiple output types - schema: - type: string - enum: - - text - - json - responses: - '200': - description: A simple response for a simple path - content: - application/json: - schema: - $ref: "#/components/schemas/some_object" - text/plain: - schema: - type: string - /get-with-references/{global_argument}/{argument}: - summary: GetWithReferences - parameters: - - name: global_argument - in: path - required: true - description: A parameter in global path scope - schema: - type: integer - format: int64 - get: - summary: Getter with referenced parameter and referenced response - operationId: getWithReferences - parameters: - - $ref: "#/components/parameters/argument" - responses: - '200': - $ref: "#/components/responses/SimpleResponse" - /get-with-args: - summary: GetWithArgs - get: - summary: Getter with referenced parameter and referenced response - operationId: getWithArgs - parameters: - - name: optional_argument - in: query - required: false - description: An optional query argument - schema: - type: integer - format: int64 - - name: required_argument - in: query - required: true - description: An optional query argument - schema: - type: integer - format: int64 - - name: header_argument - in: header - required: false - description: An optional query argument - schema: - type: integer - format: int32 - #- name: cookie_argument - # in: cookie - # required: false - # description: An optional query argument - # schema: - # type: integer - # format: int32 - responses: - '200': - $ref: "#/components/responses/SimpleResponse" - /resource/{argument}: - post: - summary: Create a resource - operationId: createResource - parameters: - - $ref: "#/components/parameters/argument" - requestBody: - description: Required body - required: true - content: - application/json: - schema: - $ref: '#/components/schemas/EveryTypeRequired' - responses: - '200': - $ref: "#/components/responses/SimpleResponse" - /resource2/{inline_argument}: - post: - summary: Create a resource with inline parameter - operationId: createResource2 - parameters: - - name: inline_argument - in: path - required: true - description: Some argument - schema: - type: integer - - name: inline_query_argument - in: query - description: Some query argument - schema: - type: integer - requestBody: - description: Optional body - required: false - content: - application/json: - schema: - $ref: '#/components/schemas/Resource' - responses: - '200': - $ref: "#/components/responses/SimpleResponse" - /resource3/{fallthrough}: - put: - summary: | - Update a resource with inline body. The parameter name is a reserved - keyword, so make sure that gets prefixed to avoid syntax errors - operationId: updateResource3 - parameters: - - name: fallthrough - in: path - required: true - description: Some argument - schema: - type: integer - requestBody: - description: required inline body - required: true - content: - application/json: - schema: - properties: - id: - type: integer - name: - type: string - responses: - '200': - $ref: "#/components/responses/SimpleResponse" -components: - parameters: - argument: - name: argument - in: path - required: true - description: Some argument - schema: - type: string - schemas: - ThisShouldBePruned: - properties: - name: - type: string - # This is intentionally named in snake case - some_object: - properties: - name: - type: string - required: - - name - Resource: - properties: - name: - type: string - value: - type: number - format: float - required: - - name - - value - EveryTypeRequired: - properties: - int32_field: - type: integer - format: int32 - int64_field: - type: integer - format: int64 - int_field: - type: integer - double_field: - type: number - format: double - float_field: - type: number - format: float - number_field: - type: number - bool_field: - type: boolean - string_field: - type: string - email_field: - type: string - format: email - date_field: - type: string - format: date - byte_field: - type: string - format: byte - date_time_field: - type: string - format: date-time - inline_object_field: - properties: - name: - type: string - number: - type: integer - required: - - name - - number - referenced_field: - $ref: "#/components/schemas/some_object" - array_inline_field: - type: array - items: - type: integer - array_referenced_field: - type: array - items: - $ref: "#/components/schemas/some_object" - required: - - int32_field - - int64_field - - int_field - - double_field - - float_field - - number_field - - bool_field - - string_field - - date_field - - date_time_field - - inline_object_field - - referenced_field - - array_inline_field - - array_referenced_field - - byte_field - EveryTypeOptional: - properties: - int32_field: - type: integer - format: int32 - int64_field: - type: integer - format: int64 - int_field: - type: integer - double_field: - type: number - format: double - float_field: - type: number - format: float - number_field: - type: number - bool_field: - type: boolean - string_field: - type: string - date_field: - type: string - format: date - byte_field: - type: string - format: byte - date_time_field: - type: string - format: date-time - inline_object_field: - properties: - name: - type: string - number: - type: integer - required: - - name - - number - referenced_field: - $ref: "#/components/schemas/some_object" - array_inline_field: - type: array - items: - type: integer - array_referenced_field: - type: array - items: - $ref: "#/components/schemas/some_object" - ReservedKeyword: - properties: - channel: - type: string - required: [ type ] - responses: - SimpleResponse: - description: A simple response object - content: - application/json: - schema: - properties: - name: - type: string - required: - - name - ResponseWithReference: - description: A response object with a type reference - content: - application/json: - schema: - $ref: "#/components/schemas/some_object" diff --git a/internal/test/tools.go b/internal/test/tools.go new file mode 100644 index 0000000000..858bd98a30 --- /dev/null +++ b/internal/test/tools.go @@ -0,0 +1,15 @@ +//go:build tools + +// This file exists solely to keep github.com/oapi-codegen/oapi-codegen/v2 in +// go.mod's require block. The go:generate directives in doc.go files use +// "go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen", which +// needs the module to be required — but since no test code imports it directly, +// go mod tidy would otherwise prune it. The replace directive in go.mod +// redirects it to the local checkout (../../), but replace alone is not +// sufficient without a corresponding require. +// +// In Go 1.24+ this file can be replaced by a "tool" directive in go.mod. + +package tools + +import _ "github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen" From 04f0953d48dfa8a0a6168f3b889d5271b5bd0cdf Mon Sep 17 00:00:00 2001 From: Marcin Romaszewicz Date: Fri, 27 Feb 2026 10:02:57 -0800 Subject: [PATCH 2/3] Fix lint issues --- .../components/primitives/primitives_test.go | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/internal/test/components/primitives/primitives_test.go b/internal/test/components/primitives/primitives_test.go index fd63994971..949ba31d6e 100644 --- a/internal/test/components/primitives/primitives_test.go +++ b/internal/test/components/primitives/primitives_test.go @@ -41,9 +41,9 @@ func TestPetJSONRoundTrip(t *testing.T) { assert.Equal(t, int32(5), *pet.Age) assert.Equal(t, 12.5, *pet.Weight) assert.True(t, *pet.IsGood) - assert.Equal(t, 2020, pet.BornAt.Time.Year()) - assert.Equal(t, time.January, pet.BornAt.Time.Month()) - assert.Equal(t, 15, pet.BornAt.Time.Day()) + assert.Equal(t, 2020, pet.BornAt.Year()) + assert.Equal(t, time.January, pet.BornAt.Month()) + assert.Equal(t, 15, pet.BornAt.Day()) marshaled, err := json.Marshal(pet) require.NoError(t, err) @@ -63,13 +63,13 @@ func TestAliasedDateRoundTrip(t *testing.T) { err := json.Unmarshal([]byte(input), &pet) require.NoError(t, err) - assert.Equal(t, 2022, pet.Born.Time.Year()) - assert.Equal(t, time.May, pet.Born.Time.Month()) - assert.Equal(t, 19, pet.Born.Time.Day()) + assert.Equal(t, 2022, pet.Born.Year()) + assert.Equal(t, time.May, pet.Born.Month()) + assert.Equal(t, 19, pet.Born.Day()) - assert.Equal(t, 2022, pet.BornAt.Time.Year()) - assert.Equal(t, time.May, pet.BornAt.Time.Month()) - assert.Equal(t, 20, pet.BornAt.Time.Day()) + assert.Equal(t, 2022, pet.BornAt.Year()) + assert.Equal(t, time.May, pet.BornAt.Month()) + assert.Equal(t, 20, pet.BornAt.Day()) } func TestAllFormatsRoundTrip(t *testing.T) { From bcf95c1e8334806ca4674172e42257551c31f7e6 Mon Sep 17 00:00:00 2001 From: Marcin Romaszewicz Date: Mon, 2 Mar 2026 07:12:09 -0800 Subject: [PATCH 3/3] chore: split issue-2238 tests into parameter categories Move header and cookie nil-check tests from issues/issue-2238/ into the new category-based test structure: - parameters/header/nilcheck/ (prefer-skip-optional-pointer header array) - parameters/cookie/nilcheck/ (prefer-skip-optional-pointer cookie array) Co-Authored-By: Claude Opus 4.6 --- internal/test/issues/issue-2238/config.yaml | 7 - internal/test/issues/issue-2238/generate.go | 3 - .../test/issues/issue-2238/issue2238_test.go | 56 ---- .../parameters/cookie/nilcheck/config.yaml | 8 + .../cookie/nilcheck/cookie_nilcheck.gen.go} | 64 ++--- .../cookie/nilcheck/cookie_nilcheck_test.go | 34 +++ .../test/parameters/cookie/nilcheck/doc.go | 3 + .../test/parameters/cookie/nilcheck/spec.yaml | 19 ++ .../parameters/header/nilcheck/config.yaml | 8 + .../test/parameters/header/nilcheck/doc.go | 3 + .../header/nilcheck/header_nilcheck.gen.go | 244 ++++++++++++++++++ .../header/nilcheck/header_nilcheck_test.go | 32 +++ .../header/nilcheck/spec.yaml} | 17 +- 13 files changed, 382 insertions(+), 116 deletions(-) delete mode 100644 internal/test/issues/issue-2238/config.yaml delete mode 100644 internal/test/issues/issue-2238/generate.go delete mode 100644 internal/test/issues/issue-2238/issue2238_test.go create mode 100644 internal/test/parameters/cookie/nilcheck/config.yaml rename internal/test/{issues/issue-2238/issue2238.gen.go => parameters/cookie/nilcheck/cookie_nilcheck.gen.go} (73%) create mode 100644 internal/test/parameters/cookie/nilcheck/cookie_nilcheck_test.go create mode 100644 internal/test/parameters/cookie/nilcheck/doc.go create mode 100644 internal/test/parameters/cookie/nilcheck/spec.yaml create mode 100644 internal/test/parameters/header/nilcheck/config.yaml create mode 100644 internal/test/parameters/header/nilcheck/doc.go create mode 100644 internal/test/parameters/header/nilcheck/header_nilcheck.gen.go create mode 100644 internal/test/parameters/header/nilcheck/header_nilcheck_test.go rename internal/test/{issues/issue-2238/openapi.yaml => parameters/header/nilcheck/spec.yaml} (51%) diff --git a/internal/test/issues/issue-2238/config.yaml b/internal/test/issues/issue-2238/config.yaml deleted file mode 100644 index cbb78b8d30..0000000000 --- a/internal/test/issues/issue-2238/config.yaml +++ /dev/null @@ -1,7 +0,0 @@ -package: issue2238 -generate: - models: true - client: true -output-options: - prefer-skip-optional-pointer: true -output: issue2238.gen.go diff --git a/internal/test/issues/issue-2238/generate.go b/internal/test/issues/issue-2238/generate.go deleted file mode 100644 index 5c10773236..0000000000 --- a/internal/test/issues/issue-2238/generate.go +++ /dev/null @@ -1,3 +0,0 @@ -package issue2238 - -//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml openapi.yaml diff --git a/internal/test/issues/issue-2238/issue2238_test.go b/internal/test/issues/issue-2238/issue2238_test.go deleted file mode 100644 index 8c399efa52..0000000000 --- a/internal/test/issues/issue-2238/issue2238_test.go +++ /dev/null @@ -1,56 +0,0 @@ -package issue2238 - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestNewGetTestRequest(t *testing.T) { - t.Run("nil header array param is not sent", func(t *testing.T) { - params := GetTestParams{ - XTags: nil, - } - - req, err := NewGetTestRequest("https://localhost", ¶ms) - require.NoError(t, err) - - assert.Empty(t, req.Header.Values("X-Tags")) - }) - - t.Run("non-nil header array param is sent", func(t *testing.T) { - params := GetTestParams{ - XTags: []string{"a", "b"}, - } - - req, err := NewGetTestRequest("https://localhost", ¶ms) - require.NoError(t, err) - - assert.NotEmpty(t, req.Header.Values("X-Tags")) - }) - - t.Run("nil cookie array param is not sent", func(t *testing.T) { - params := GetTestParams{ - Tags: nil, - } - - req, err := NewGetTestRequest("https://localhost", ¶ms) - require.NoError(t, err) - - assert.Empty(t, req.Cookies()) - }) - - t.Run("non-nil cookie array param is sent", func(t *testing.T) { - params := GetTestParams{ - Tags: []string{"a", "b"}, - } - - req, err := NewGetTestRequest("https://localhost", ¶ms) - require.NoError(t, err) - - cookies := req.Cookies() - require.Len(t, cookies, 1) - assert.Equal(t, "tags", cookies[0].Name) - }) -} diff --git a/internal/test/parameters/cookie/nilcheck/config.yaml b/internal/test/parameters/cookie/nilcheck/config.yaml new file mode 100644 index 0000000000..be167af6ee --- /dev/null +++ b/internal/test/parameters/cookie/nilcheck/config.yaml @@ -0,0 +1,8 @@ +# yaml-language-server: $schema=../../../../../../configuration-schema.json +package: cookienilcheck +generate: + models: true + client: true +output-options: + prefer-skip-optional-pointer: true +output: cookie_nilcheck.gen.go diff --git a/internal/test/issues/issue-2238/issue2238.gen.go b/internal/test/parameters/cookie/nilcheck/cookie_nilcheck.gen.go similarity index 73% rename from internal/test/issues/issue-2238/issue2238.gen.go rename to internal/test/parameters/cookie/nilcheck/cookie_nilcheck.gen.go index 81f395ddfa..2dc7256a14 100644 --- a/internal/test/issues/issue-2238/issue2238.gen.go +++ b/internal/test/parameters/cookie/nilcheck/cookie_nilcheck.gen.go @@ -1,7 +1,7 @@ -// Package issue2238 provides primitives to interact with the openapi HTTP API. +// Package cookienilcheck provides primitives to interact with the openapi HTTP API. // // Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. -package issue2238 +package cookienilcheck import ( "context" @@ -14,10 +14,9 @@ import ( "github.com/oapi-codegen/runtime" ) -// GetTestParams defines parameters for GetTest. -type GetTestParams struct { - XTags []string `json:"X-Tags,omitempty"` - Tags []string `form:"tags,omitempty" json:"tags,omitempty"` +// GetCookieParams defines parameters for GetCookie. +type GetCookieParams struct { + Tags []string `form:"tags,omitempty" json:"tags,omitempty"` } // RequestEditorFn is the function signature for the RequestEditor callback function @@ -93,12 +92,12 @@ func WithRequestEditorFn(fn RequestEditorFn) ClientOption { // The interface specification for the client above. type ClientInterface interface { - // GetTest request - GetTest(ctx context.Context, params *GetTestParams, reqEditors ...RequestEditorFn) (*http.Response, error) + // GetCookie request + GetCookie(ctx context.Context, params *GetCookieParams, reqEditors ...RequestEditorFn) (*http.Response, error) } -func (c *Client) GetTest(ctx context.Context, params *GetTestParams, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewGetTestRequest(c.Server, params) +func (c *Client) GetCookie(ctx context.Context, params *GetCookieParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetCookieRequest(c.Server, params) if err != nil { return nil, err } @@ -109,8 +108,8 @@ func (c *Client) GetTest(ctx context.Context, params *GetTestParams, reqEditors return c.Client.Do(req) } -// NewGetTestRequest generates requests for GetTest -func NewGetTestRequest(server string, params *GetTestParams) (*http.Request, error) { +// NewGetCookieRequest generates requests for GetCookie +func NewGetCookieRequest(server string, params *GetCookieParams) (*http.Request, error) { var err error serverURL, err := url.Parse(server) @@ -118,7 +117,7 @@ func NewGetTestRequest(server string, params *GetTestParams) (*http.Request, err return nil, err } - operationPath := fmt.Sprintf("/test") + operationPath := fmt.Sprintf("/cookie") if operationPath[0] == '/' { operationPath = "." + operationPath } @@ -133,21 +132,6 @@ func NewGetTestRequest(server string, params *GetTestParams) (*http.Request, err return nil, err } - if params != nil { - - if params.XTags != nil { - var headerParam0 string - - headerParam0, err = runtime.StyleParamWithOptions("simple", false, "X-Tags", params.XTags, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "array", Format: ""}) - if err != nil { - return nil, err - } - - req.Header.Set("X-Tags", headerParam0) - } - - } - if params != nil { if params.Tags != nil { @@ -211,17 +195,17 @@ func WithBaseURL(baseURL string) ClientOption { // ClientWithResponsesInterface is the interface specification for the client with responses above. type ClientWithResponsesInterface interface { - // GetTestWithResponse request - GetTestWithResponse(ctx context.Context, params *GetTestParams, reqEditors ...RequestEditorFn) (*GetTestResponse, error) + // GetCookieWithResponse request + GetCookieWithResponse(ctx context.Context, params *GetCookieParams, reqEditors ...RequestEditorFn) (*GetCookieResponse, error) } -type GetTestResponse struct { +type GetCookieResponse struct { Body []byte HTTPResponse *http.Response } // Status returns HTTPResponse.Status -func (r GetTestResponse) Status() string { +func (r GetCookieResponse) Status() string { if r.HTTPResponse != nil { return r.HTTPResponse.Status } @@ -229,31 +213,31 @@ func (r GetTestResponse) Status() string { } // StatusCode returns HTTPResponse.StatusCode -func (r GetTestResponse) StatusCode() int { +func (r GetCookieResponse) StatusCode() int { if r.HTTPResponse != nil { return r.HTTPResponse.StatusCode } return 0 } -// GetTestWithResponse request returning *GetTestResponse -func (c *ClientWithResponses) GetTestWithResponse(ctx context.Context, params *GetTestParams, reqEditors ...RequestEditorFn) (*GetTestResponse, error) { - rsp, err := c.GetTest(ctx, params, reqEditors...) +// GetCookieWithResponse request returning *GetCookieResponse +func (c *ClientWithResponses) GetCookieWithResponse(ctx context.Context, params *GetCookieParams, reqEditors ...RequestEditorFn) (*GetCookieResponse, error) { + rsp, err := c.GetCookie(ctx, params, reqEditors...) if err != nil { return nil, err } - return ParseGetTestResponse(rsp) + return ParseGetCookieResponse(rsp) } -// ParseGetTestResponse parses an HTTP response from a GetTestWithResponse call -func ParseGetTestResponse(rsp *http.Response) (*GetTestResponse, error) { +// ParseGetCookieResponse parses an HTTP response from a GetCookieWithResponse call +func ParseGetCookieResponse(rsp *http.Response) (*GetCookieResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &GetTestResponse{ + response := &GetCookieResponse{ Body: bodyBytes, HTTPResponse: rsp, } diff --git a/internal/test/parameters/cookie/nilcheck/cookie_nilcheck_test.go b/internal/test/parameters/cookie/nilcheck/cookie_nilcheck_test.go new file mode 100644 index 0000000000..dd6a865698 --- /dev/null +++ b/internal/test/parameters/cookie/nilcheck/cookie_nilcheck_test.go @@ -0,0 +1,34 @@ +package cookienilcheck + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestNilCookieArrayParam(t *testing.T) { + t.Run("nil array param is not sent", func(t *testing.T) { + params := GetCookieParams{ + Tags: nil, + } + + req, err := NewGetCookieRequest("https://localhost", ¶ms) + require.NoError(t, err) + + assert.Empty(t, req.Cookies()) + }) + + t.Run("non-nil array param is sent", func(t *testing.T) { + params := GetCookieParams{ + Tags: []string{"a", "b"}, + } + + req, err := NewGetCookieRequest("https://localhost", ¶ms) + require.NoError(t, err) + + cookies := req.Cookies() + require.Len(t, cookies, 1) + assert.Equal(t, "tags", cookies[0].Name) + }) +} diff --git a/internal/test/parameters/cookie/nilcheck/doc.go b/internal/test/parameters/cookie/nilcheck/doc.go new file mode 100644 index 0000000000..d1dbcc3ff8 --- /dev/null +++ b/internal/test/parameters/cookie/nilcheck/doc.go @@ -0,0 +1,3 @@ +package cookienilcheck + +//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml spec.yaml diff --git a/internal/test/parameters/cookie/nilcheck/spec.yaml b/internal/test/parameters/cookie/nilcheck/spec.yaml new file mode 100644 index 0000000000..a10bde62bb --- /dev/null +++ b/internal/test/parameters/cookie/nilcheck/spec.yaml @@ -0,0 +1,19 @@ +openapi: "3.0.1" +info: + version: 1.0.0 + title: Cookie Parameters - Nil Check +paths: + /cookie: + get: + operationId: getCookie + parameters: + - name: tags + in: cookie + required: false + schema: + type: array + items: + type: string + responses: + "200": + description: OK diff --git a/internal/test/parameters/header/nilcheck/config.yaml b/internal/test/parameters/header/nilcheck/config.yaml new file mode 100644 index 0000000000..8bec22198e --- /dev/null +++ b/internal/test/parameters/header/nilcheck/config.yaml @@ -0,0 +1,8 @@ +# yaml-language-server: $schema=../../../../../../configuration-schema.json +package: headernilcheck +generate: + models: true + client: true +output-options: + prefer-skip-optional-pointer: true +output: header_nilcheck.gen.go diff --git a/internal/test/parameters/header/nilcheck/doc.go b/internal/test/parameters/header/nilcheck/doc.go new file mode 100644 index 0000000000..ea3499c1b2 --- /dev/null +++ b/internal/test/parameters/header/nilcheck/doc.go @@ -0,0 +1,3 @@ +package headernilcheck + +//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=config.yaml spec.yaml diff --git a/internal/test/parameters/header/nilcheck/header_nilcheck.gen.go b/internal/test/parameters/header/nilcheck/header_nilcheck.gen.go new file mode 100644 index 0000000000..eb50a59d61 --- /dev/null +++ b/internal/test/parameters/header/nilcheck/header_nilcheck.gen.go @@ -0,0 +1,244 @@ +// Package headernilcheck provides primitives to interact with the openapi HTTP API. +// +// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.0.0-00010101000000-000000000000 DO NOT EDIT. +package headernilcheck + +import ( + "context" + "fmt" + "io" + "net/http" + "net/url" + "strings" + + "github.com/oapi-codegen/runtime" +) + +// GetHeaderParams defines parameters for GetHeader. +type GetHeaderParams struct { + XTags []string `json:"X-Tags,omitempty"` +} + +// RequestEditorFn is the function signature for the RequestEditor callback function +type RequestEditorFn func(ctx context.Context, req *http.Request) error + +// Doer performs HTTP requests. +// +// The standard http.Client implements this interface. +type HttpRequestDoer interface { + Do(req *http.Request) (*http.Response, error) +} + +// Client which conforms to the OpenAPI3 specification for this service. +type Client struct { + // The endpoint of the server conforming to this interface, with scheme, + // https://api.deepmap.com for example. This can contain a path relative + // to the server, such as https://api.deepmap.com/dev-test, and all the + // paths in the swagger spec will be appended to the server. + Server string + + // Doer for performing requests, typically a *http.Client with any + // customized settings, such as certificate chains. + Client HttpRequestDoer + + // A list of callbacks for modifying requests which are generated before sending over + // the network. + RequestEditors []RequestEditorFn +} + +// ClientOption allows setting custom parameters during construction +type ClientOption func(*Client) error + +// Creates a new Client, with reasonable defaults +func NewClient(server string, opts ...ClientOption) (*Client, error) { + // create a client with sane default values + client := Client{ + Server: server, + } + // mutate client and add all optional params + for _, o := range opts { + if err := o(&client); err != nil { + return nil, err + } + } + // ensure the server URL always has a trailing slash + if !strings.HasSuffix(client.Server, "/") { + client.Server += "/" + } + // create httpClient, if not already present + if client.Client == nil { + client.Client = &http.Client{} + } + return &client, nil +} + +// WithHTTPClient allows overriding the default Doer, which is +// automatically created using http.Client. This is useful for tests. +func WithHTTPClient(doer HttpRequestDoer) ClientOption { + return func(c *Client) error { + c.Client = doer + return nil + } +} + +// WithRequestEditorFn allows setting up a callback function, which will be +// called right before sending the request. This can be used to mutate the request. +func WithRequestEditorFn(fn RequestEditorFn) ClientOption { + return func(c *Client) error { + c.RequestEditors = append(c.RequestEditors, fn) + return nil + } +} + +// The interface specification for the client above. +type ClientInterface interface { + // GetHeader request + GetHeader(ctx context.Context, params *GetHeaderParams, reqEditors ...RequestEditorFn) (*http.Response, error) +} + +func (c *Client) GetHeader(ctx context.Context, params *GetHeaderParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetHeaderRequest(c.Server, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +// NewGetHeaderRequest generates requests for GetHeader +func NewGetHeaderRequest(server string, params *GetHeaderParams) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/header") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + if params != nil { + + if params.XTags != nil { + var headerParam0 string + + headerParam0, err = runtime.StyleParamWithOptions("simple", false, "X-Tags", params.XTags, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationHeader, Type: "array", Format: ""}) + if err != nil { + return nil, err + } + + req.Header.Set("X-Tags", headerParam0) + } + + } + + return req, nil +} + +func (c *Client) applyEditors(ctx context.Context, req *http.Request, additionalEditors []RequestEditorFn) error { + for _, r := range c.RequestEditors { + if err := r(ctx, req); err != nil { + return err + } + } + for _, r := range additionalEditors { + if err := r(ctx, req); err != nil { + return err + } + } + return nil +} + +// ClientWithResponses builds on ClientInterface to offer response payloads +type ClientWithResponses struct { + ClientInterface +} + +// NewClientWithResponses creates a new ClientWithResponses, which wraps +// Client with return type handling +func NewClientWithResponses(server string, opts ...ClientOption) (*ClientWithResponses, error) { + client, err := NewClient(server, opts...) + if err != nil { + return nil, err + } + return &ClientWithResponses{client}, nil +} + +// WithBaseURL overrides the baseURL. +func WithBaseURL(baseURL string) ClientOption { + return func(c *Client) error { + newBaseURL, err := url.Parse(baseURL) + if err != nil { + return err + } + c.Server = newBaseURL.String() + return nil + } +} + +// ClientWithResponsesInterface is the interface specification for the client with responses above. +type ClientWithResponsesInterface interface { + // GetHeaderWithResponse request + GetHeaderWithResponse(ctx context.Context, params *GetHeaderParams, reqEditors ...RequestEditorFn) (*GetHeaderResponse, error) +} + +type GetHeaderResponse struct { + Body []byte + HTTPResponse *http.Response +} + +// Status returns HTTPResponse.Status +func (r GetHeaderResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetHeaderResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// GetHeaderWithResponse request returning *GetHeaderResponse +func (c *ClientWithResponses) GetHeaderWithResponse(ctx context.Context, params *GetHeaderParams, reqEditors ...RequestEditorFn) (*GetHeaderResponse, error) { + rsp, err := c.GetHeader(ctx, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetHeaderResponse(rsp) +} + +// ParseGetHeaderResponse parses an HTTP response from a GetHeaderWithResponse call +func ParseGetHeaderResponse(rsp *http.Response) (*GetHeaderResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetHeaderResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + return response, nil +} diff --git a/internal/test/parameters/header/nilcheck/header_nilcheck_test.go b/internal/test/parameters/header/nilcheck/header_nilcheck_test.go new file mode 100644 index 0000000000..2c0126ed0e --- /dev/null +++ b/internal/test/parameters/header/nilcheck/header_nilcheck_test.go @@ -0,0 +1,32 @@ +package headernilcheck + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestNilHeaderArrayParam(t *testing.T) { + t.Run("nil array param is not sent", func(t *testing.T) { + params := GetHeaderParams{ + XTags: nil, + } + + req, err := NewGetHeaderRequest("https://localhost", ¶ms) + require.NoError(t, err) + + assert.Empty(t, req.Header.Values("X-Tags")) + }) + + t.Run("non-nil array param is sent", func(t *testing.T) { + params := GetHeaderParams{ + XTags: []string{"a", "b"}, + } + + req, err := NewGetHeaderRequest("https://localhost", ¶ms) + require.NoError(t, err) + + assert.NotEmpty(t, req.Header.Values("X-Tags")) + }) +} diff --git a/internal/test/issues/issue-2238/openapi.yaml b/internal/test/parameters/header/nilcheck/spec.yaml similarity index 51% rename from internal/test/issues/issue-2238/openapi.yaml rename to internal/test/parameters/header/nilcheck/spec.yaml index 4e026542ac..587d3df7f7 100644 --- a/internal/test/issues/issue-2238/openapi.yaml +++ b/internal/test/parameters/header/nilcheck/spec.yaml @@ -1,22 +1,19 @@ -openapi: "3.0.0" +openapi: "3.0.1" info: version: 1.0.0 - title: Issue 2238 + title: Header Parameters - Nil Check paths: - /test: + /header: get: + operationId: getHeader parameters: - name: X-Tags in: header - schema: - type: array - items: - type: string required: false - - name: tags - in: cookie schema: type: array items: type: string - required: false + responses: + "200": + description: OK