From 759311e72c5abe27e06f2513f5b211f100b436d8 Mon Sep 17 00:00:00 2001 From: Mengnan Gong Date: Fri, 30 Jun 2023 15:02:45 +0800 Subject: [PATCH] [Gorilla] update the `MiddlewareFunc` type for compatibility This PR ported the fix https://github.com/deepmap/oapi-codegen/pull/578 to gorilla/mux, so the gorilla/mux users can have a consistent behaviour too. Signed-off-by: Mengnan Gong --- README.md | 42 -- cmd/oapi-codegen/oapi-codegen.go | 4 +- .../authenticated-api/echo/api/api.gen.go | 18 +- examples/authenticated-api/echo/main.go | 6 +- .../custom-client-type.gen.go | 2 +- .../petstore-expanded/chi/api/petstore.gen.go | 56 +-- .../petstore-expanded/chi/api/petstore.go | 4 +- examples/petstore-expanded/chi/petstore.go | 5 +- .../echo/api/petstore-server.gen.go | 12 +- .../petstore-expanded/echo/api/petstore.go | 4 +- examples/petstore-expanded/echo/petstore.go | 5 +- .../fiber/api/petstore-server.gen.go | 12 +- .../petstore-expanded/fiber/api/petstore.go | 2 +- examples/petstore-expanded/fiber/petstore.go | 7 +- .../gin/api/petstore-server.gen.go | 20 +- .../petstore-expanded/gin/api/petstore.go | 4 +- examples/petstore-expanded/gin/petstore.go | 7 +- .../petstore-expanded/gin/petstore_test.go | 2 +- .../gorilla/api/petstore.gen.go | 38 +- .../petstore-expanded/gorilla/api/petstore.go | 4 +- .../petstore-expanded/gorilla/petstore.go | 5 +- .../petstore-expanded/petstore-client.gen.go | 10 +- .../strict/api/petstore-server.gen.go | 56 +-- .../petstore-expanded/strict/api/petstore.go | 2 +- examples/petstore-expanded/strict/petstore.go | 5 +- go.mod | 68 +-- go.sum | 180 +++---- internal/test/all_of/v1/openapi.gen.go | 12 +- internal/test/all_of/v2/openapi.gen.go | 12 +- internal/test/any_of/param/param.gen.go | 2 +- internal/test/client/client.gen.go | 48 +- internal/test/externalref/externalref.gen.go | 12 +- .../externalref/packageA/externalref.gen.go | 12 +- .../externalref/packageB/externalref.gen.go | 12 +- internal/test/issues/issue-1087/api.gen.go | 453 ------------------ .../test/issues/issue-1087/deps/config.yaml | 8 - .../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 | 10 - internal/test/issues/issue-1087/spec.yaml | 109 ----- .../issues/issue-1093/api/child/child.gen.go | 232 --------- .../issue-1093/api/parent/parent.gen.go | 229 --------- .../test/issues/issue-1093/child.api.yaml | 21 - .../test/issues/issue-1093/child.cfg.yaml | 10 - 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 | 9 - internal/test/issues/issue-1127/api.gen.go | 18 - internal/test/issues/issue-1127/doc.go | 3 - .../test/issues/issue-1127/server.config.yaml | 5 - 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 - .../test/issues/issue-1168/server.config.yaml | 5 - internal/test/issues/issue-1168/spec.yaml | 95 ---- internal/test/issues/issue-312/issue.gen.go | 18 +- internal/test/issues/issue-52/issue.gen.go | 14 +- internal/test/issues/issue-832/issue.gen.go | 12 +- .../issue-grab_import_names/issue.gen.go | 14 +- .../issue-illegal_enum_names/issue.gen.go | 14 +- .../gen/spec_base/issue.gen.go | 22 +- .../gen/spec_ext/issue.gen.go | 4 - internal/test/parameters/parameters.gen.go | 54 +-- internal/test/schemas/schemas.gen.go | 36 +- internal/test/server/server.gen.go | 105 +--- internal/test/strict-server/chi/server.gen.go | 170 ++----- .../test/strict-server/client/client.gen.go | 53 +- .../test/strict-server/echo/server.gen.go | 66 +-- .../test/strict-server/fiber/server.gen.go | 61 +-- internal/test/strict-server/gin/server.gen.go | 73 ++- .../test/strict-server/strict-schema.yaml | 3 - pkg/chi-middleware/oapi_validate.go | 9 +- pkg/chi-middleware/oapi_validate_test.go | 4 +- pkg/codegen/codegen.go | 50 +- pkg/codegen/codegen_test.go | 47 +- pkg/codegen/extension.go | 12 - pkg/codegen/extension_test.go | 54 --- pkg/codegen/inline.go | 8 +- pkg/codegen/operations.go | 36 +- pkg/codegen/schema.go | 18 - pkg/codegen/template_helpers.go | 4 +- pkg/codegen/templates/chi/chi-interface.tmpl | 10 - pkg/codegen/templates/chi/chi-middleware.tmpl | 4 +- .../templates/client-with-responses.tmpl | 2 +- pkg/codegen/templates/client.tmpl | 4 +- .../templates/fiber/fiber-middleware.tmpl | 8 +- pkg/codegen/templates/gin/gin-wrappers.tmpl | 10 +- .../templates/gorilla/gorilla-middleware.tmpl | 8 +- pkg/codegen/templates/inline.tmpl | 12 +- pkg/codegen/templates/strict/strict-echo.tmpl | 2 +- .../strict/strict-fiber-interface.tmpl | 2 +- .../templates/strict/strict-fiber.tmpl | 2 +- pkg/codegen/templates/strict/strict-gin.tmpl | 2 +- pkg/codegen/templates/strict/strict-http.tmpl | 2 +- .../templates/strict/strict-interface.tmpl | 12 +- .../x-go-type-skip-optional-pointer.yaml | 54 --- pkg/codegen/utils.go | 14 - pkg/fiber-middleware/oapi_validate.go | 2 +- pkg/gin-middleware/oapi_validate.go | 16 +- pkg/gin-middleware/oapi_validate_test.go | 4 +- pkg/middleware/oapi_validate.go | 9 +- pkg/middleware/oapi_validate_test.go | 4 +- pkg/runtime/bindparam.go | 2 +- pkg/runtime/bindstring.go | 2 +- pkg/runtime/styleparam.go | 2 +- pkg/testutil/request_helpers.go | 2 +- pkg/testutil/response_handlers.go | 2 +- pkg/types/email.go | 19 +- pkg/types/email_test.go | 175 +------ pkg/util/inputmapping.go | 4 +- 113 files changed, 678 insertions(+), 3151 deletions(-) delete mode 100644 internal/test/issues/issue-1087/api.gen.go delete mode 100644 internal/test/issues/issue-1087/deps/config.yaml 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/server.config.yaml 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/server.config.yaml delete mode 100644 internal/test/issues/issue-1168/spec.yaml delete mode 100644 pkg/codegen/test_specs/x-go-type-skip-optional-pointer.yaml diff --git a/README.md b/README.md index c31534988..3ef3cdcf9 100644 --- a/README.md +++ b/README.md @@ -28,34 +28,6 @@ something via utility code or reflection, it's probably a better approach than code generation, which is fragile due to the very dynamic nature of OpenAPI and the very static nature of Go. -## Contributing - -I would like to pre-emptively extend my gratitude to anyone who takes the time -to improve this project. - -Oapi-codegen is being actively maintained, however the two people who do so -are very busy, and can only set aside time for this project every once in a while, -so our release cadence is slow and conservative. - -Generating code which others depend on, which is based on something as complex -as OpenAPI is fraught with many edge cases, and we prefer to leave things as -they are if there is a reasonable workaround. - -If you do find a case where oapi-codegen is broken, and would like to submit a PR, -we are very grateful, and will happily look at it. - -Since most commits affect generated code, before sending your PR, please -ensure that all boilerplate has been regenerated. You can do this from the top level -of the repository by running: - - go generate ./... - -I realize that our code isn't entirely idiomatic with respect to comments, and -variable naming and initialisms, especially the generated code, but I'm reluctant -to merge PR's which change this, due to the breakage they will cause for others. If -you rename anything under `/pkg` or change the names of variables in generated -code, you will break other people's code. It's safe to rename internal names. - ## Overview We're going to use the OpenAPI example of the @@ -596,20 +568,6 @@ which help you to use the various OpenAPI 3 Authentication mechanism. will override any default value. This extended property isn't supported in all parts of OpenAPI, so please refer to the spec as to where it's allowed. Swagger validation tools will flag incorrect usage of this property. -- `x-go-type-skip-optional-pointer`: specifies if the Go type should or should not be a pointer - when the property is optional. If set to true, the type will not be a pointer if the field is - optional or nullable. If set to false, the type will be a pointer. - - ```yaml - properties: - field: - type: string - x-go-type-skip-optional-pointer: true - ``` - - In the example above, the `field` field will be of type `string` instead of `*string`. This is - useful when you want to handle the case of an empty string differently than a null value. - - `x-go-name`: specifies Go field name. It allows you to specify the field name for a schema, and will override any default value. This extended property isn't supported in all parts of OpenAPI, so please refer to the spec as to where it's allowed. Swagger validation tools will diff --git a/cmd/oapi-codegen/oapi-codegen.go b/cmd/oapi-codegen/oapi-codegen.go index ad9f78c0d..ae81acfca 100644 --- a/cmd/oapi-codegen/oapi-codegen.go +++ b/cmd/oapi-codegen/oapi-codegen.go @@ -269,7 +269,7 @@ func main() { } if opts.OutputFile != "" { - err = os.WriteFile(opts.OutputFile, []byte(code), 0o644) + err = os.WriteFile(opts.OutputFile, []byte(code), 0644) if err != nil { errExit("error writing generated code to file: %s\n", err) } @@ -279,7 +279,7 @@ func main() { } func loadTemplateOverrides(templatesDir string) (map[string]string, error) { - templates := make(map[string]string) + var templates = make(map[string]string) if templatesDir == "" { return templates, nil diff --git a/examples/authenticated-api/echo/api/api.gen.go b/examples/authenticated-api/echo/api/api.gen.go index 9e69dd013..b9f7c1328 100644 --- a/examples/authenticated-api/echo/api/api.gen.go +++ b/examples/authenticated-api/echo/api/api.gen.go @@ -123,7 +123,7 @@ type ClientInterface interface { // ListThings request ListThings(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) - // AddThingWithBody request with any body + // AddThing request with any body AddThingWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) AddThing(ctx context.Context, body AddThingJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) @@ -275,10 +275,10 @@ func WithBaseURL(baseURL string) ClientOption { // ClientWithResponsesInterface is the interface specification for the client with responses above. type ClientWithResponsesInterface interface { - // ListThingsWithResponse request + // ListThings request ListThingsWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*ListThingsResponse, error) - // AddThingWithBodyWithResponse request with any body + // AddThing request with any body AddThingWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*AddThingResponse, error) AddThingWithResponse(ctx context.Context, body AddThingJSONRequestBody, reqEditors ...RequestEditorFn) (*AddThingResponse, error) @@ -497,16 +497,16 @@ var swaggerSpec = []string{ 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) + return nil, fmt.Errorf("error base64 decoding spec: %s", err) } zr, err := gzip.NewReader(bytes.NewReader(zipped)) if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) + return nil, fmt.Errorf("error decompressing spec: %s", err) } var buf bytes.Buffer _, err = buf.ReadFrom(zr) if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) + return nil, fmt.Errorf("error decompressing spec: %s", err) } return buf.Bytes(), nil @@ -524,7 +524,7 @@ func decodeSpecCached() func() ([]byte, error) { // 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)) + var res = make(map[string]func() ([]byte, error)) if len(pathToFile) > 0 { res[pathToFile] = rawSpec } @@ -538,12 +538,12 @@ func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { // 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("") + var resolvePath = PathToRawSpec("") loader := openapi3.NewLoader() loader.IsExternalRefsAllowed = true loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() + var pathToFile = url.String() pathToFile = path.Clean(pathToFile) getSpec, ok := resolvePath[pathToFile] if !ok { diff --git a/examples/authenticated-api/echo/main.go b/examples/authenticated-api/echo/main.go index d28c28803..0bd6ff245 100644 --- a/examples/authenticated-api/echo/main.go +++ b/examples/authenticated-api/echo/main.go @@ -2,8 +2,8 @@ package main import ( "flag" + "fmt" "log" - "net" "github.com/deepmap/oapi-codegen/examples/authenticated-api/echo/api" "github.com/deepmap/oapi-codegen/examples/authenticated-api/echo/server" @@ -12,7 +12,7 @@ import ( ) func main() { - port := flag.String("port", "8080", "port where to serve traffic") + var port = flag.Int("port", 8080, "port where to serve traffic") e := echo.New() @@ -50,5 +50,5 @@ func main() { log.Println("Reader token", string(readerJWS)) log.Println("Writer token", string(writerJWS)) - e.Logger.Fatal(e.Start(net.JoinHostPort("0.0.0.0", *port))) + e.Logger.Fatal(e.Start(fmt.Sprintf("0.0.0.0:%d", *port))) } diff --git a/examples/custom-client-type/custom-client-type.gen.go b/examples/custom-client-type/custom-client-type.gen.go index aad5444d4..34c34ea99 100644 --- a/examples/custom-client-type/custom-client-type.gen.go +++ b/examples/custom-client-type/custom-client-type.gen.go @@ -177,7 +177,7 @@ func WithBaseURL(baseURL string) ClientOption { // ClientWithResponsesInterface is the interface specification for the client with responses above. type ClientWithResponsesInterface interface { - // GetClientWithResponse request + // GetClient request GetClientWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*GetClientResponse, error) } diff --git a/examples/petstore-expanded/chi/api/petstore.gen.go b/examples/petstore-expanded/chi/api/petstore.gen.go index bf349f4b7..59e517c8c 100644 --- a/examples/petstore-expanded/chi/api/petstore.gen.go +++ b/examples/petstore-expanded/chi/api/petstore.gen.go @@ -76,34 +76,6 @@ type ServerInterface interface { FindPetByID(w http.ResponseWriter, r *http.Request, id int64) } -// Unimplemented server implementation that returns http.StatusNotImplemented for each endpoint. - -type Unimplemented struct{} - -// Returns all pets -// (GET /pets) -func (_ Unimplemented) FindPets(w http.ResponseWriter, r *http.Request, params FindPetsParams) { - w.WriteHeader(http.StatusNotImplemented) -} - -// Creates a new pet -// (POST /pets) -func (_ Unimplemented) AddPet(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusNotImplemented) -} - -// Deletes a pet by ID -// (DELETE /pets/{id}) -func (_ Unimplemented) DeletePet(w http.ResponseWriter, r *http.Request, id int64) { - w.WriteHeader(http.StatusNotImplemented) -} - -// Returns a pet by ID -// (GET /pets/{id}) -func (_ Unimplemented) FindPetByID(w http.ResponseWriter, r *http.Request, id int64) { - w.WriteHeader(http.StatusNotImplemented) -} - // ServerInterfaceWrapper converts contexts to parameters. type ServerInterfaceWrapper struct { Handler ServerInterface @@ -138,9 +110,9 @@ func (siw *ServerInterfaceWrapper) FindPets(w http.ResponseWriter, r *http.Reque return } - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var handler http.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { siw.Handler.FindPets(w, r, params) - })) + }) for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { handler = siw.HandlerMiddlewares[i](handler) @@ -153,9 +125,9 @@ func (siw *ServerInterfaceWrapper) FindPets(w http.ResponseWriter, r *http.Reque func (siw *ServerInterfaceWrapper) AddPet(w http.ResponseWriter, r *http.Request) { ctx := r.Context() - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var handler http.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { siw.Handler.AddPet(w, r) - })) + }) for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { handler = siw.HandlerMiddlewares[i](handler) @@ -179,9 +151,9 @@ func (siw *ServerInterfaceWrapper) DeletePet(w http.ResponseWriter, r *http.Requ return } - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var handler http.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { siw.Handler.DeletePet(w, r, id) - })) + }) for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { handler = siw.HandlerMiddlewares[i](handler) @@ -205,9 +177,9 @@ func (siw *ServerInterfaceWrapper) FindPetByID(w http.ResponseWriter, r *http.Re return } - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var handler http.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { siw.Handler.FindPetByID(w, r, id) - })) + }) for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { handler = siw.HandlerMiddlewares[i](handler) @@ -383,16 +355,16 @@ var swaggerSpec = []string{ 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) + return nil, fmt.Errorf("error base64 decoding spec: %s", err) } zr, err := gzip.NewReader(bytes.NewReader(zipped)) if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) + return nil, fmt.Errorf("error decompressing spec: %s", err) } var buf bytes.Buffer _, err = buf.ReadFrom(zr) if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) + return nil, fmt.Errorf("error decompressing spec: %s", err) } return buf.Bytes(), nil @@ -410,7 +382,7 @@ func decodeSpecCached() func() ([]byte, error) { // 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)) + var res = make(map[string]func() ([]byte, error)) if len(pathToFile) > 0 { res[pathToFile] = rawSpec } @@ -424,12 +396,12 @@ func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { // 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("") + var resolvePath = PathToRawSpec("") loader := openapi3.NewLoader() loader.IsExternalRefsAllowed = true loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() + var pathToFile = url.String() pathToFile = path.Clean(pathToFile) getSpec, ok := resolvePath[pathToFile] if !ok { diff --git a/examples/petstore-expanded/chi/api/petstore.go b/examples/petstore-expanded/chi/api/petstore.go index ea5b9aa8d..838c96116 100644 --- a/examples/petstore-expanded/chi/api/petstore.go +++ b/examples/petstore-expanded/chi/api/petstore.go @@ -26,7 +26,7 @@ func NewPetStore() *PetStore { } } -// sendPetStoreError wraps sending of an error in the Error format, and +// This function wraps sending of an error in the Error format, and // handling the failure to marshal that. func sendPetStoreError(w http.ResponseWriter, code int, message string) { petErr := Error{ @@ -89,7 +89,7 @@ func (p *PetStore) AddPet(w http.ResponseWriter, r *http.Request) { pet.Name = newPet.Name pet.Tag = newPet.Tag pet.Id = p.NextId - p.NextId++ + p.NextId = p.NextId + 1 // Insert into map p.Pets[pet.Id] = pet diff --git a/examples/petstore-expanded/chi/petstore.go b/examples/petstore-expanded/chi/petstore.go index c4cfa2feb..cdf725e9b 100644 --- a/examples/petstore-expanded/chi/petstore.go +++ b/examples/petstore-expanded/chi/petstore.go @@ -8,7 +8,6 @@ import ( "flag" "fmt" "log" - "net" "net/http" "os" @@ -18,7 +17,7 @@ import ( ) func main() { - port := flag.String("port", "8080", "Port for test HTTP server") + var port = flag.Int("port", 8080, "Port for test HTTP server") flag.Parse() swagger, err := api.GetSwagger() @@ -46,7 +45,7 @@ func main() { s := &http.Server{ Handler: r, - Addr: net.JoinHostPort("0.0.0.0", *port), + Addr: fmt.Sprintf("0.0.0.0:%d", *port), } // And we serve HTTP until the world ends. diff --git a/examples/petstore-expanded/echo/api/petstore-server.gen.go b/examples/petstore-expanded/echo/api/petstore-server.gen.go index 5ee2daf35..bb088e099 100644 --- a/examples/petstore-expanded/echo/api/petstore-server.gen.go +++ b/examples/petstore-expanded/echo/api/petstore-server.gen.go @@ -179,16 +179,16 @@ var swaggerSpec = []string{ 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) + return nil, fmt.Errorf("error base64 decoding spec: %s", err) } zr, err := gzip.NewReader(bytes.NewReader(zipped)) if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) + return nil, fmt.Errorf("error decompressing spec: %s", err) } var buf bytes.Buffer _, err = buf.ReadFrom(zr) if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) + return nil, fmt.Errorf("error decompressing spec: %s", err) } return buf.Bytes(), nil @@ -206,7 +206,7 @@ func decodeSpecCached() func() ([]byte, error) { // 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)) + var res = make(map[string]func() ([]byte, error)) if len(pathToFile) > 0 { res[pathToFile] = rawSpec } @@ -220,12 +220,12 @@ func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { // 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("") + var resolvePath = PathToRawSpec("") loader := openapi3.NewLoader() loader.IsExternalRefsAllowed = true loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() + var pathToFile = url.String() pathToFile = path.Clean(pathToFile) getSpec, ok := resolvePath[pathToFile] if !ok { diff --git a/examples/petstore-expanded/echo/api/petstore.go b/examples/petstore-expanded/echo/api/petstore.go index a95997cb2..65229d0bb 100644 --- a/examples/petstore-expanded/echo/api/petstore.go +++ b/examples/petstore-expanded/echo/api/petstore.go @@ -39,7 +39,7 @@ func NewPetStore() *PetStore { } } -// sendPetStoreError wraps sending of an error in the Error format, and +// This function wraps sending of an error in the Error format, and // handling the failure to marshal that. func sendPetStoreError(ctx echo.Context, code int, message string) error { petErr := models.Error{ @@ -99,7 +99,7 @@ func (p *PetStore) AddPet(ctx echo.Context) error { pet.Name = newPet.Name pet.Tag = newPet.Tag pet.Id = p.NextId - p.NextId++ + p.NextId = p.NextId + 1 // Insert into map p.Pets[pet.Id] = pet diff --git a/examples/petstore-expanded/echo/petstore.go b/examples/petstore-expanded/echo/petstore.go index bf28fd76d..af0ae8310 100644 --- a/examples/petstore-expanded/echo/petstore.go +++ b/examples/petstore-expanded/echo/petstore.go @@ -8,7 +8,6 @@ package main import ( "flag" "fmt" - "net" "os" "github.com/deepmap/oapi-codegen/examples/petstore-expanded/echo/api" @@ -18,7 +17,7 @@ import ( ) func main() { - port := flag.String("port", "8080", "Port for test HTTP server") + var port = flag.Int("port", 8080, "Port for test HTTP server") flag.Parse() swagger, err := api.GetSwagger() @@ -46,5 +45,5 @@ func main() { api.RegisterHandlers(e, petStore) // And we serve HTTP until the world ends. - e.Logger.Fatal(e.Start(net.JoinHostPort("0.0.0.0", *port))) + e.Logger.Fatal(e.Start(fmt.Sprintf("0.0.0.0:%d", *port))) } diff --git a/examples/petstore-expanded/fiber/api/petstore-server.gen.go b/examples/petstore-expanded/fiber/api/petstore-server.gen.go index b0f5ac588..a55486c1d 100644 --- a/examples/petstore-expanded/fiber/api/petstore-server.gen.go +++ b/examples/petstore-expanded/fiber/api/petstore-server.gen.go @@ -178,16 +178,16 @@ var swaggerSpec = []string{ 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) + return nil, fmt.Errorf("error base64 decoding spec: %s", err) } zr, err := gzip.NewReader(bytes.NewReader(zipped)) if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) + return nil, fmt.Errorf("error decompressing spec: %s", err) } var buf bytes.Buffer _, err = buf.ReadFrom(zr) if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) + return nil, fmt.Errorf("error decompressing spec: %s", err) } return buf.Bytes(), nil @@ -205,7 +205,7 @@ func decodeSpecCached() func() ([]byte, error) { // 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)) + var res = make(map[string]func() ([]byte, error)) if len(pathToFile) > 0 { res[pathToFile] = rawSpec } @@ -219,12 +219,12 @@ func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { // 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("") + var resolvePath = PathToRawSpec("") loader := openapi3.NewLoader() loader.IsExternalRefsAllowed = true loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() + var pathToFile = url.String() pathToFile = path.Clean(pathToFile) getSpec, ok := resolvePath[pathToFile] if !ok { diff --git a/examples/petstore-expanded/fiber/api/petstore.go b/examples/petstore-expanded/fiber/api/petstore.go index f69566b81..60ecd58ff 100644 --- a/examples/petstore-expanded/fiber/api/petstore.go +++ b/examples/petstore-expanded/fiber/api/petstore.go @@ -94,7 +94,7 @@ func (p *PetStore) AddPet(c *fiber.Ctx) error { pet.Name = newPet.Name pet.Tag = newPet.Tag pet.Id = p.NextId - p.NextId++ + p.NextId = p.NextId + 1 // Insert into map p.Pets[pet.Id] = pet diff --git a/examples/petstore-expanded/fiber/petstore.go b/examples/petstore-expanded/fiber/petstore.go index f09e9c893..344752bbb 100644 --- a/examples/petstore-expanded/fiber/petstore.go +++ b/examples/petstore-expanded/fiber/petstore.go @@ -8,7 +8,6 @@ import ( "flag" "fmt" "log" - "net" "os" "github.com/gofiber/fiber/v2" @@ -18,7 +17,9 @@ import ( ) func main() { - port := flag.String("port", "8080", "Port for test HTTP server") + + var port = flag.Int("port", 8080, "Port for test HTTP server") + flag.Parse() // Create an instance of our handler which satisfies the generated interface @@ -27,7 +28,7 @@ func main() { s := NewFiberPetServer(petStore) // And we serve HTTP until the world ends. - log.Fatal(s.Listen(net.JoinHostPort("0.0.0.0", *port))) + log.Fatal(s.Listen(fmt.Sprintf("localhost:%d", *port))) } func NewFiberPetServer(petStore *api.PetStore) *fiber.App { diff --git a/examples/petstore-expanded/gin/api/petstore-server.gen.go b/examples/petstore-expanded/gin/api/petstore-server.gen.go index 8da56c16a..3b0368db5 100644 --- a/examples/petstore-expanded/gin/api/petstore-server.gen.go +++ b/examples/petstore-expanded/gin/api/petstore-server.gen.go @@ -55,7 +55,7 @@ func (siw *ServerInterfaceWrapper) FindPets(c *gin.Context) { err = runtime.BindQueryParameter("form", true, false, "tags", c.Request.URL.Query(), ¶ms.Tags) if err != nil { - siw.ErrorHandler(c, fmt.Errorf("Invalid format for parameter tags: %w", err), http.StatusBadRequest) + siw.ErrorHandler(c, fmt.Errorf("Invalid format for parameter tags: %s", err), http.StatusBadRequest) return } @@ -63,7 +63,7 @@ func (siw *ServerInterfaceWrapper) FindPets(c *gin.Context) { err = runtime.BindQueryParameter("form", true, false, "limit", c.Request.URL.Query(), ¶ms.Limit) if err != nil { - siw.ErrorHandler(c, fmt.Errorf("Invalid format for parameter limit: %w", err), http.StatusBadRequest) + siw.ErrorHandler(c, fmt.Errorf("Invalid format for parameter limit: %s", err), http.StatusBadRequest) return } @@ -100,7 +100,7 @@ func (siw *ServerInterfaceWrapper) DeletePet(c *gin.Context) { err = runtime.BindStyledParameter("simple", false, "id", c.Param("id"), &id) if err != nil { - siw.ErrorHandler(c, fmt.Errorf("Invalid format for parameter id: %w", err), http.StatusBadRequest) + siw.ErrorHandler(c, fmt.Errorf("Invalid format for parameter id: %s", err), http.StatusBadRequest) return } @@ -124,7 +124,7 @@ func (siw *ServerInterfaceWrapper) FindPetByID(c *gin.Context) { err = runtime.BindStyledParameter("simple", false, "id", c.Param("id"), &id) if err != nil { - siw.ErrorHandler(c, fmt.Errorf("Invalid format for parameter id: %w", err), http.StatusBadRequest) + siw.ErrorHandler(c, fmt.Errorf("Invalid format for parameter id: %s", err), http.StatusBadRequest) return } @@ -209,16 +209,16 @@ var swaggerSpec = []string{ 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) + return nil, fmt.Errorf("error base64 decoding spec: %s", err) } zr, err := gzip.NewReader(bytes.NewReader(zipped)) if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) + return nil, fmt.Errorf("error decompressing spec: %s", err) } var buf bytes.Buffer _, err = buf.ReadFrom(zr) if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) + return nil, fmt.Errorf("error decompressing spec: %s", err) } return buf.Bytes(), nil @@ -236,7 +236,7 @@ func decodeSpecCached() func() ([]byte, error) { // 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)) + var res = make(map[string]func() ([]byte, error)) if len(pathToFile) > 0 { res[pathToFile] = rawSpec } @@ -250,12 +250,12 @@ func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { // 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("") + var resolvePath = PathToRawSpec("") loader := openapi3.NewLoader() loader.IsExternalRefsAllowed = true loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() + var pathToFile = url.String() pathToFile = path.Clean(pathToFile) getSpec, ok := resolvePath[pathToFile] if !ok { diff --git a/examples/petstore-expanded/gin/api/petstore.go b/examples/petstore-expanded/gin/api/petstore.go index d482863e7..2654d3798 100644 --- a/examples/petstore-expanded/gin/api/petstore.go +++ b/examples/petstore-expanded/gin/api/petstore.go @@ -38,7 +38,7 @@ func NewPetStore() *PetStore { } } -// sendPetStoreError wraps sending of an error in the Error format, and +// This function wraps sending of an error in the Error format, and // handling the failure to marshal that. func sendPetStoreError(c *gin.Context, code int, message string) { petErr := Error{ @@ -98,7 +98,7 @@ func (p *PetStore) AddPet(c *gin.Context) { pet.Name = newPet.Name pet.Tag = newPet.Tag pet.Id = p.NextId - p.NextId++ + p.NextId = p.NextId + 1 // Insert into map p.Pets[pet.Id] = pet diff --git a/examples/petstore-expanded/gin/petstore.go b/examples/petstore-expanded/gin/petstore.go index 50f47e672..a5b40a2f4 100644 --- a/examples/petstore-expanded/gin/petstore.go +++ b/examples/petstore-expanded/gin/petstore.go @@ -8,7 +8,6 @@ import ( "flag" "fmt" "log" - "net" "net/http" "os" @@ -18,7 +17,7 @@ import ( middleware "github.com/deepmap/oapi-codegen/pkg/gin-middleware" ) -func NewGinPetServer(petStore *api.PetStore, port string) *http.Server { +func NewGinPetServer(petStore *api.PetStore, port int) *http.Server { swagger, err := api.GetSwagger() if err != nil { fmt.Fprintf(os.Stderr, "Error loading swagger spec\n: %s", err) @@ -41,13 +40,13 @@ func NewGinPetServer(petStore *api.PetStore, port string) *http.Server { s := &http.Server{ Handler: r, - Addr: net.JoinHostPort("0.0.0.0", port), + Addr: fmt.Sprintf("0.0.0.0:%d", port), } return s } func main() { - port := flag.String("port", "8080", "Port for test HTTP server") + var port = flag.Int("port", 8080, "Port for test HTTP server") flag.Parse() // Create an instance of our handler which satisfies the generated interface petStore := api.NewPetStore() diff --git a/examples/petstore-expanded/gin/petstore_test.go b/examples/petstore-expanded/gin/petstore_test.go index d967486bb..ccb38de06 100644 --- a/examples/petstore-expanded/gin/petstore_test.go +++ b/examples/petstore-expanded/gin/petstore_test.go @@ -20,7 +20,7 @@ func doGet(t *testing.T, handler http.Handler, url string) *httptest.ResponseRec func TestPetStore(t *testing.T) { var err error store := api.NewPetStore() - ginPetServer := NewGinPetServer(store, "8080") + ginPetServer := NewGinPetServer(store, 8080) r := ginPetServer.Handler t.Run("Add pet", func(t *testing.T) { diff --git a/examples/petstore-expanded/gorilla/api/petstore.gen.go b/examples/petstore-expanded/gorilla/api/petstore.gen.go index 4e7ea9129..dcb8d2c3a 100644 --- a/examples/petstore-expanded/gorilla/api/petstore.gen.go +++ b/examples/petstore-expanded/gorilla/api/petstore.gen.go @@ -83,7 +83,7 @@ type ServerInterfaceWrapper struct { ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) } -type MiddlewareFunc func(http.HandlerFunc) http.HandlerFunc +type MiddlewareFunc func(http.Handler) http.Handler // FindPets operation middleware func (siw *ServerInterfaceWrapper) FindPets(w http.ResponseWriter, r *http.Request) { @@ -110,30 +110,30 @@ func (siw *ServerInterfaceWrapper) FindPets(w http.ResponseWriter, r *http.Reque return } - handler := func(w http.ResponseWriter, r *http.Request) { + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { siw.Handler.FindPets(w, r, params) - } + })) for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { handler = siw.HandlerMiddlewares[i](handler) } - handler(w, r.WithContext(ctx)) + handler.ServeHTTP(w, r.WithContext(ctx)) } // AddPet operation middleware func (siw *ServerInterfaceWrapper) AddPet(w http.ResponseWriter, r *http.Request) { ctx := r.Context() - handler := func(w http.ResponseWriter, r *http.Request) { + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { siw.Handler.AddPet(w, r) - } + })) for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { handler = siw.HandlerMiddlewares[i](handler) } - handler(w, r.WithContext(ctx)) + handler.ServeHTTP(w, r.WithContext(ctx)) } // DeletePet operation middleware @@ -151,15 +151,15 @@ func (siw *ServerInterfaceWrapper) DeletePet(w http.ResponseWriter, r *http.Requ return } - handler := func(w http.ResponseWriter, r *http.Request) { + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { siw.Handler.DeletePet(w, r, id) - } + })) for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { handler = siw.HandlerMiddlewares[i](handler) } - handler(w, r.WithContext(ctx)) + handler.ServeHTTP(w, r.WithContext(ctx)) } // FindPetByID operation middleware @@ -177,15 +177,15 @@ func (siw *ServerInterfaceWrapper) FindPetByID(w http.ResponseWriter, r *http.Re return } - handler := func(w http.ResponseWriter, r *http.Request) { + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { siw.Handler.FindPetByID(w, r, id) - } + })) for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { handler = siw.HandlerMiddlewares[i](handler) } - handler(w, r.WithContext(ctx)) + handler.ServeHTTP(w, r.WithContext(ctx)) } type UnescapedCookieParamError struct { @@ -350,16 +350,16 @@ var swaggerSpec = []string{ 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) + return nil, fmt.Errorf("error base64 decoding spec: %s", err) } zr, err := gzip.NewReader(bytes.NewReader(zipped)) if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) + return nil, fmt.Errorf("error decompressing spec: %s", err) } var buf bytes.Buffer _, err = buf.ReadFrom(zr) if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) + return nil, fmt.Errorf("error decompressing spec: %s", err) } return buf.Bytes(), nil @@ -377,7 +377,7 @@ func decodeSpecCached() func() ([]byte, error) { // 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)) + var res = make(map[string]func() ([]byte, error)) if len(pathToFile) > 0 { res[pathToFile] = rawSpec } @@ -391,12 +391,12 @@ func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { // 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("") + var resolvePath = PathToRawSpec("") loader := openapi3.NewLoader() loader.IsExternalRefsAllowed = true loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() + var pathToFile = url.String() pathToFile = path.Clean(pathToFile) getSpec, ok := resolvePath[pathToFile] if !ok { diff --git a/examples/petstore-expanded/gorilla/api/petstore.go b/examples/petstore-expanded/gorilla/api/petstore.go index ea5b9aa8d..838c96116 100644 --- a/examples/petstore-expanded/gorilla/api/petstore.go +++ b/examples/petstore-expanded/gorilla/api/petstore.go @@ -26,7 +26,7 @@ func NewPetStore() *PetStore { } } -// sendPetStoreError wraps sending of an error in the Error format, and +// This function wraps sending of an error in the Error format, and // handling the failure to marshal that. func sendPetStoreError(w http.ResponseWriter, code int, message string) { petErr := Error{ @@ -89,7 +89,7 @@ func (p *PetStore) AddPet(w http.ResponseWriter, r *http.Request) { pet.Name = newPet.Name pet.Tag = newPet.Tag pet.Id = p.NextId - p.NextId++ + p.NextId = p.NextId + 1 // Insert into map p.Pets[pet.Id] = pet diff --git a/examples/petstore-expanded/gorilla/petstore.go b/examples/petstore-expanded/gorilla/petstore.go index 5f402e030..dfd01180a 100644 --- a/examples/petstore-expanded/gorilla/petstore.go +++ b/examples/petstore-expanded/gorilla/petstore.go @@ -8,7 +8,6 @@ import ( "flag" "fmt" "log" - "net" "net/http" "os" @@ -18,7 +17,7 @@ import ( ) func main() { - port := flag.String("port", "8080", "Port for test HTTP server") + var port = flag.Int("port", 8080, "Port for test HTTP server") flag.Parse() swagger, err := api.GetSwagger() @@ -46,7 +45,7 @@ func main() { s := &http.Server{ Handler: r, - Addr: net.JoinHostPort("0.0.0.0", *port), + Addr: fmt.Sprintf("0.0.0.0:%d", *port), } // And we serve HTTP until the world ends. diff --git a/examples/petstore-expanded/petstore-client.gen.go b/examples/petstore-expanded/petstore-client.gen.go index 299a58726..766135e38 100644 --- a/examples/petstore-expanded/petstore-client.gen.go +++ b/examples/petstore-expanded/petstore-client.gen.go @@ -134,7 +134,7 @@ type ClientInterface interface { // FindPets request FindPets(ctx context.Context, params *FindPetsParams, reqEditors ...RequestEditorFn) (*http.Response, error) - // AddPetWithBody request with any body + // AddPet request with any body AddPetWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) AddPet(ctx context.Context, body AddPetJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) @@ -422,18 +422,18 @@ func WithBaseURL(baseURL string) ClientOption { // ClientWithResponsesInterface is the interface specification for the client with responses above. type ClientWithResponsesInterface interface { - // FindPetsWithResponse request + // FindPets request FindPetsWithResponse(ctx context.Context, params *FindPetsParams, reqEditors ...RequestEditorFn) (*FindPetsResponse, error) - // AddPetWithBodyWithResponse request with any body + // AddPet request with any body AddPetWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*AddPetResponse, error) AddPetWithResponse(ctx context.Context, body AddPetJSONRequestBody, reqEditors ...RequestEditorFn) (*AddPetResponse, error) - // DeletePetWithResponse request + // DeletePet request DeletePetWithResponse(ctx context.Context, id int64, reqEditors ...RequestEditorFn) (*DeletePetResponse, error) - // FindPetByIDWithResponse request + // FindPetByID request FindPetByIDWithResponse(ctx context.Context, id int64, reqEditors ...RequestEditorFn) (*FindPetByIDResponse, error) } diff --git a/examples/petstore-expanded/strict/api/petstore-server.gen.go b/examples/petstore-expanded/strict/api/petstore-server.gen.go index 3f3e849e0..3008bd89d 100644 --- a/examples/petstore-expanded/strict/api/petstore-server.gen.go +++ b/examples/petstore-expanded/strict/api/petstore-server.gen.go @@ -36,34 +36,6 @@ type ServerInterface interface { FindPetByID(w http.ResponseWriter, r *http.Request, id int64) } -// Unimplemented server implementation that returns http.StatusNotImplemented for each endpoint. - -type Unimplemented struct{} - -// Returns all pets -// (GET /pets) -func (_ Unimplemented) FindPets(w http.ResponseWriter, r *http.Request, params FindPetsParams) { - w.WriteHeader(http.StatusNotImplemented) -} - -// Creates a new pet -// (POST /pets) -func (_ Unimplemented) AddPet(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusNotImplemented) -} - -// Deletes a pet by ID -// (DELETE /pets/{id}) -func (_ Unimplemented) DeletePet(w http.ResponseWriter, r *http.Request, id int64) { - w.WriteHeader(http.StatusNotImplemented) -} - -// Returns a pet by ID -// (GET /pets/{id}) -func (_ Unimplemented) FindPetByID(w http.ResponseWriter, r *http.Request, id int64) { - w.WriteHeader(http.StatusNotImplemented) -} - // ServerInterfaceWrapper converts contexts to parameters. type ServerInterfaceWrapper struct { Handler ServerInterface @@ -98,9 +70,9 @@ func (siw *ServerInterfaceWrapper) FindPets(w http.ResponseWriter, r *http.Reque return } - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var handler http.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { siw.Handler.FindPets(w, r, params) - })) + }) for _, middleware := range siw.HandlerMiddlewares { handler = middleware(handler) @@ -113,9 +85,9 @@ func (siw *ServerInterfaceWrapper) FindPets(w http.ResponseWriter, r *http.Reque func (siw *ServerInterfaceWrapper) AddPet(w http.ResponseWriter, r *http.Request) { ctx := r.Context() - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var handler http.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { siw.Handler.AddPet(w, r) - })) + }) for _, middleware := range siw.HandlerMiddlewares { handler = middleware(handler) @@ -139,9 +111,9 @@ func (siw *ServerInterfaceWrapper) DeletePet(w http.ResponseWriter, r *http.Requ return } - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var handler http.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { siw.Handler.DeletePet(w, r, id) - })) + }) for _, middleware := range siw.HandlerMiddlewares { handler = middleware(handler) @@ -165,9 +137,9 @@ func (siw *ServerInterfaceWrapper) FindPetByID(w http.ResponseWriter, r *http.Re return } - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var handler http.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { siw.Handler.FindPetByID(w, r, id) - })) + }) for _, middleware := range siw.HandlerMiddlewares { handler = middleware(handler) @@ -612,16 +584,16 @@ var swaggerSpec = []string{ 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) + return nil, fmt.Errorf("error base64 decoding spec: %s", err) } zr, err := gzip.NewReader(bytes.NewReader(zipped)) if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) + return nil, fmt.Errorf("error decompressing spec: %s", err) } var buf bytes.Buffer _, err = buf.ReadFrom(zr) if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) + return nil, fmt.Errorf("error decompressing spec: %s", err) } return buf.Bytes(), nil @@ -639,7 +611,7 @@ func decodeSpecCached() func() ([]byte, error) { // 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)) + var res = make(map[string]func() ([]byte, error)) if len(pathToFile) > 0 { res[pathToFile] = rawSpec } @@ -653,12 +625,12 @@ func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { // 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("") + var resolvePath = PathToRawSpec("") loader := openapi3.NewLoader() loader.IsExternalRefsAllowed = true loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() + var pathToFile = url.String() pathToFile = path.Clean(pathToFile) getSpec, ok := resolvePath[pathToFile] if !ok { diff --git a/examples/petstore-expanded/strict/api/petstore.go b/examples/petstore-expanded/strict/api/petstore.go index 29b7bd291..dc2c3016f 100644 --- a/examples/petstore-expanded/strict/api/petstore.go +++ b/examples/petstore-expanded/strict/api/petstore.go @@ -70,7 +70,7 @@ func (p *PetStore) AddPet(ctx context.Context, request AddPetRequestObject) (Add pet.Name = request.Body.Name pet.Tag = request.Body.Tag pet.Id = p.NextId - p.NextId++ + p.NextId = p.NextId + 1 // Insert into map p.Pets[pet.Id] = pet diff --git a/examples/petstore-expanded/strict/petstore.go b/examples/petstore-expanded/strict/petstore.go index ef0776bcd..c34860034 100644 --- a/examples/petstore-expanded/strict/petstore.go +++ b/examples/petstore-expanded/strict/petstore.go @@ -8,7 +8,6 @@ import ( "flag" "fmt" "log" - "net" "net/http" "os" @@ -18,7 +17,7 @@ import ( ) func main() { - port := flag.String("port", "8080", "Port for test HTTP server") + var port = flag.Int("port", 8080, "Port for test HTTP server") flag.Parse() swagger, err := api.GetSwagger() @@ -48,7 +47,7 @@ func main() { s := &http.Server{ Handler: r, - Addr: net.JoinHostPort("0.0.0.0", *port), + Addr: fmt.Sprintf("0.0.0.0:%d", *port), } // And we serve HTTP until the world ends. diff --git a/go.mod b/go.mod index 008d41fbd..f003ee7d8 100644 --- a/go.mod +++ b/go.mod @@ -2,78 +2,80 @@ module github.com/deepmap/oapi-codegen require ( github.com/apapsch/go-jsonmerge/v2 v2.0.0 - github.com/getkin/kin-openapi v0.118.0 + github.com/getkin/kin-openapi v0.117.0 github.com/gin-gonic/gin v1.9.1 - github.com/go-chi/chi/v5 v5.0.10 - github.com/gofiber/fiber/v2 v2.48.0 + github.com/go-chi/chi/v5 v5.0.8 + github.com/gofiber/fiber/v2 v2.46.0 github.com/golangci/lint-1 v0.0.0-20181222135242-d2cdd8c08219 github.com/google/uuid v1.3.0 github.com/gorilla/mux v1.8.0 - github.com/labstack/echo/v4 v4.11.1 - github.com/lestrrat-go/jwx v1.2.26 - github.com/matryer/moq v0.3.2 + github.com/labstack/echo/v4 v4.10.2 + github.com/lestrrat-go/jwx v1.2.25 + github.com/matryer/moq v0.3.1 github.com/stretchr/testify v1.8.4 - golang.org/x/text v0.12.0 - golang.org/x/tools v0.11.1 + golang.org/x/text v0.9.0 + golang.org/x/tools v0.9.3 gopkg.in/yaml.v2 v2.4.0 ) require ( github.com/andybalholm/brotli v1.0.5 // indirect - github.com/bytedance/sonic v1.10.0-rc3 // indirect - github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d // indirect - github.com/chenzhuoyu/iasm v0.9.0 // indirect + github.com/bytedance/sonic v1.9.1 // indirect + github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect github.com/davecgh/go-spew v1.1.1 // indirect - github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0 // indirect + github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1 // indirect github.com/gabriel-vasile/mimetype v1.4.2 // indirect github.com/gin-contrib/sse v0.1.0 // indirect - github.com/go-openapi/jsonpointer v0.20.0 // indirect - github.com/go-openapi/swag v0.22.4 // indirect + github.com/go-openapi/jsonpointer v0.19.5 // indirect + github.com/go-openapi/swag v0.21.1 // 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.14.1 // indirect + github.com/go-playground/validator/v10 v10.14.0 // indirect github.com/goccy/go-json v0.10.2 // indirect github.com/golang-jwt/jwt v3.2.2+incompatible // indirect - github.com/invopop/yaml v0.2.0 // indirect + github.com/invopop/yaml v0.1.0 // indirect github.com/josharian/intern v1.0.0 // indirect github.com/json-iterator/go v1.1.12 // indirect - github.com/klauspost/compress v1.16.7 // indirect - github.com/klauspost/cpuid/v2 v2.2.5 // indirect + github.com/klauspost/compress v1.16.3 // indirect + github.com/klauspost/cpuid/v2 v2.2.4 // indirect github.com/labstack/gommon v0.4.0 // indirect github.com/leodido/go-urn v1.2.4 // indirect github.com/lestrrat-go/backoff/v2 v2.0.8 // indirect - github.com/lestrrat-go/blackmagic v1.0.1 // indirect + github.com/lestrrat-go/blackmagic v1.0.0 // indirect github.com/lestrrat-go/httpcc v1.0.1 // indirect - github.com/lestrrat-go/iter v1.0.2 // indirect - github.com/lestrrat-go/option v1.0.1 // indirect + github.com/lestrrat-go/iter v1.0.1 // indirect + github.com/lestrrat-go/option v1.0.0 // indirect github.com/mailru/easyjson v0.7.7 // indirect github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-isatty v0.0.19 // indirect - github.com/mattn/go-runewidth v0.0.15 // indirect + github.com/mattn/go-runewidth v0.0.14 // 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/pelletier/go-toml/v2 v2.0.9 // indirect - github.com/perimeterx/marshmallow v1.1.5 // indirect + github.com/pelletier/go-toml/v2 v2.0.8 // indirect + github.com/perimeterx/marshmallow v1.1.4 // indirect + github.com/philhofer/fwd v1.1.2 // indirect github.com/pkg/errors v0.9.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect - github.com/rivo/uniseg v0.4.4 // indirect - github.com/rogpeppe/go-internal v1.11.0 // indirect + github.com/rivo/uniseg v0.2.0 // indirect + github.com/savsgio/dictpool v0.0.0-20221023140959-7bf2e61cea94 // indirect + github.com/savsgio/gotils v0.0.0-20230208104028-c358bd845dee // indirect github.com/stretchr/objx v0.5.0 // indirect + github.com/tinylib/msgp v1.1.8 // indirect github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/ugorji/go/codec v1.2.11 // indirect github.com/valyala/bytebufferpool v1.0.0 // indirect - github.com/valyala/fasthttp v1.48.0 // indirect + github.com/valyala/fasthttp v1.47.0 // indirect github.com/valyala/fasttemplate v1.2.2 // indirect github.com/valyala/tcplisten v1.0.0 // indirect - golang.org/x/arch v0.4.0 // indirect - golang.org/x/crypto v0.11.0 // indirect - golang.org/x/mod v0.12.0 // indirect - golang.org/x/net v0.12.0 // indirect - golang.org/x/sys v0.10.0 // indirect + golang.org/x/arch v0.3.0 // indirect + golang.org/x/crypto v0.9.0 // indirect + golang.org/x/mod v0.10.0 // indirect + golang.org/x/net v0.10.0 // indirect + golang.org/x/sys v0.8.0 // indirect golang.org/x/time v0.3.0 // indirect golang.org/x/xerrors v0.0.0-20220411194840-2f41105eb62f // indirect - google.golang.org/protobuf v1.31.0 // indirect + google.golang.org/protobuf v1.30.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/go.sum b/go.sum index 1c420c683..da0b9ce8d 100644 --- a/go.sum +++ b/go.sum @@ -5,50 +5,48 @@ github.com/apapsch/go-jsonmerge/v2 v2.0.0 h1:axGnT1gRIfimI7gJifB699GoE/oq+F2MU7D 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/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM= -github.com/bytedance/sonic v1.10.0-rc/go.mod h1:ElCzW+ufi8qKqNW0FY314xriJhyJhuoJ3gFZdAHF7NM= -github.com/bytedance/sonic v1.10.0-rc3 h1:uNSnscRapXTwUgTyOF0GVljYD08p9X/Lbr9MweSV3V0= -github.com/bytedance/sonic v1.10.0-rc3/go.mod h1:iZcSUejdk5aukTND/Eu/ivjQuEL0Cu9/rf50Hi0u/g4= +github.com/bytedance/sonic v1.9.1 h1:6iJ6NqdoxCDr6mbY8h18oSO+cShGSMRGCEo7F2h0x8s= +github.com/bytedance/sonic v1.9.1/go.mod h1:i736AoUSYt75HyZLoJW9ERYxcy6eaN6h4BZXU064P/U= github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY= +github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 h1:qSGYFH7+jGhDF8vLC+iwCD4WpbV1EBDSzWkJODFLams= github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk= -github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d h1:77cEq6EriyTZ0g/qfRdp61a3Uu/AWrgIq2s0ClJV1g0= -github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d/go.mod h1:8EPpVsBuRksnlj1mLy4AWzRNQYxauNi62uWcE3to6eA= -github.com/chenzhuoyu/iasm v0.9.0 h1:9fhXjVzq5hUy2gkhhgHl95zG2cEAhw9OSGs8toWWAwo= -github.com/chenzhuoyu/iasm v0.9.0/go.mod h1:Xjy2NpN3h7aUqeqM+woSuuvxmIe6+DDsiNLIrkAmYog= +github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/decred/dcrd/crypto/blake256 v1.0.1/go.mod h1:2OfgNZ5wDpcsFmHmCK5gZTPcCXqlm2ArzUIkw9czNJo= -github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0 h1:8UrgZ3GkP4i/CLijOJx79Yu+etlyjdBU4sfcs2WYQMs= -github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0/go.mod h1:v57UDF4pDQJcEfFUCRop3lJL149eHGSe9Jvczhzjo/0= +github.com/decred/dcrd/crypto/blake256 v1.0.0/go.mod h1:sQl2p6Y26YV+ZOcSTP6thNdn47hh8kt6rqSlvmrXFAc= +github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.0-20210816181553-5444fa50b93d/go.mod h1:tmAIfUFEirG/Y8jhZ9M+h36obRZAk/1fcSpXwAVlfqE= +github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1 h1:YLtO71vCjJRCBcrPMtQ9nqBsqpA1m5sE92cU+pd5Mcc= +github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1/go.mod h1:hyedUtir6IdtD/7lIxGeCxkaw7y45JueMRL4DIyJDKs= github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU= github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA= -github.com/getkin/kin-openapi v0.118.0 h1:z43njxPmJ7TaPpMSCQb7PN0dEYno4tyBPQcrFdHoLuM= -github.com/getkin/kin-openapi v0.118.0/go.mod h1:l5e9PaFUo9fyLJCPGQeXI2ML8c3P8BHOEV2VaAVf/pc= +github.com/getkin/kin-openapi v0.117.0 h1:QT2DyGujAL09F4NrKDHJGsUoIprlIcFVHWDVDcUFE8A= +github.com/getkin/kin-openapi v0.117.0/go.mod h1:l5e9PaFUo9fyLJCPGQeXI2ML8c3P8BHOEV2VaAVf/pc= github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= github.com/gin-gonic/gin v1.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg= github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SUcPTeU= -github.com/go-chi/chi/v5 v5.0.10 h1:rLz5avzKpjqxrYwXNfmjkrYYXOyLJd37pz53UFHC6vk= -github.com/go-chi/chi/v5 v5.0.10/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8= +github.com/go-chi/chi/v5 v5.0.8 h1:lD+NLqFcAi1ovnVZpsnObHGW4xb4J8lNmoYVfECH1Y0= +github.com/go-chi/chi/v5 v5.0.8/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8= +github.com/go-openapi/jsonpointer v0.19.5 h1:gZr+CIYByUqjcgeLXnQu2gHYQC9o73G2XUeOFYEICuY= github.com/go-openapi/jsonpointer v0.19.5/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= -github.com/go-openapi/jsonpointer v0.20.0 h1:ESKJdU9ASRfaPNOPRx12IUyA1vn3R9GiE3KYD14BXdQ= -github.com/go-openapi/jsonpointer v0.20.0/go.mod h1:6PGzBjjIIumbLYysB73Klnms1mwnU4G3YHOECG3CedA= github.com/go-openapi/swag v0.19.5/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk= -github.com/go-openapi/swag v0.22.4 h1:QLMzNJnMGPRNDCbySlcj1x01tzU8/9LTTL9hZZZogBU= -github.com/go-openapi/swag v0.22.4/go.mod h1:UzaqsxGiab7freDnrUUra0MwWfN/q7tE4j+VcZ0yl14= +github.com/go-openapi/swag v0.21.1 h1:wm0rhTb5z7qpJRHBdPOMuY4QjVUMbF6/kwoYeRAOrKU= +github.com/go-openapi/swag v0.21.1/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/eQntq43wQ= github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= 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.14.1 h1:9c50NUPC30zyuKprjL3vNZ0m5oG+jU0zvx4AqHGnv4k= -github.com/go-playground/validator/v10 v10.14.1/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU= +github.com/go-playground/validator/v10 v10.14.0 h1:vgvQWe3XCz3gIeFDm/HnTIbj6UGmg/+t63MyGU2n5js= +github.com/go-playground/validator/v10 v10.14.0/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU= 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/goccy/go-json v0.9.7/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= 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/gofiber/fiber/v2 v2.48.0 h1:cRVMCb9aUJDsyHxGFLwz/sGzDggdailZZyptU9F9cU0= -github.com/gofiber/fiber/v2 v2.48.0/go.mod h1:xqJgfqrc23FJuqGOW6DVgi3HyZEm2Mn9pRqUb2kHSX8= +github.com/gofiber/fiber/v2 v2.46.0 h1:wkkWotblsGVlLjXj2dpgKQAYHtXumsK/HyFugQM68Ns= +github.com/gofiber/fiber/v2 v2.46.0/go.mod h1:DNl0/c37WLe0g92U6lx1VMQuxGUQY5V7EIaVoEsUffc= github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY= github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I= github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= @@ -61,50 +59,48 @@ github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI= github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So= +github.com/invopop/yaml v0.1.0 h1:YW3WGUoJEXYfzWBjn00zIlrw7brGVD0fUKRYDPAPhrc= github.com/invopop/yaml v0.1.0/go.mod h1:2XuRLgs/ouIrW3XNzuNj7J3Nvu/Dig5MXvbCEdiBN3Q= -github.com/invopop/yaml v0.2.0 h1:7zky/qH+O0DwAyoobXUqvVBwgBFRxKoQ/3FjcVpjTMY= -github.com/invopop/yaml v0.2.0/go.mod h1:2XuRLgs/ouIrW3XNzuNj7J3Nvu/Dig5MXvbCEdiBN3Q= 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/klauspost/compress v1.16.7 h1:2mk3MPGNzKyxErAw8YaohYh69+pa4sIQSC0fPGCFR9I= -github.com/klauspost/compress v1.16.7/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= +github.com/klauspost/compress v1.16.3 h1:XuJt9zzcnaz6a16/OU53ZjWp/v7/42WcR5t2a0PcNQY= +github.com/klauspost/compress v1.16.3/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= -github.com/klauspost/cpuid/v2 v2.2.5 h1:0E5MSMDEoAulmXNFquVs//DdoomxaoTY1kUhbc/qbZg= -github.com/klauspost/cpuid/v2 v2.2.5/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws= -github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M= +github.com/klauspost/cpuid/v2 v2.2.4 h1:acbojRNwl3o09bUq+yDCtZFc1aiwaAAxtcn8YkZXnvk= +github.com/klauspost/cpuid/v2 v2.2.4/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= -github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= -github.com/labstack/echo/v4 v4.11.1 h1:dEpLU2FLg4UVmvCGPuk/APjlH6GDpbEPti61srUUUs4= -github.com/labstack/echo/v4 v4.11.1/go.mod h1:YuYRTSM3CHs2ybfrL8Px48bO6BAnYIN4l8wSTMP6BDQ= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/labstack/echo/v4 v4.10.2 h1:n1jAhnq/elIFTHr1EYpiYtyKgx4RW9ccVgkqByZaN2M= +github.com/labstack/echo/v4 v4.10.2/go.mod h1:OEyqf2//K1DFdE57vw2DRgWY0M7s65IVQO2FzvI4J5k= github.com/labstack/gommon v0.4.0 h1:y7cvthEAEbU0yHOf4axH8ZG2NH8knB9iNSoTO8dyIk8= github.com/labstack/gommon v0.4.0/go.mod h1:uW6kP17uPlLJsD3ijUYn3/M5bAxtlZhMI6m3MFxTMTM= github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q= github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4= github.com/lestrrat-go/backoff/v2 v2.0.8 h1:oNb5E5isby2kiro9AgdHLv5N5tint1AnDVVf2E2un5A= github.com/lestrrat-go/backoff/v2 v2.0.8/go.mod h1:rHP/q/r9aT27n24JQLa7JhSQZCKBBOiM/uP402WwN8Y= -github.com/lestrrat-go/blackmagic v1.0.1 h1:lS5Zts+5HIC/8og6cGHb0uCcNCa3OUt1ygh3Qz2Fe80= -github.com/lestrrat-go/blackmagic v1.0.1/go.mod h1:UrEqBzIR2U6CnzVyUtfM6oZNMt/7O7Vohk2J0OGSAtU= +github.com/lestrrat-go/blackmagic v1.0.0 h1:XzdxDbuQTz0RZZEmdU7cnQxUtFUzgCSPq8RCz4BxIi4= +github.com/lestrrat-go/blackmagic v1.0.0/go.mod h1:TNgH//0vYSs8VXDCfkZLgIrVTTXQELZffUV0tz3MtdQ= github.com/lestrrat-go/httpcc v1.0.1 h1:ydWCStUeJLkpYyjLDHihupbn2tYmZ7m22BGkcvZZrIE= github.com/lestrrat-go/httpcc v1.0.1/go.mod h1:qiltp3Mt56+55GPVCbTdM9MlqhvzyuL6W/NMDA8vA5E= -github.com/lestrrat-go/iter v1.0.2 h1:gMXo1q4c2pHmC3dn8LzRhJfP1ceCbgSiT9lUydIzltI= -github.com/lestrrat-go/iter v1.0.2/go.mod h1:Momfcq3AnRlRjI5b5O8/G5/BvpzrhoFTZcn06fEOPt4= -github.com/lestrrat-go/jwx v1.2.26 h1:4iFo8FPRZGDYe1t19mQP0zTRqA7n8HnJ5lkIiDvJcB0= -github.com/lestrrat-go/jwx v1.2.26/go.mod h1:MaiCdGbn3/cckbOFSCluJlJMmp9dmZm5hDuIkx8ftpQ= +github.com/lestrrat-go/iter v1.0.1 h1:q8faalr2dY6o8bV45uwrxq12bRa1ezKrB6oM9FUgN4A= +github.com/lestrrat-go/iter v1.0.1/go.mod h1:zIdgO1mRKhn8l9vrZJZz9TUMMFbQbLeTsbqPDrJ/OJc= +github.com/lestrrat-go/jwx v1.2.25 h1:tAx93jN2SdPvFn08fHNAhqFJazn5mBBOB8Zli0g0otA= +github.com/lestrrat-go/jwx v1.2.25/go.mod h1:zoNuZymNl5lgdcu6P7K6ie2QRll5HVfF4xwxBBK1NxY= +github.com/lestrrat-go/option v1.0.0 h1:WqAWL8kh8VcSoD6xjSH34/1m8yxluXQbDeKNfvFeEO4= github.com/lestrrat-go/option v1.0.0/go.mod h1:5ZHFbivi4xwXxhxY9XHDe2FHo6/Z7WWmtT7T5nBBp3I= -github.com/lestrrat-go/option v1.0.1 h1:oAzP2fvZGQKWkvHa1/SAcFolBEca1oN+mQ7eooNBEYU= -github.com/lestrrat-go/option v1.0.1/go.mod h1:5ZHFbivi4xwXxhxY9XHDe2FHo6/Z7WWmtT7T5nBBp3I= github.com/mailru/easyjson v0.0.0-20190614124828-94de47d64c63/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= +github.com/mailru/easyjson v0.7.6/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0= github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= -github.com/matryer/moq v0.3.2 h1:z7oltmpTxiQ9nKNg0Jc7z45TM+eO7OhCVohxRxwaudM= -github.com/matryer/moq v0.3.2/go.mod h1:RJ75ZZZD71hejp39j4crZLsEDszGk6iH4v4YsWFKH4s= +github.com/matryer/moq v0.3.1 h1:kLDiBJoGcusWS2BixGyTkF224aSCD8nLY24tj/NcTCs= +github.com/matryer/moq v0.3.1/go.mod h1:RJ75ZZZD71hejp39j4crZLsEDszGk6iH4v4YsWFKH4s= github.com/mattn/go-colorable v0.1.11/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4= github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= @@ -112,8 +108,8 @@ github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27k github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA= github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= -github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U= -github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= +github.com/mattn/go-runewidth v0.0.14 h1:+xnbZSEeDbOIg5/mE6JF0w6n9duR1l3/WmbinWVwUuU= +github.com/mattn/go-runewidth v0.0.14/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= 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= @@ -121,34 +117,45 @@ github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9G 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/pelletier/go-toml/v2 v2.0.9 h1:uH2qQXheeefCCkuBBSLi7jCiSmj3VRh2+Goq2N7Xxu0= -github.com/pelletier/go-toml/v2 v2.0.9/go.mod h1:tJU2Z3ZkXwnxa4DPO899bsyIoywizdUvyaeZurnPPDc= +github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs= +github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= +github.com/pelletier/go-toml/v2 v2.0.8 h1:0ctb6s9mE31h0/lhu+J6OPmVeDxJn+kYnJc2jZR9tGQ= +github.com/pelletier/go-toml/v2 v2.0.8/go.mod h1:vuYfssBdrU2XDZ9bYydBu6t+6a6PYNcZljzZR9VXg+4= +github.com/perimeterx/marshmallow v1.1.4 h1:pZLDH9RjlLGGorbXhcaQLhfuV0pFMNfPO55FuFkxqLw= github.com/perimeterx/marshmallow v1.1.4/go.mod h1:dsXbUu8CRzfYP5a87xpp0xq9S3u0Vchtcl8we9tYaXw= -github.com/perimeterx/marshmallow v1.1.5 h1:a2LALqQ1BlHM8PZblsDdidgv1mWi1DgC2UmX50IvK2s= -github.com/perimeterx/marshmallow v1.1.5/go.mod h1:dsXbUu8CRzfYP5a87xpp0xq9S3u0Vchtcl8we9tYaXw= +github.com/philhofer/fwd v1.1.1/go.mod h1:gk3iGcWd9+svBvR0sR+KPcfE+RNWozjowpeBVG3ZVNU= +github.com/philhofer/fwd v1.1.2 h1:bnDivRJ1EWPjUIRXV5KfORO897HTbpFAQddBdE8t7Gw= +github.com/philhofer/fwd v1.1.2/go.mod h1:qkPdfjR2SIEbspLqpe1tO4n5yICnr2DY7mqEx2tUTP0= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY= github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= -github.com/rivo/uniseg v0.4.4 h1:8TfxU8dW6PdqD27gjM8MVNuicgxIjxpm4K7x4jp8sis= -github.com/rivo/uniseg v0.4.4/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= -github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M= -github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA= +github.com/savsgio/dictpool v0.0.0-20221023140959-7bf2e61cea94 h1:rmMl4fXJhKMNWl+K+r/fq4FbbKI+Ia2m9hYBLm2h4G4= +github.com/savsgio/dictpool v0.0.0-20221023140959-7bf2e61cea94/go.mod h1:90zrgN3D/WJsDd1iXHT96alCoN2KJo6/4x1DZC3wZs8= +github.com/savsgio/gotils v0.0.0-20220530130905-52f3993e8d6d/go.mod h1:Gy+0tqhJvgGlqnTF8CVGP0AaGRjwBtXs/a5PA0Y3+A4= +github.com/savsgio/gotils v0.0.0-20230208104028-c358bd845dee h1:8Iv5m6xEo1NR1AvpV+7XmhI4r39LGNzwUL4YpMuL5vk= +github.com/savsgio/gotils v0.0.0-20230208104028-c358bd845dee/go.mod h1:qwtSXrKuJh/zsFQ12yEE89xfCrGKK63Rr7ctU/uCo4g= 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 h1:1zr/of2m5FGMsad5YfcqgdqdWrIhu+EBEJRhR1U7z/c= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 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.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.8.3/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/tinylib/msgp v1.1.6/go.mod h1:75BAfg2hauQhs3qedfdDZmWAPcFMAvJE5b9rGOMufyw= +github.com/tinylib/msgp v1.1.8 h1:FCXC1xanKO4I8plpHGH2P7koL/RzZs12l/+r7vakfm0= +github.com/tinylib/msgp v1.1.8/go.mod h1:qkpG+2ldGg4xRFmx+jfTvZPxfGFhi64BcnL9vkCm/Tw= 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 v1.2.7/go.mod h1:nF9osbDWLy6bDVv/Rtoh6QgnvNDpmCalQV5urGCCS6M= @@ -157,87 +164,100 @@ github.com/ugorji/go/codec v1.2.11 h1:BMaWp1Bb6fHwEtbplGBGJ498wD+LKlNSl25MjdZY4d github.com/ugorji/go/codec v1.2.11/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg= 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.48.0 h1:oJWvHb9BIZToTQS3MuQ2R3bJZiNSa2KiNdeI8A+79Tc= -github.com/valyala/fasthttp v1.48.0/go.mod h1:k2zXd82h/7UZc3VOdJ2WaUqt1uZ/XpXAfE9i+HBC3lA= +github.com/valyala/fasthttp v1.47.0 h1:y7moDoxYzMooFpT5aHgNgVOQDrS3qlkfiP9mDtGGK9c= +github.com/valyala/fasthttp v1.47.0/go.mod h1:k2zXd82h/7UZc3VOdJ2WaUqt1uZ/XpXAfE9i+HBC3lA= github.com/valyala/fasttemplate v1.2.1/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ= 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/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= -golang.org/x/arch v0.4.0 h1:A8WCeEWhLwPBKNbFi5Wv5UTCBx5zzubnXDlMOFAzFMc= -golang.org/x/arch v0.4.0/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= +golang.org/x/arch v0.3.0 h1:02VY4/ZcO/gBOH6PUaoiptASxtXU10jazRCP865E97k= +golang.org/x/arch v0.3.0/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= 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.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.0.0-20220427172511-eb4f295cb31f/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= +golang.org/x/crypto v0.9.0 h1:LF6fAI+IutBocDJ2OT0Q1g8plpYljMZ4+lty+dsqw3g= golang.org/x/crypto v0.9.0/go.mod h1:yrmDGqONDYtNj3tH8X9dzUun2m2lzPa9ngI6/RUPGR0= -golang.org/x/crypto v0.11.0 h1:6Ewdq3tDic1mg5xRO4milcWCfMVQhI4NkqWWvqejpuA= -golang.org/x/crypto v0.11.0/go.mod h1:xgJhtzW8F9jGdVFWZESrid1U1bjeNy4zgy5cRr/CIio= +golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= -golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= -golang.org/x/mod v0.12.0 h1:rmsUpXtvNzj340zd98LZ4KntptpfRHwpFOHG188oHXc= -golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/mod v0.7.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/mod v0.10.0 h1:lFO9qtOdlre5W1jxS3r/4szv2/6iXxScdzjoBMXNhYk= +golang.org/x/mod v0.10.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +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-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= -golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= +golang.org/x/net v0.3.0/go.mod h1:MBQ8lrhLObU/6UmLb4fmbmk5OcyYmqtbGd/9yIeKjEE= +golang.org/x/net v0.10.0 h1:X2//UzNDwYmtCLn7To6G58Wr6f5ahEAQgKNzv9Y951M= golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= -golang.org/x/net v0.12.0 h1:cfawfvKITfUsFCeJIHJrbSxpeu/E81khclypR0GVT50= -golang.org/x/net v0.12.0/go.mod h1:zEVYFnQC7m/vmpQFELhcD1EWkZlX69l4oqgmer6hfKA= 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-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.3.0 h1:ftCYgMx6zT/asHUrPw8BLLscYtGznsLAnjq5RH9P66E= +golang.org/x/sync v0.2.0 h1:PUR+T4wwASmuSTYdKjYHI5TD22Wy5ogLU5qZCOLxBrI= 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-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-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-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211103235746-7861aae1554b/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220704084225-05e143d24a9e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.8.0 h1:EBmGv8NaZBZTWvrbjNoL6HVt+IVy3QDQpJs7VRIw3tU= golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.10.0 h1:SqMFp9UcQJZa+pmYuAKjd9xq1f0j5rLcDIk0mj4qAsA= -golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 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/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= -golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= +golang.org/x/term v0.3.0/go.mod h1:q750SLmJuPmVoN1blW3UFBPREJfb1KmY3vwxfr+nFDA= 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.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.5.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.9.0 h1:2sjJmO8cDvYveuX97RDLsxlyUxLl+GHoLxBiRdHllBE= golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= -golang.org/x/text v0.12.0 h1:k+n5B8goJNdU7hSvEtMUz3d1Q6D/XW4COJSJR6fN0mc= -golang.org/x/text v0.12.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= golang.org/x/time v0.3.0 h1:rg5rLMjNzMS1RkNLzCG38eapWhnYLFYXDXj2gOlr8j4= golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= 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-20201022035929-9cf592e881e9/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= -golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= -golang.org/x/tools v0.11.1 h1:ojD5zOW8+7dOGzdnNgersm8aPfcDjhMp12UfG93NIMc= -golang.org/x/tools v0.11.1/go.mod h1:anzJrxPjNtfgiYQYirP2CPGzGLxrH2u2QBhn6Bf3qY8= +golang.org/x/tools v0.4.0/go.mod h1:UE5sM2OK9E/d67R0ANs2xJizIymRP5gJU295PvKXxjQ= +golang.org/x/tools v0.9.3 h1:Gn1I8+64MsuTb/HpH+LmQtNas23LhUVr3rYZ0eKuaMM= +golang.org/x/tools v0.9.3/go.mod h1:owI94Op576fPu3cIGQeHs3joujW/2Oc6MtlxbF5dfNc= 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= golang.org/x/xerrors v0.0.0-20220411194840-2f41105eb62f h1:GGU+dLjvlC3qDwqYgL6UgRmHXhOOgns0bZu2Ty5mm6U= golang.org/x/xerrors v0.0.0-20220411194840-2f41105eb62f/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= -google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8= -google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= +google.golang.org/protobuf v1.30.0 h1:kPPoIgf3TsEvrm0PFe15JQ+570QVxYzEvvHqChK+cng= +google.golang.org/protobuf v1.30.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU= +gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v2 v2.2.2/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-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0/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= -nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50= rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4= diff --git a/internal/test/all_of/v1/openapi.gen.go b/internal/test/all_of/v1/openapi.gen.go index 18841cdae..002326125 100644 --- a/internal/test/all_of/v1/openapi.gen.go +++ b/internal/test/all_of/v1/openapi.gen.go @@ -59,16 +59,16 @@ var swaggerSpec = []string{ 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) + return nil, fmt.Errorf("error base64 decoding spec: %s", err) } zr, err := gzip.NewReader(bytes.NewReader(zipped)) if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) + return nil, fmt.Errorf("error decompressing spec: %s", err) } var buf bytes.Buffer _, err = buf.ReadFrom(zr) if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) + return nil, fmt.Errorf("error decompressing spec: %s", err) } return buf.Bytes(), nil @@ -86,7 +86,7 @@ func decodeSpecCached() func() ([]byte, error) { // 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)) + var res = make(map[string]func() ([]byte, error)) if len(pathToFile) > 0 { res[pathToFile] = rawSpec } @@ -100,12 +100,12 @@ func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { // 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("") + var resolvePath = PathToRawSpec("") loader := openapi3.NewLoader() loader.IsExternalRefsAllowed = true loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() + var pathToFile = url.String() pathToFile = path.Clean(pathToFile) getSpec, ok := resolvePath[pathToFile] if !ok { diff --git a/internal/test/all_of/v2/openapi.gen.go b/internal/test/all_of/v2/openapi.gen.go index 9828f2b75..3222dcf0a 100644 --- a/internal/test/all_of/v2/openapi.gen.go +++ b/internal/test/all_of/v2/openapi.gen.go @@ -59,16 +59,16 @@ var swaggerSpec = []string{ 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) + return nil, fmt.Errorf("error base64 decoding spec: %s", err) } zr, err := gzip.NewReader(bytes.NewReader(zipped)) if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) + return nil, fmt.Errorf("error decompressing spec: %s", err) } var buf bytes.Buffer _, err = buf.ReadFrom(zr) if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) + return nil, fmt.Errorf("error decompressing spec: %s", err) } return buf.Bytes(), nil @@ -86,7 +86,7 @@ func decodeSpecCached() func() ([]byte, error) { // 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)) + var res = make(map[string]func() ([]byte, error)) if len(pathToFile) > 0 { res[pathToFile] = rawSpec } @@ -100,12 +100,12 @@ func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { // 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("") + var resolvePath = PathToRawSpec("") loader := openapi3.NewLoader() loader.IsExternalRefsAllowed = true loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() + var pathToFile = url.String() pathToFile = path.Clean(pathToFile) getSpec, ok := resolvePath[pathToFile] if !ok { diff --git a/internal/test/any_of/param/param.gen.go b/internal/test/any_of/param/param.gen.go index 2fa5d9125..650f1f3cc 100644 --- a/internal/test/any_of/param/param.gen.go +++ b/internal/test/any_of/param/param.gen.go @@ -370,7 +370,7 @@ func WithBaseURL(baseURL string) ClientOption { // ClientWithResponsesInterface is the interface specification for the client with responses above. type ClientWithResponsesInterface interface { - // GetTestWithResponse request + // GetTest request GetTestWithResponse(ctx context.Context, params *GetTestParams, reqEditors ...RequestEditorFn) (*GetTestResponse, error) } diff --git a/internal/test/client/client.gen.go b/internal/test/client/client.gen.go index dc696bf04..865727b6a 100644 --- a/internal/test/client/client.gen.go +++ b/internal/test/client/client.gen.go @@ -24,8 +24,8 @@ type SchemaObject struct { Role string `json:"role"` } -// PostVendorJsonApplicationVndAPIPlusJSONBody defines parameters for PostVendorJson. -type PostVendorJsonApplicationVndAPIPlusJSONBody = map[string]interface{} +// PostVendorJsonJSONBody defines parameters for PostVendorJson. +type PostVendorJsonJSONBody = map[string]interface{} // PostBothJSONRequestBody defines body for PostBoth for application/json ContentType. type PostBothJSONRequestBody = SchemaObject @@ -33,8 +33,8 @@ 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 +// PostVendorJsonJSONRequestBody defines body for PostVendorJson for application/vnd.api+json ContentType. +type PostVendorJsonJSONRequestBody = PostVendorJsonJSONBody // RequestEditorFn is the function signature for the RequestEditor callback function type RequestEditorFn func(ctx context.Context, req *http.Request) error @@ -109,7 +109,7 @@ func WithRequestEditorFn(fn RequestEditorFn) ClientOption { // The interface specification for the client above. type ClientInterface interface { - // PostBothWithBody request with any body + // PostBoth 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) @@ -117,7 +117,7 @@ type ClientInterface interface { // GetBoth request GetBoth(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) - // PostJsonWithBody request with any body + // PostJson 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) @@ -125,7 +125,7 @@ type ClientInterface interface { // GetJson request GetJson(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) - // PostOtherWithBody request with any body + // PostOther request with any body PostOtherWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) // GetOther request @@ -134,10 +134,10 @@ type ClientInterface interface { // GetJsonWithTrailingSlash request GetJsonWithTrailingSlash(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) - // PostVendorJsonWithBody request with any body + // PostVendorJson 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) + PostVendorJson(ctx context.Context, body PostVendorJsonJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) } func (c *Client) PostBothWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { @@ -260,8 +260,8 @@ func (c *Client) PostVendorJsonWithBody(ctx context.Context, contentType string, 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) +func (c *Client) PostVendorJson(ctx context.Context, body PostVendorJsonJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewPostVendorJsonRequest(c.Server, body) if err != nil { return nil, err } @@ -489,8 +489,8 @@ func NewGetJsonWithTrailingSlashRequest(server string) (*http.Request, error) { return req, nil } -// NewPostVendorJsonRequestWithApplicationVndAPIPlusJSONBody calls the generic PostVendorJson builder with application/vnd.api+json body -func NewPostVendorJsonRequestWithApplicationVndAPIPlusJSONBody(server string, body PostVendorJsonApplicationVndAPIPlusJSONRequestBody) (*http.Request, error) { +// NewPostVendorJsonRequest calls the generic PostVendorJson builder with application/vnd.api+json body +func NewPostVendorJsonRequest(server string, body PostVendorJsonJSONRequestBody) (*http.Request, error) { var bodyReader io.Reader buf, err := json.Marshal(body) if err != nil { @@ -572,35 +572,35 @@ func WithBaseURL(baseURL string) ClientOption { // ClientWithResponsesInterface is the interface specification for the client with responses above. type ClientWithResponsesInterface interface { - // PostBothWithBodyWithResponse request with any body + // PostBoth 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 + // GetBoth request GetBothWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*GetBothResponse, error) - // PostJsonWithBodyWithResponse request with any body + // PostJson 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 + // GetJson request GetJsonWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*GetJsonResponse, error) - // PostOtherWithBodyWithResponse request with any body + // PostOther request with any body PostOtherWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*PostOtherResponse, error) - // GetOtherWithResponse request + // GetOther request GetOtherWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*GetOtherResponse, error) - // GetJsonWithTrailingSlashWithResponse request + // GetJsonWithTrailingSlash request GetJsonWithTrailingSlashWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*GetJsonWithTrailingSlashResponse, error) - // PostVendorJsonWithBodyWithResponse request with any body + // PostVendorJson 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) + PostVendorJsonWithResponse(ctx context.Context, body PostVendorJsonJSONRequestBody, reqEditors ...RequestEditorFn) (*PostVendorJsonResponse, error) } type PostBothResponse struct { @@ -859,8 +859,8 @@ func (c *ClientWithResponses) PostVendorJsonWithBodyWithResponse(ctx context.Con return ParsePostVendorJsonResponse(rsp) } -func (c *ClientWithResponses) PostVendorJsonWithApplicationVndAPIPlusJSONBodyWithResponse(ctx context.Context, body PostVendorJsonApplicationVndAPIPlusJSONRequestBody, reqEditors ...RequestEditorFn) (*PostVendorJsonResponse, error) { - rsp, err := c.PostVendorJsonWithApplicationVndAPIPlusJSONBody(ctx, body, reqEditors...) +func (c *ClientWithResponses) PostVendorJsonWithResponse(ctx context.Context, body PostVendorJsonJSONRequestBody, reqEditors ...RequestEditorFn) (*PostVendorJsonResponse, error) { + rsp, err := c.PostVendorJson(ctx, body, reqEditors...) if err != nil { return nil, err } diff --git a/internal/test/externalref/externalref.gen.go b/internal/test/externalref/externalref.gen.go index 23beee0f4..b9b62d1b2 100644 --- a/internal/test/externalref/externalref.gen.go +++ b/internal/test/externalref/externalref.gen.go @@ -38,16 +38,16 @@ var swaggerSpec = []string{ 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) + return nil, fmt.Errorf("error base64 decoding spec: %s", err) } zr, err := gzip.NewReader(bytes.NewReader(zipped)) if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) + return nil, fmt.Errorf("error decompressing spec: %s", err) } var buf bytes.Buffer _, err = buf.ReadFrom(zr) if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) + return nil, fmt.Errorf("error decompressing spec: %s", err) } return buf.Bytes(), nil @@ -65,7 +65,7 @@ func decodeSpecCached() func() ([]byte, error) { // 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)) + var res = make(map[string]func() ([]byte, error)) if len(pathToFile) > 0 { res[pathToFile] = rawSpec } @@ -93,12 +93,12 @@ func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { // 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("") + var resolvePath = PathToRawSpec("") loader := openapi3.NewLoader() loader.IsExternalRefsAllowed = true loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() + var pathToFile = url.String() pathToFile = path.Clean(pathToFile) getSpec, ok := resolvePath[pathToFile] if !ok { diff --git a/internal/test/externalref/packageA/externalref.gen.go b/internal/test/externalref/packageA/externalref.gen.go index 0fe09a937..1a4d648dd 100644 --- a/internal/test/externalref/packageA/externalref.gen.go +++ b/internal/test/externalref/packageA/externalref.gen.go @@ -35,16 +35,16 @@ var swaggerSpec = []string{ 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) + return nil, fmt.Errorf("error base64 decoding spec: %s", err) } zr, err := gzip.NewReader(bytes.NewReader(zipped)) if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) + return nil, fmt.Errorf("error decompressing spec: %s", err) } var buf bytes.Buffer _, err = buf.ReadFrom(zr) if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) + return nil, fmt.Errorf("error decompressing spec: %s", err) } return buf.Bytes(), nil @@ -62,7 +62,7 @@ func decodeSpecCached() func() ([]byte, error) { // 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)) + var res = make(map[string]func() ([]byte, error)) if len(pathToFile) > 0 { res[pathToFile] = rawSpec } @@ -84,12 +84,12 @@ func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { // 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("") + var resolvePath = PathToRawSpec("") loader := openapi3.NewLoader() loader.IsExternalRefsAllowed = true loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() + var pathToFile = url.String() pathToFile = path.Clean(pathToFile) getSpec, ok := resolvePath[pathToFile] if !ok { diff --git a/internal/test/externalref/packageB/externalref.gen.go b/internal/test/externalref/packageB/externalref.gen.go index 15791a869..3e4fe051e 100644 --- a/internal/test/externalref/packageB/externalref.gen.go +++ b/internal/test/externalref/packageB/externalref.gen.go @@ -32,16 +32,16 @@ var swaggerSpec = []string{ 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) + return nil, fmt.Errorf("error base64 decoding spec: %s", err) } zr, err := gzip.NewReader(bytes.NewReader(zipped)) if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) + return nil, fmt.Errorf("error decompressing spec: %s", err) } var buf bytes.Buffer _, err = buf.ReadFrom(zr) if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) + return nil, fmt.Errorf("error decompressing spec: %s", err) } return buf.Bytes(), nil @@ -59,7 +59,7 @@ func decodeSpecCached() func() ([]byte, error) { // 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)) + var res = make(map[string]func() ([]byte, error)) if len(pathToFile) > 0 { res[pathToFile] = rawSpec } @@ -73,12 +73,12 @@ func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { // 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("") + var resolvePath = PathToRawSpec("") loader := openapi3.NewLoader() loader.IsExternalRefsAllowed = true loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() + var pathToFile = url.String() pathToFile = path.Clean(pathToFile) getSpec, ok := resolvePath[pathToFile] if !ok { 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 df2711cbd..000000000 --- a/internal/test/issues/issue-1087/api.gen.go +++ /dev/null @@ -1,453 +0,0 @@ -// Package issue1087 provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/deepmap/oapi-codegen version (devel) DO NOT EDIT. -package issue1087 - -import ( - "context" - "encoding/json" - "fmt" - "io" - "net/http" - "net/url" - "strings" - - externalRef0 "github.com/deepmap/oapi-codegen/internal/test/issues/issue-1087/deps" - "github.com/go-chi/chi/v5" -) - -// 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) { - ctx := r.Context() - - 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.WithContext(ctx)) -} - -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/config.yaml b/internal/test/issues/issue-1087/deps/config.yaml deleted file mode 100644 index 01ee1951a..000000000 --- a/internal/test/issues/issue-1087/deps/config.yaml +++ /dev/null @@ -1,8 +0,0 @@ -package: deps -output: - deps.gen.go -output-options: - skip-prune: true -generate: - models: true - embedded-spec: true \ No newline at end of file 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 01263635a..000000000 --- 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/deepmap/oapi-codegen version (devel) 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 5f2295d74..000000000 --- a/internal/test/issues/issue-1087/deps/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -package deps - -//go:generate go run github.com/deepmap/oapi-codegen/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 57674e121..000000000 --- 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 521fd0f11..000000000 --- a/internal/test/issues/issue-1087/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -package issue1087 - -//go:generate go run github.com/deepmap/oapi-codegen/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 8275b35b4..000000000 --- a/internal/test/issues/issue-1087/server.config.yaml +++ /dev/null @@ -1,10 +0,0 @@ -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/deepmap/oapi-codegen/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 5686be9b5..000000000 --- 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 cafa05045..000000000 --- a/internal/test/issues/issue-1093/api/child/child.gen.go +++ /dev/null @@ -1,232 +0,0 @@ -// Package api provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/deepmap/oapi-codegen version (devel) DO NOT EDIT. -package api - -import ( - "bytes" - "compress/gzip" - "context" - "encoding/base64" - "encoding/json" - "fmt" - "net/http" - "net/url" - "path" - "strings" - - externalRef0 "github.com/deepmap/oapi-codegen/internal/test/issues/issue-1093/api/parent" - "github.com/deepmap/oapi-codegen/pkg/runtime" - "github.com/getkin/kin-openapi/openapi3" - "github.com/gin-gonic/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 = runtime.StrictGinHandlerFunc -type StrictMiddlewareFunc = runtime.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/2xRQW7jMAz8isDdoxF7tzd9oOgtKHpLc1BlOlZgSyxJFwgC/72g3CAI0BMpYcgZzlwh", - "lplKxqwC/goSR5xDbfeoVogLIWvC+pnDjFb1QggeRDnlE6wNaDj98r82wPi5JMYe/GGbPjY3VPk4Y1RY", - "DZbyUGxBjxI5kaaSwcPbmMTFMU29E8Lo0kyFVdxcepzEDVxmpyM6CoxZKwYa0KST7a+D0MAXsmz7/u06", - "E1sIc6AEHp523a6DBijoWA9sCTcnTtv5j3peURfO4gj1Ti4XUbQ2aH0vguzGIC7EiCJOy3uGSsrB9rz0", - "4OEZdW9MZpBQybL5+7/rrMSSFXMVEIimFOtgexZTcUvJur+MA3j4095jbH8ybC3A6u3jDcHJUoUNy+Ru", - "5AY0qCCbW+APV1h4Ag/t5uJ6XL8DAAD//w/2Vy4sAgAA", -} - -// 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 - } - - pathPrefix := path.Dir(pathToFile) - - for rawPath, rawFunc := range externalRef0.PathToRawSpec(path.Join(pathPrefix, "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 beb73ab00..000000000 --- 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/deepmap/oapi-codegen version (devel) DO NOT EDIT. -package api - -import ( - "bytes" - "compress/gzip" - "context" - "encoding/base64" - "encoding/json" - "fmt" - "net/http" - "net/url" - "path" - "strings" - - "github.com/deepmap/oapi-codegen/pkg/runtime" - "github.com/getkin/kin-openapi/openapi3" - "github.com/gin-gonic/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 = runtime.StrictGinHandlerFunc -type StrictMiddlewareFunc = runtime.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 c373c1ec2..000000000 --- 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 1ebaf789a..000000000 --- a/internal/test/issues/issue-1093/child.cfg.yaml +++ /dev/null @@ -1,10 +0,0 @@ -# child.yaml -package: api -generate: - gin-server: true - embedded-spec: true - strict-server: true - models: true -import-mapping: - parent.api.yaml: github.com/deepmap/oapi-codegen/internal/test/issues/issue-1093/api/parent -output: api/child/child.gen.go \ No newline at end of file diff --git a/internal/test/issues/issue-1093/doc.go b/internal/test/issues/issue-1093/doc.go deleted file mode 100644 index b80f0e5ee..000000000 --- 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/deepmap/oapi-codegen/issues/1093 -package issue1093 - -//go:generate go run github.com/deepmap/oapi-codegen/cmd/oapi-codegen --config parent.cfg.yaml parent.api.yaml -//go:generate go run github.com/deepmap/oapi-codegen/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 277e7462d..000000000 --- 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/deepmap/oapi-codegen/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/deepmap/oapi-codegen/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 95687168a..000000000 --- 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 306f456cc..000000000 --- a/internal/test/issues/issue-1093/parent.cfg.yaml +++ /dev/null @@ -1,9 +0,0 @@ -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 \ No newline at end of file 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 6b031962a..000000000 --- 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/deepmap/oapi-codegen version (devel) 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 78bc2ef06..000000000 --- a/internal/test/issues/issue-1127/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -package issue1127 - -//go:generate go run github.com/deepmap/oapi-codegen/cmd/oapi-codegen --config=server.config.yaml spec.yaml diff --git a/internal/test/issues/issue-1127/server.config.yaml b/internal/test/issues/issue-1127/server.config.yaml deleted file mode 100644 index 86e0e1e42..000000000 --- a/internal/test/issues/issue-1127/server.config.yaml +++ /dev/null @@ -1,5 +0,0 @@ -package: issue1127 -output: - api.gen.go -generate: - models: true diff --git a/internal/test/issues/issue-1127/spec.yaml b/internal/test/issues/issue-1127/spec.yaml deleted file mode 100644 index e3eee0662..000000000 --- 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 e83f9be28..000000000 --- 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/deepmap/oapi-codegen version (devel) 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 9916b7b85..000000000 --- a/internal/test/issues/issue-1168/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -package issue1168 - -//go:generate go run github.com/deepmap/oapi-codegen/cmd/oapi-codegen --config=server.config.yaml spec.yaml diff --git a/internal/test/issues/issue-1168/server.config.yaml b/internal/test/issues/issue-1168/server.config.yaml deleted file mode 100644 index 7d70ed842..000000000 --- a/internal/test/issues/issue-1168/server.config.yaml +++ /dev/null @@ -1,5 +0,0 @@ -package: issue1168 -output: - api.gen.go -generate: - models: true diff --git a/internal/test/issues/issue-1168/spec.yaml b/internal/test/issues/issue-1168/spec.yaml deleted file mode 100644 index 72af58325..000000000 --- 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-312/issue.gen.go b/internal/test/issues/issue-312/issue.gen.go index 074b89d52..31ee2bb9c 100644 --- a/internal/test/issues/issue-312/issue.gen.go +++ b/internal/test/issues/issue-312/issue.gen.go @@ -121,7 +121,7 @@ type ClientInterface interface { // GetPet request GetPet(ctx context.Context, petId string, reqEditors ...RequestEditorFn) (*http.Response, error) - // ValidatePetsWithBody request with any body + // ValidatePets request with any body ValidatePetsWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) ValidatePets(ctx context.Context, body ValidatePetsJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) @@ -280,10 +280,10 @@ func WithBaseURL(baseURL string) ClientOption { // ClientWithResponsesInterface is the interface specification for the client with responses above. type ClientWithResponsesInterface interface { - // GetPetWithResponse request + // GetPet request GetPetWithResponse(ctx context.Context, petId string, reqEditors ...RequestEditorFn) (*GetPetResponse, error) - // ValidatePetsWithBodyWithResponse request with any body + // ValidatePets request with any body ValidatePetsWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*ValidatePetsResponse, error) ValidatePetsWithResponse(ctx context.Context, body ValidatePetsJSONRequestBody, reqEditors ...RequestEditorFn) (*ValidatePetsResponse, error) @@ -511,16 +511,16 @@ var swaggerSpec = []string{ 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) + return nil, fmt.Errorf("error base64 decoding spec: %s", err) } zr, err := gzip.NewReader(bytes.NewReader(zipped)) if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) + return nil, fmt.Errorf("error decompressing spec: %s", err) } var buf bytes.Buffer _, err = buf.ReadFrom(zr) if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) + return nil, fmt.Errorf("error decompressing spec: %s", err) } return buf.Bytes(), nil @@ -538,7 +538,7 @@ func decodeSpecCached() func() ([]byte, error) { // 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)) + var res = make(map[string]func() ([]byte, error)) if len(pathToFile) > 0 { res[pathToFile] = rawSpec } @@ -552,12 +552,12 @@ func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { // 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("") + var resolvePath = PathToRawSpec("") loader := openapi3.NewLoader() loader.IsExternalRefsAllowed = true loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() + var pathToFile = url.String() pathToFile = path.Clean(pathToFile) getSpec, ok := resolvePath[pathToFile] if !ok { diff --git a/internal/test/issues/issue-52/issue.gen.go b/internal/test/issues/issue-52/issue.gen.go index b6f3dbaec..fb3b38b5f 100644 --- a/internal/test/issues/issue-52/issue.gen.go +++ b/internal/test/issues/issue-52/issue.gen.go @@ -193,7 +193,7 @@ func WithBaseURL(baseURL string) ClientOption { // ClientWithResponsesInterface is the interface specification for the client with responses above. type ClientWithResponsesInterface interface { - // ExampleGetWithResponse request + // ExampleGet request ExampleGetWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*ExampleGetResponse, error) } @@ -323,16 +323,16 @@ var swaggerSpec = []string{ 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) + return nil, fmt.Errorf("error base64 decoding spec: %s", err) } zr, err := gzip.NewReader(bytes.NewReader(zipped)) if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) + return nil, fmt.Errorf("error decompressing spec: %s", err) } var buf bytes.Buffer _, err = buf.ReadFrom(zr) if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) + return nil, fmt.Errorf("error decompressing spec: %s", err) } return buf.Bytes(), nil @@ -350,7 +350,7 @@ func decodeSpecCached() func() ([]byte, error) { // 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)) + var res = make(map[string]func() ([]byte, error)) if len(pathToFile) > 0 { res[pathToFile] = rawSpec } @@ -364,12 +364,12 @@ func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { // 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("") + var resolvePath = PathToRawSpec("") loader := openapi3.NewLoader() loader.IsExternalRefsAllowed = true loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() + var pathToFile = url.String() pathToFile = path.Clean(pathToFile) getSpec, ok := resolvePath[pathToFile] if !ok { diff --git a/internal/test/issues/issue-832/issue.gen.go b/internal/test/issues/issue-832/issue.gen.go index a8fe23304..6bad2fbda 100644 --- a/internal/test/issues/issue-832/issue.gen.go +++ b/internal/test/issues/issue-832/issue.gen.go @@ -53,16 +53,16 @@ var swaggerSpec = []string{ 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) + return nil, fmt.Errorf("error base64 decoding spec: %s", err) } zr, err := gzip.NewReader(bytes.NewReader(zipped)) if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) + return nil, fmt.Errorf("error decompressing spec: %s", err) } var buf bytes.Buffer _, err = buf.ReadFrom(zr) if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) + return nil, fmt.Errorf("error decompressing spec: %s", err) } return buf.Bytes(), nil @@ -80,7 +80,7 @@ func decodeSpecCached() func() ([]byte, error) { // 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)) + var res = make(map[string]func() ([]byte, error)) if len(pathToFile) > 0 { res[pathToFile] = rawSpec } @@ -94,12 +94,12 @@ func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { // 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("") + var resolvePath = PathToRawSpec("") loader := openapi3.NewLoader() loader.IsExternalRefsAllowed = true loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() + var pathToFile = url.String() pathToFile = path.Clean(pathToFile) getSpec, ok := resolvePath[pathToFile] if !ok { diff --git a/internal/test/issues/issue-grab_import_names/issue.gen.go b/internal/test/issues/issue-grab_import_names/issue.gen.go index 56312ae0e..aa05713fd 100644 --- a/internal/test/issues/issue-grab_import_names/issue.gen.go +++ b/internal/test/issues/issue-grab_import_names/issue.gen.go @@ -215,7 +215,7 @@ func WithBaseURL(baseURL string) ClientOption { // ClientWithResponsesInterface is the interface specification for the client with responses above. type ClientWithResponsesInterface interface { - // GetFooWithResponse request + // GetFoo request GetFooWithResponse(ctx context.Context, params *GetFooParams, reqEditors ...RequestEditorFn) (*GetFooResponse, error) } @@ -380,16 +380,16 @@ var swaggerSpec = []string{ 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) + return nil, fmt.Errorf("error base64 decoding spec: %s", err) } zr, err := gzip.NewReader(bytes.NewReader(zipped)) if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) + return nil, fmt.Errorf("error decompressing spec: %s", err) } var buf bytes.Buffer _, err = buf.ReadFrom(zr) if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) + return nil, fmt.Errorf("error decompressing spec: %s", err) } return buf.Bytes(), nil @@ -407,7 +407,7 @@ func decodeSpecCached() func() ([]byte, error) { // 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)) + var res = make(map[string]func() ([]byte, error)) if len(pathToFile) > 0 { res[pathToFile] = rawSpec } @@ -421,12 +421,12 @@ func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { // 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("") + var resolvePath = PathToRawSpec("") loader := openapi3.NewLoader() loader.IsExternalRefsAllowed = true loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() + var pathToFile = url.String() pathToFile = path.Clean(pathToFile) getSpec, ok := resolvePath[pathToFile] if !ok { diff --git a/internal/test/issues/issue-illegal_enum_names/issue.gen.go b/internal/test/issues/issue-illegal_enum_names/issue.gen.go index 7e76a1e6f..65d66460d 100644 --- a/internal/test/issues/issue-illegal_enum_names/issue.gen.go +++ b/internal/test/issues/issue-illegal_enum_names/issue.gen.go @@ -196,7 +196,7 @@ func WithBaseURL(baseURL string) ClientOption { // ClientWithResponsesInterface is the interface specification for the client with responses above. type ClientWithResponsesInterface interface { - // GetFooWithResponse request + // GetFoo request GetFooWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*GetFooResponse, error) } @@ -325,16 +325,16 @@ var swaggerSpec = []string{ 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) + return nil, fmt.Errorf("error base64 decoding spec: %s", err) } zr, err := gzip.NewReader(bytes.NewReader(zipped)) if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) + return nil, fmt.Errorf("error decompressing spec: %s", err) } var buf bytes.Buffer _, err = buf.ReadFrom(zr) if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) + return nil, fmt.Errorf("error decompressing spec: %s", err) } return buf.Bytes(), nil @@ -352,7 +352,7 @@ func decodeSpecCached() func() ([]byte, error) { // 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)) + var res = make(map[string]func() ([]byte, error)) if len(pathToFile) > 0 { res[pathToFile] = rawSpec } @@ -366,12 +366,12 @@ func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { // 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("") + var resolvePath = PathToRawSpec("") loader := openapi3.NewLoader() loader.IsExternalRefsAllowed = true loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() + var pathToFile = url.String() pathToFile = path.Clean(pathToFile) getSpec, ok := resolvePath[pathToFile] if !ok { 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 index efc756947..11247c7f2 100644 --- 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 @@ -34,20 +34,6 @@ type ServerInterface interface { 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 @@ -61,9 +47,9 @@ type MiddlewareFunc func(http.Handler) http.Handler func (siw *ServerInterfaceWrapper) PostInvalidExtRefTrouble(w http.ResponseWriter, r *http.Request) { ctx := r.Context() - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var 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) @@ -76,9 +62,9 @@ func (siw *ServerInterfaceWrapper) PostInvalidExtRefTrouble(w http.ResponseWrite func (siw *ServerInterfaceWrapper) PostNoTrouble(w http.ResponseWriter, r *http.Request) { ctx := r.Context() - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var 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) 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 index 8bea148d6..53c506de8 100644 --- 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 @@ -35,10 +35,6 @@ type Pascal = PascalSchema 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 diff --git a/internal/test/parameters/parameters.gen.go b/internal/test/parameters/parameters.gen.go index 01af8d4bb..d301fe13e 100644 --- a/internal/test/parameters/parameters.gen.go +++ b/internal/test/parameters/parameters.gen.go @@ -1648,67 +1648,67 @@ func WithBaseURL(baseURL string) ClientOption { // ClientWithResponsesInterface is the interface specification for the client with responses above. type ClientWithResponsesInterface interface { - // GetContentObjectWithResponse request + // GetContentObject request GetContentObjectWithResponse(ctx context.Context, param ComplexObject, reqEditors ...RequestEditorFn) (*GetContentObjectResponse, error) - // GetCookieWithResponse request + // GetCookie request GetCookieWithResponse(ctx context.Context, params *GetCookieParams, reqEditors ...RequestEditorFn) (*GetCookieResponse, error) - // EnumParamsWithResponse request + // EnumParams request EnumParamsWithResponse(ctx context.Context, params *EnumParamsParams, reqEditors ...RequestEditorFn) (*EnumParamsResponse, error) - // GetHeaderWithResponse request + // GetHeader request GetHeaderWithResponse(ctx context.Context, params *GetHeaderParams, reqEditors ...RequestEditorFn) (*GetHeaderResponse, error) - // GetLabelExplodeArrayWithResponse request + // GetLabelExplodeArray request GetLabelExplodeArrayWithResponse(ctx context.Context, param []int32, reqEditors ...RequestEditorFn) (*GetLabelExplodeArrayResponse, error) - // GetLabelExplodeObjectWithResponse request + // GetLabelExplodeObject request GetLabelExplodeObjectWithResponse(ctx context.Context, param Object, reqEditors ...RequestEditorFn) (*GetLabelExplodeObjectResponse, error) - // GetLabelNoExplodeArrayWithResponse request + // GetLabelNoExplodeArray request GetLabelNoExplodeArrayWithResponse(ctx context.Context, param []int32, reqEditors ...RequestEditorFn) (*GetLabelNoExplodeArrayResponse, error) - // GetLabelNoExplodeObjectWithResponse request + // GetLabelNoExplodeObject request GetLabelNoExplodeObjectWithResponse(ctx context.Context, param Object, reqEditors ...RequestEditorFn) (*GetLabelNoExplodeObjectResponse, error) - // GetMatrixExplodeArrayWithResponse request + // GetMatrixExplodeArray request GetMatrixExplodeArrayWithResponse(ctx context.Context, id []int32, reqEditors ...RequestEditorFn) (*GetMatrixExplodeArrayResponse, error) - // GetMatrixExplodeObjectWithResponse request + // GetMatrixExplodeObject request GetMatrixExplodeObjectWithResponse(ctx context.Context, id Object, reqEditors ...RequestEditorFn) (*GetMatrixExplodeObjectResponse, error) - // GetMatrixNoExplodeArrayWithResponse request + // GetMatrixNoExplodeArray request GetMatrixNoExplodeArrayWithResponse(ctx context.Context, id []int32, reqEditors ...RequestEditorFn) (*GetMatrixNoExplodeArrayResponse, error) - // GetMatrixNoExplodeObjectWithResponse request + // GetMatrixNoExplodeObject request GetMatrixNoExplodeObjectWithResponse(ctx context.Context, id Object, reqEditors ...RequestEditorFn) (*GetMatrixNoExplodeObjectResponse, error) - // GetPassThroughWithResponse request + // GetPassThrough request GetPassThroughWithResponse(ctx context.Context, param string, reqEditors ...RequestEditorFn) (*GetPassThroughResponse, error) - // GetDeepObjectWithResponse request + // GetDeepObject request GetDeepObjectWithResponse(ctx context.Context, params *GetDeepObjectParams, reqEditors ...RequestEditorFn) (*GetDeepObjectResponse, error) - // GetQueryFormWithResponse request + // GetQueryForm request GetQueryFormWithResponse(ctx context.Context, params *GetQueryFormParams, reqEditors ...RequestEditorFn) (*GetQueryFormResponse, error) - // GetSimpleExplodeArrayWithResponse request + // GetSimpleExplodeArray request GetSimpleExplodeArrayWithResponse(ctx context.Context, param []int32, reqEditors ...RequestEditorFn) (*GetSimpleExplodeArrayResponse, error) - // GetSimpleExplodeObjectWithResponse request + // GetSimpleExplodeObject request GetSimpleExplodeObjectWithResponse(ctx context.Context, param Object, reqEditors ...RequestEditorFn) (*GetSimpleExplodeObjectResponse, error) - // GetSimpleNoExplodeArrayWithResponse request + // GetSimpleNoExplodeArray request GetSimpleNoExplodeArrayWithResponse(ctx context.Context, param []int32, reqEditors ...RequestEditorFn) (*GetSimpleNoExplodeArrayResponse, error) - // GetSimpleNoExplodeObjectWithResponse request + // GetSimpleNoExplodeObject request GetSimpleNoExplodeObjectWithResponse(ctx context.Context, param Object, reqEditors ...RequestEditorFn) (*GetSimpleNoExplodeObjectResponse, error) - // GetSimplePrimitiveWithResponse request + // GetSimplePrimitive request GetSimplePrimitiveWithResponse(ctx context.Context, param int32, reqEditors ...RequestEditorFn) (*GetSimplePrimitiveResponse, error) - // GetStartingWithNumberWithResponse request + // GetStartingWithNumber request GetStartingWithNumberWithResponse(ctx context.Context, n1param string, reqEditors ...RequestEditorFn) (*GetStartingWithNumberResponse, error) } @@ -3437,16 +3437,16 @@ var swaggerSpec = []string{ 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) + return nil, fmt.Errorf("error base64 decoding spec: %s", err) } zr, err := gzip.NewReader(bytes.NewReader(zipped)) if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) + return nil, fmt.Errorf("error decompressing spec: %s", err) } var buf bytes.Buffer _, err = buf.ReadFrom(zr) if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) + return nil, fmt.Errorf("error decompressing spec: %s", err) } return buf.Bytes(), nil @@ -3464,7 +3464,7 @@ func decodeSpecCached() func() ([]byte, error) { // 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)) + var res = make(map[string]func() ([]byte, error)) if len(pathToFile) > 0 { res[pathToFile] = rawSpec } @@ -3478,12 +3478,12 @@ func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { // 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("") + var resolvePath = PathToRawSpec("") loader := openapi3.NewLoader() loader.IsExternalRefsAllowed = true loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() + var pathToFile = url.String() pathToFile = path.Clean(pathToFile) getSpec, ok := resolvePath[pathToFile] if !ok { diff --git a/internal/test/schemas/schemas.gen.go b/internal/test/schemas/schemas.gen.go index 72dacaf60..6492939cb 100644 --- a/internal/test/schemas/schemas.gen.go +++ b/internal/test/schemas/schemas.gen.go @@ -195,7 +195,7 @@ type ClientInterface interface { // Issue127 request Issue127(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) - // Issue185WithBody request with any body + // Issue185 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) @@ -212,7 +212,7 @@ type ClientInterface interface { // Issue41 request Issue41(ctx context.Context, n1param N5StartsWithNumber, reqEditors ...RequestEditorFn) (*http.Response, error) - // Issue9WithBody request with any body + // Issue9 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) @@ -743,38 +743,38 @@ func WithBaseURL(baseURL string) ClientOption { // ClientWithResponsesInterface is the interface specification for the client with responses above. type ClientWithResponsesInterface interface { - // EnsureEverythingIsReferencedWithResponse request + // EnsureEverythingIsReferenced request EnsureEverythingIsReferencedWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*EnsureEverythingIsReferencedResponse, error) - // Issue1051WithResponse request + // Issue1051 request Issue1051WithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*Issue1051Response, error) - // Issue127WithResponse request + // Issue127 request Issue127WithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*Issue127Response, error) - // Issue185WithBodyWithResponse request with any body + // Issue185 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 + // Issue209 request Issue209WithResponse(ctx context.Context, str StringInPath, reqEditors ...RequestEditorFn) (*Issue209Response, error) - // Issue30WithResponse request + // Issue30 request Issue30WithResponse(ctx context.Context, pFallthrough string, reqEditors ...RequestEditorFn) (*Issue30Response, error) - // GetIssues375WithResponse request + // GetIssues375 request GetIssues375WithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*GetIssues375Response, error) - // Issue41WithResponse request + // Issue41 request Issue41WithResponse(ctx context.Context, n1param N5StartsWithNumber, reqEditors ...RequestEditorFn) (*Issue41Response, error) - // Issue9WithBodyWithResponse request with any body + // Issue9 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 + // Issue975 request Issue975WithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*Issue975Response, error) } @@ -1612,16 +1612,16 @@ var swaggerSpec = []string{ 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) + return nil, fmt.Errorf("error base64 decoding spec: %s", err) } zr, err := gzip.NewReader(bytes.NewReader(zipped)) if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) + return nil, fmt.Errorf("error decompressing spec: %s", err) } var buf bytes.Buffer _, err = buf.ReadFrom(zr) if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) + return nil, fmt.Errorf("error decompressing spec: %s", err) } return buf.Bytes(), nil @@ -1639,7 +1639,7 @@ func decodeSpecCached() func() ([]byte, error) { // 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)) + var res = make(map[string]func() ([]byte, error)) if len(pathToFile) > 0 { res[pathToFile] = rawSpec } @@ -1653,12 +1653,12 @@ func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { // 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("") + var resolvePath = PathToRawSpec("") loader := openapi3.NewLoader() loader.IsExternalRefsAllowed = true loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() + var pathToFile = url.String() pathToFile = path.Clean(pathToFile) getSpec, ok := resolvePath[pathToFile] if !ok { diff --git a/internal/test/server/server.gen.go b/internal/test/server/server.gen.go index 2c8769201..d676d1625 100644 --- a/internal/test/server/server.gen.go +++ b/internal/test/server/server.gen.go @@ -162,71 +162,6 @@ type ServerInterface interface { 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 @@ -240,9 +175,9 @@ type MiddlewareFunc func(http.Handler) http.Handler func (siw *ServerInterfaceWrapper) GetEveryTypeOptional(w http.ResponseWriter, r *http.Request) { ctx := r.Context() - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var 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) @@ -255,9 +190,9 @@ func (siw *ServerInterfaceWrapper) GetEveryTypeOptional(w http.ResponseWriter, r func (siw *ServerInterfaceWrapper) GetSimple(w http.ResponseWriter, r *http.Request) { ctx := r.Context() - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var 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) @@ -319,9 +254,9 @@ func (siw *ServerInterfaceWrapper) GetWithArgs(w http.ResponseWriter, r *http.Re } - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var 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) @@ -354,9 +289,9 @@ func (siw *ServerInterfaceWrapper) GetWithReferences(w http.ResponseWriter, r *h return } - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var 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) @@ -380,9 +315,9 @@ func (siw *ServerInterfaceWrapper) GetWithContentType(w http.ResponseWriter, r * return } - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var 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) @@ -395,9 +330,9 @@ func (siw *ServerInterfaceWrapper) GetWithContentType(w http.ResponseWriter, r * func (siw *ServerInterfaceWrapper) GetReservedKeyword(w http.ResponseWriter, r *http.Request) { ctx := r.Context() - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var 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) @@ -421,9 +356,9 @@ func (siw *ServerInterfaceWrapper) CreateResource(w http.ResponseWriter, r *http return } - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var 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) @@ -458,9 +393,9 @@ func (siw *ServerInterfaceWrapper) CreateResource2(w http.ResponseWriter, r *htt return } - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var 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) @@ -484,9 +419,9 @@ func (siw *ServerInterfaceWrapper) UpdateResource3(w http.ResponseWriter, r *htt return } - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var 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) @@ -499,9 +434,9 @@ func (siw *ServerInterfaceWrapper) UpdateResource3(w http.ResponseWriter, r *htt func (siw *ServerInterfaceWrapper) GetResponseWithReference(w http.ResponseWriter, r *http.Request) { ctx := r.Context() - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var 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) diff --git a/internal/test/strict-server/chi/server.gen.go b/internal/test/strict-server/chi/server.gen.go index d442c43a9..5d17d7492 100644 --- a/internal/test/strict-server/chi/server.gen.go +++ b/internal/test/strict-server/chi/server.gen.go @@ -59,65 +59,6 @@ type ServerInterface interface { 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 /multiple) -func (_ Unimplemented) MultipleRequestAndResponseTypes(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 @@ -131,9 +72,9 @@ type MiddlewareFunc func(http.Handler) http.Handler func (siw *ServerInterfaceWrapper) JSONExample(w http.ResponseWriter, r *http.Request) { ctx := r.Context() - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var 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) @@ -146,9 +87,9 @@ func (siw *ServerInterfaceWrapper) JSONExample(w http.ResponseWriter, r *http.Re func (siw *ServerInterfaceWrapper) MultipartExample(w http.ResponseWriter, r *http.Request) { ctx := r.Context() - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var 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) @@ -161,9 +102,9 @@ func (siw *ServerInterfaceWrapper) MultipartExample(w http.ResponseWriter, r *ht func (siw *ServerInterfaceWrapper) MultipleRequestAndResponseTypes(w http.ResponseWriter, r *http.Request) { ctx := r.Context() - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var 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) @@ -187,9 +128,9 @@ func (siw *ServerInterfaceWrapper) ReservedGoKeywordParameters(w http.ResponseWr return } - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var 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) @@ -202,9 +143,9 @@ func (siw *ServerInterfaceWrapper) ReservedGoKeywordParameters(w http.ResponseWr func (siw *ServerInterfaceWrapper) ReusableResponses(w http.ResponseWriter, r *http.Request) { ctx := r.Context() - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var 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) @@ -217,9 +158,9 @@ func (siw *ServerInterfaceWrapper) ReusableResponses(w http.ResponseWriter, r *h func (siw *ServerInterfaceWrapper) TextExample(w http.ResponseWriter, r *http.Request) { ctx := r.Context() - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var 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) @@ -232,9 +173,9 @@ func (siw *ServerInterfaceWrapper) TextExample(w http.ResponseWriter, r *http.Re func (siw *ServerInterfaceWrapper) UnknownExample(w http.ResponseWriter, r *http.Request) { ctx := r.Context() - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var 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) @@ -247,9 +188,9 @@ func (siw *ServerInterfaceWrapper) UnknownExample(w http.ResponseWriter, r *http func (siw *ServerInterfaceWrapper) UnspecifiedContentType(w http.ResponseWriter, r *http.Request) { ctx := r.Context() - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var 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) @@ -262,9 +203,9 @@ func (siw *ServerInterfaceWrapper) UnspecifiedContentType(w http.ResponseWriter, func (siw *ServerInterfaceWrapper) URLEncodedExample(w http.ResponseWriter, r *http.Request) { ctx := r.Context() - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var 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) @@ -326,9 +267,9 @@ func (siw *ServerInterfaceWrapper) HeadersExample(w http.ResponseWriter, r *http } - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var 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) @@ -341,9 +282,9 @@ func (siw *ServerInterfaceWrapper) HeadersExample(w http.ResponseWriter, r *http func (siw *ServerInterfaceWrapper) UnionExample(w http.ResponseWriter, r *http.Request) { ctx := r.Context() - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var 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) @@ -694,9 +635,9 @@ type ReusableResponsesResponseObject interface { 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.Header().Set("Content-Type", "application/json") w.WriteHeader(200) return json.NewEncoder(w).Encode(response.Body) @@ -914,9 +855,9 @@ type HeadersExample200JSONResponse struct { } 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.Header().Set("Content-Type", "application/json") w.WriteHeader(200) return json.NewEncoder(w).Encode(response.Body) @@ -951,20 +892,6 @@ type UnionExample200ResponseHeaders struct { 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 @@ -973,9 +900,9 @@ type UnionExample200JSONResponse struct { } 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.Header().Set("Content-Type", "application/json") w.WriteHeader(200) return json.NewEncoder(w).Encode(response.Body.union) @@ -1130,7 +1057,6 @@ func (sh *strictHandler) MultipleRequestAndResponseTypes(w http.ResponseWriter, 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 { sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't decode JSON body: %w", err)) @@ -1436,23 +1362,23 @@ func (sh *strictHandler) UnionExample(w http.ResponseWriter, r *http.Request) { // Base64 encoded, gzipped, json marshaled Swagger object var swaggerSpec = []string{ - "H4sIAAAAAAAC/+xYS2/jNhD+KwTb01aynGxOunWDxbbdtimc5FTkQIsjm7sSyQ5HVgzD/72gKL9ixbW3", - "fhRBb3oMvxl+8+BwZjwzpTUaNDmezjiCs0Y7aF6GQiL8VYEj/ybBZagsKaN5yj8IOWj/zSOOUDkxLGCx", - "3MtnRhPoZqmwtlCZ8EuTL86vn3GXjaEU/ul7hJyn/LtkZUoS/roEnkVpC+Dz+Tx6YcHdZx7xMQgJ2Fgb", - "Hq82sWlqgafcESo94h4kiF13iilNMAL02rxoa4QXWNiRzrhFYwFJBY4moqigW1P7xQy/QEZhB0rnZpvL", - "W6NJKO2YVHkOCJpYSx7zGI65ylqDBJINp8xryIg5wAkgjzgp8obx+/XvrDXY8YhPAF1QdNXr9/reX8aC", - "FlbxlL9vPkXcCho3G1o6yJouv/9yf/c7U46JikwpSGWiKKasFOjGogDJlCbjTawycj3eaMLG8T/LdvXH", - "lkofNU0AfTByeoqAaeJyLZyv+/0zxeU84jdBWRfG0qhkLcEamFxURQfnj/qrNrVmgGiw3VlSVgUpK5DW", - "fbXJ9m8LkX0oX+IlucEyloLEiVg/lqaLEt/Wgs4cuR+b2rGxqRkZJkEUrFY0ZouFL5JbaSaYU3pUAFsY", - "FXV6soC25P6o5aDdy4PHOHkuRRsoz3Fd13HjvAoL0JmRIL8NVpViBInVo83lHlsQT/lwSj5st4vrkYIo", - "4gTPlNhCKL375DhTOfmf6aMldkhXhOZElPHIxF9hWhuUsRUoSiBAl8y89rkHHkFHKv+xlGSZ0GwITIsS", - "JBM5AbJPhrWQbitlB63eT+ZzEFlBNcft8iX9c8Y9Jc0RzCPuFfA0sBLyWqF3OmEF0Q7anv4xPv+VAxZs", - "hkYv3lDVXQYXJWpJHULufEns8lwHf0HTYE3iMg3D7ojban3PcQZ5T75+7j/A815H/hFL37lz+1DCqvDx", - "dc7aVfvQ9o2VdA8WJ0qCSUp7cyDyxUh1FjKVK5Bxu4s42PZaSbg1OkOgzRbIXye0IbYE87ccGgMLDETM", - "GVYDKytHzArnmKKmihQq3JQkbBWPx5Vlt0HTw6qc7vLquxP59N2lPHrTvzp8yfsTx81GK/NKPg5+/Rhk", - "Dr0vHq1nOrDjO57eC6Wzv6TEawOV7hT+KQiszvQM1MR3RFoyBKpQg2QTJRZDgK3cbAFWbu3qhYIZq25o", - "Mdw5pCGKdmJd82jXAOjpDY8nTjk2O1ecVlrtGlM9+t+s7aFfng3K6P/oEEoUBKgFqQn8cJwb5DaK0XCX", - "N5n2wsvRnhqe3l5UzSMe5qahBFVY+DpBZNMkCfPWnqvFaATYUyYRVnkW/g4AAP//Pk3lbjwXAAA=", + "H4sIAAAAAAAC/+xYS2/jNhD+KwO2p4VkOdmcdOsGi227bVM4yanIgRZHNnclkiVHVgzD/72gKL9ixbW3", + "fqDB3vSYF795cmYs06XRChU5ls6YRWe0cti8DLmw+HeFjvybQJdZaUhqxVL2gYtB+28eMYuV48MCF+ye", + "PtOKUDWs3JhCZtyzJl+c558xl42x5P7pR4s5S9kPycqUJPx1CT7z0hTI5vN59MKCu88sYmPkAm1jbXi8", + "2pRNU4MsZY6sVCPmhQSy604yqQhHaL02T9oa4QkWdqQzZqw2aEkGjCa8qLBbU/tFD79gRuEEUuV6G8tb", + "rYhL5UDIPEeLiqAFD7wMB64yRltCAcMpeA0ZgUM7QcsiRpK8Yex+/Tu0BjsWsQlaFxRd9fq9vveXNqi4", + "kSxl75tPETOcxs2Blg4yusvvv97f/QHSAa9Il5xkxotiCiW3bswLFCAVaW9ilZHrsUaTbRz/i2i5P7ZQ", + "+qhpAuiDFtNTBEwTl2vhfN3vnyku5xG7Ccq6ZCyNStYSrBGT86rowPxRfVW6VoDWatueLCmrgqThltZ9", + "tYn27wuSfSBfyktybctYcOInQv1Ymi4KfFsLOnPkfqxrB2NdA2kQyAuoJY1hwfgiuaUCDk6qUYGwMCrq", + "9GSBbcn9SYlBe5YHL+PkuRRtSHmO67qOG+dVtkCVaYHi28TKko8wMWq0ye5lc2IpG07Jh+12cT1SEEWM", + "8JkSU3CpdneOM5WT70gfLbFDulpsOqKIRzr+itNaWxEbbnmJhNYlM6997gWPsCOV/1xSQsYVDBEUL1EA", + "zwktfNLQinRbKTto9X7SnwPJSlTTbpcv6V8z5iFpWjCLmFfA0oBKyGtpvdPJVhjtgO3pX+PzPzlggWYY", + "9OINVd1lcFGiltBZzJ0viV2e68AvaBqsUVxmYNgdcVuj7zl6kPfk633/AZ/3avlHLH3nzu1DAavCx9cx", + "a7n2ge0bK+keKE6kQJ2U5uZAyRcD1RnMZC5RxO0p4mDbayXhVqvMIm2OQP46oTTBUpi/5dAYISAQgdNQ", + "I5SVIzDcOZDUVJFChpuSwK3i8biy7DZoeliV011efXcin767lEdv+leHs7w/cdxsjDKv5OPgt4+B5tD7", + "4tFmpgMnvuPpvVA6+0tKvLZQ6U7hnwPBqqdnKCd+IlICLFJlFQqYSL5YAmzlZitg5dauWSiYsZqGFsud", + "QwaiaKesaxbtWgA9veH1xCnXZueK00rJXWuqR/8b2hn6ZW+QWv1vllBa4V3e5MULn0R7mvD09mJgHrGw", + "5QwFo7KFz2oikyZJ2I72XM1HI7Q9qRNupEfhnwAAAP//4wU1quoWAAA=", } // GetSwagger returns the content of the embedded swagger specification file @@ -1460,16 +1386,16 @@ var swaggerSpec = []string{ 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) + return nil, fmt.Errorf("error base64 decoding spec: %s", err) } zr, err := gzip.NewReader(bytes.NewReader(zipped)) if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) + return nil, fmt.Errorf("error decompressing spec: %s", err) } var buf bytes.Buffer _, err = buf.ReadFrom(zr) if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) + return nil, fmt.Errorf("error decompressing spec: %s", err) } return buf.Bytes(), nil @@ -1487,7 +1413,7 @@ func decodeSpecCached() func() ([]byte, error) { // 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)) + var res = make(map[string]func() ([]byte, error)) if len(pathToFile) > 0 { res[pathToFile] = rawSpec } @@ -1501,12 +1427,12 @@ func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { // 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("") + var resolvePath = PathToRawSpec("") loader := openapi3.NewLoader() loader.IsExternalRefsAllowed = true loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() + var pathToFile = url.String() pathToFile = path.Clean(pathToFile) getSpec, ok := resolvePath[pathToFile] if !ok { diff --git a/internal/test/strict-server/client/client.gen.go b/internal/test/strict-server/client/client.gen.go index d0a1353cc..2a8c2c3c1 100644 --- a/internal/test/strict-server/client/client.gen.go +++ b/internal/test/strict-server/client/client.gen.go @@ -142,15 +142,15 @@ func WithRequestEditorFn(fn RequestEditorFn) ClientOption { // The interface specification for the client above. type ClientInterface interface { - // JSONExampleWithBody request with any body + // JSONExample 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 + // MultipartExample request with any body MultipartExampleWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) - // MultipleRequestAndResponseTypesWithBody request with any body + // MultipleRequestAndResponseTypes 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) @@ -162,33 +162,33 @@ type ClientInterface interface { // ReservedGoKeywordParameters request ReservedGoKeywordParameters(ctx context.Context, pType string, reqEditors ...RequestEditorFn) (*http.Response, error) - // ReusableResponsesWithBody request with any body + // ReusableResponses 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 + // TextExample 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 + // UnknownExample request with any body UnknownExampleWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) - // UnspecifiedContentTypeWithBody request with any body + // UnspecifiedContentType request with any body UnspecifiedContentTypeWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) - // URLEncodedExampleWithBody request with any body + // URLEncodedExample 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 + // HeadersExample 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 + // UnionExample 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) @@ -916,15 +916,15 @@ func WithBaseURL(baseURL string) ClientOption { // ClientWithResponsesInterface is the interface specification for the client with responses above. type ClientWithResponsesInterface interface { - // JSONExampleWithBodyWithResponse request with any body + // JSONExample 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 + // MultipartExample request with any body MultipartExampleWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*MultipartExampleResponse, error) - // MultipleRequestAndResponseTypesWithBodyWithResponse request with any body + // MultipleRequestAndResponseTypes 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) @@ -933,36 +933,36 @@ type ClientWithResponsesInterface interface { MultipleRequestAndResponseTypesWithTextBodyWithResponse(ctx context.Context, body MultipleRequestAndResponseTypesTextRequestBody, reqEditors ...RequestEditorFn) (*MultipleRequestAndResponseTypesResponse, error) - // ReservedGoKeywordParametersWithResponse request + // ReservedGoKeywordParameters request ReservedGoKeywordParametersWithResponse(ctx context.Context, pType string, reqEditors ...RequestEditorFn) (*ReservedGoKeywordParametersResponse, error) - // ReusableResponsesWithBodyWithResponse request with any body + // ReusableResponses 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 + // TextExample 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 + // UnknownExample request with any body UnknownExampleWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*UnknownExampleResponse, error) - // UnspecifiedContentTypeWithBodyWithResponse request with any body + // UnspecifiedContentType request with any body UnspecifiedContentTypeWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*UnspecifiedContentTypeResponse, error) - // URLEncodedExampleWithBodyWithResponse request with any body + // URLEncodedExample 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 + // HeadersExample 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 + // UnionExample 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) @@ -1057,7 +1057,7 @@ func (r ReservedGoKeywordParametersResponse) StatusCode() int { type ReusableResponsesResponse struct { Body []byte HTTPResponse *http.Response - JSON200 *Reusableresponse + JSON200 *Example } // Status returns HTTPResponse.Status @@ -1183,10 +1183,9 @@ func (r HeadersExampleResponse) StatusCode() int { } type UnionExampleResponse struct { - Body []byte - HTTPResponse *http.Response - ApplicationalternativeJSON200 *Example - JSON200 *struct { + Body []byte + HTTPResponse *http.Response + JSON200 *struct { union json.RawMessage } } @@ -1480,7 +1479,7 @@ func ParseReusableResponsesResponse(rsp *http.Response) (*ReusableResponsesRespo switch { case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest Reusableresponse + var dest Example if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } diff --git a/internal/test/strict-server/echo/server.gen.go b/internal/test/strict-server/echo/server.gen.go index 00f00cb4c..aed4500b1 100644 --- a/internal/test/strict-server/echo/server.gen.go +++ b/internal/test/strict-server/echo/server.gen.go @@ -441,9 +441,9 @@ type ReusableResponsesResponseObject interface { 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.Header().Set("Content-Type", "application/json") w.WriteHeader(200) return json.NewEncoder(w).Encode(response.Body) @@ -661,9 +661,9 @@ type HeadersExample200JSONResponse struct { } 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.Header().Set("Content-Type", "application/json") w.WriteHeader(200) return json.NewEncoder(w).Encode(response.Body) @@ -698,20 +698,6 @@ type UnionExample200ResponseHeaders struct { 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 @@ -720,9 +706,9 @@ type UnionExample200JSONResponse struct { } 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.Header().Set("Content-Type", "application/json") w.WriteHeader(200) return json.NewEncoder(w).Encode(response.Body.union) @@ -1143,23 +1129,23 @@ func (sh *strictHandler) UnionExample(ctx echo.Context) error { // Base64 encoded, gzipped, json marshaled Swagger object var swaggerSpec = []string{ - "H4sIAAAAAAAC/+xYS2/jNhD+KwTb01aynGxOunWDxbbdtimc5FTkQIsjm7sSyQ5HVgzD/72gKL9ixbW3", - "fhRBb3oMvxl+8+BwZjwzpTUaNDmezjiCs0Y7aF6GQiL8VYEj/ybBZagsKaN5yj8IOWj/zSOOUDkxLGCx", - "3MtnRhPoZqmwtlCZ8EuTL86vn3GXjaEU/ul7hJyn/LtkZUoS/roEnkVpC+Dz+Tx6YcHdZx7xMQgJ2Fgb", - "Hq82sWlqgafcESo94h4kiF13iilNMAL02rxoa4QXWNiRzrhFYwFJBY4moqigW1P7xQy/QEZhB0rnZpvL", - "W6NJKO2YVHkOCJpYSx7zGI65ylqDBJINp8xryIg5wAkgjzgp8obx+/XvrDXY8YhPAF1QdNXr9/reX8aC", - "FlbxlL9vPkXcCho3G1o6yJouv/9yf/c7U46JikwpSGWiKKasFOjGogDJlCbjTawycj3eaMLG8T/LdvXH", - "lkofNU0AfTByeoqAaeJyLZyv+/0zxeU84jdBWRfG0qhkLcEamFxURQfnj/qrNrVmgGiw3VlSVgUpK5DW", - "fbXJ9m8LkX0oX+IlucEyloLEiVg/lqaLEt/Wgs4cuR+b2rGxqRkZJkEUrFY0ZouFL5JbaSaYU3pUAFsY", - "FXV6soC25P6o5aDdy4PHOHkuRRsoz3Fd13HjvAoL0JmRIL8NVpViBInVo83lHlsQT/lwSj5st4vrkYIo", - "4gTPlNhCKL375DhTOfmf6aMldkhXhOZElPHIxF9hWhuUsRUoSiBAl8y89rkHHkFHKv+xlGSZ0GwITIsS", - "JBM5AbJPhrWQbitlB63eT+ZzEFlBNcft8iX9c8Y9Jc0RzCPuFfA0sBLyWqF3OmEF0Q7anv4xPv+VAxZs", - "hkYv3lDVXQYXJWpJHULufEns8lwHf0HTYE3iMg3D7ojban3PcQZ5T75+7j/A815H/hFL37lz+1DCqvDx", - "dc7aVfvQ9o2VdA8WJ0qCSUp7cyDyxUh1FjKVK5Bxu4s42PZaSbg1OkOgzRbIXye0IbYE87ccGgMLDETM", - "GVYDKytHzArnmKKmihQq3JQkbBWPx5Vlt0HTw6qc7vLquxP59N2lPHrTvzp8yfsTx81GK/NKPg5+/Rhk", - "Dr0vHq1nOrDjO57eC6Wzv6TEawOV7hT+KQiszvQM1MR3RFoyBKpQg2QTJRZDgK3cbAFWbu3qhYIZq25o", - "Mdw5pCGKdmJd82jXAOjpDY8nTjk2O1ecVlrtGlM9+t+s7aFfng3K6P/oEEoUBKgFqQn8cJwb5DaK0XCX", - "N5n2wsvRnhqe3l5UzSMe5qahBFVY+DpBZNMkCfPWnqvFaATYUyYRVnkW/g4AAP//Pk3lbjwXAAA=", + "H4sIAAAAAAAC/+xYS2/jNhD+KwO2p4VkOdmcdOsGi227bVM4yanIgRZHNnclkiVHVgzD/72gKL9ixbW3", + "fqDB3vSYF795cmYs06XRChU5ls6YRWe0cti8DLmw+HeFjvybQJdZaUhqxVL2gYtB+28eMYuV48MCF+ye", + "PtOKUDWs3JhCZtyzJl+c558xl42x5P7pR4s5S9kPycqUJPx1CT7z0hTI5vN59MKCu88sYmPkAm1jbXi8", + "2pRNU4MsZY6sVCPmhQSy604yqQhHaL02T9oa4QkWdqQzZqw2aEkGjCa8qLBbU/tFD79gRuEEUuV6G8tb", + "rYhL5UDIPEeLiqAFD7wMB64yRltCAcMpeA0ZgUM7QcsiRpK8Yex+/Tu0BjsWsQlaFxRd9fq9vveXNqi4", + "kSxl75tPETOcxs2Blg4yusvvv97f/QHSAa9Il5xkxotiCiW3bswLFCAVaW9ilZHrsUaTbRz/i2i5P7ZQ", + "+qhpAuiDFtNTBEwTl2vhfN3vnyku5xG7Ccq6ZCyNStYSrBGT86rowPxRfVW6VoDWatueLCmrgqThltZ9", + "tYn27wuSfSBfyktybctYcOInQv1Ymi4KfFsLOnPkfqxrB2NdA2kQyAuoJY1hwfgiuaUCDk6qUYGwMCrq", + "9GSBbcn9SYlBe5YHL+PkuRRtSHmO67qOG+dVtkCVaYHi28TKko8wMWq0ye5lc2IpG07Jh+12cT1SEEWM", + "8JkSU3CpdneOM5WT70gfLbFDulpsOqKIRzr+itNaWxEbbnmJhNYlM6997gWPsCOV/1xSQsYVDBEUL1EA", + "zwktfNLQinRbKTto9X7SnwPJSlTTbpcv6V8z5iFpWjCLmFfA0oBKyGtpvdPJVhjtgO3pX+PzPzlggWYY", + "9OINVd1lcFGiltBZzJ0viV2e68AvaBqsUVxmYNgdcVuj7zl6kPfk633/AZ/3avlHLH3nzu1DAavCx9cx", + "a7n2ge0bK+keKE6kQJ2U5uZAyRcD1RnMZC5RxO0p4mDbayXhVqvMIm2OQP46oTTBUpi/5dAYISAQgdNQ", + "I5SVIzDcOZDUVJFChpuSwK3i8biy7DZoeliV011efXcin767lEdv+leHs7w/cdxsjDKv5OPgt4+B5tD7", + "4tFmpgMnvuPpvVA6+0tKvLZQ6U7hnwPBqqdnKCd+IlICLFJlFQqYSL5YAmzlZitg5dauWSiYsZqGFsud", + "QwaiaKesaxbtWgA9veH1xCnXZueK00rJXWuqR/8b2hn6ZW+QWv1vllBa4V3e5MULn0R7mvD09mJgHrGw", + "5QwFo7KFz2oikyZJ2I72XM1HI7Q9qRNupEfhnwAAAP//4wU1quoWAAA=", } // GetSwagger returns the content of the embedded swagger specification file @@ -1167,16 +1153,16 @@ var swaggerSpec = []string{ 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) + return nil, fmt.Errorf("error base64 decoding spec: %s", err) } zr, err := gzip.NewReader(bytes.NewReader(zipped)) if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) + return nil, fmt.Errorf("error decompressing spec: %s", err) } var buf bytes.Buffer _, err = buf.ReadFrom(zr) if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) + return nil, fmt.Errorf("error decompressing spec: %s", err) } return buf.Bytes(), nil @@ -1194,7 +1180,7 @@ func decodeSpecCached() func() ([]byte, error) { // 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)) + var res = make(map[string]func() ([]byte, error)) if len(pathToFile) > 0 { res[pathToFile] = rawSpec } @@ -1208,12 +1194,12 @@ func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { // 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("") + var resolvePath = PathToRawSpec("") loader := openapi3.NewLoader() loader.IsExternalRefsAllowed = true loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() + var pathToFile = url.String() pathToFile = path.Clean(pathToFile) getSpec, ok := resolvePath[pathToFile] if !ok { diff --git a/internal/test/strict-server/fiber/server.gen.go b/internal/test/strict-server/fiber/server.gen.go index e22523797..ec8b6ba4a 100644 --- a/internal/test/strict-server/fiber/server.gen.go +++ b/internal/test/strict-server/fiber/server.gen.go @@ -672,20 +672,6 @@ type UnionExample200ResponseHeaders struct { 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 @@ -831,7 +817,6 @@ 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 { return fiber.NewError(fiber.StatusBadRequest, err.Error()) @@ -1119,23 +1104,23 @@ func (sh *strictHandler) UnionExample(ctx *fiber.Ctx) error { // Base64 encoded, gzipped, json marshaled Swagger object var swaggerSpec = []string{ - "H4sIAAAAAAAC/+xYS2/jNhD+KwTb01aynGxOunWDxbbdtimc5FTkQIsjm7sSyQ5HVgzD/72gKL9ixbW3", - "fhRBb3oMvxl+8+BwZjwzpTUaNDmezjiCs0Y7aF6GQiL8VYEj/ybBZagsKaN5yj8IOWj/zSOOUDkxLGCx", - "3MtnRhPoZqmwtlCZ8EuTL86vn3GXjaEU/ul7hJyn/LtkZUoS/roEnkVpC+Dz+Tx6YcHdZx7xMQgJ2Fgb", - "Hq82sWlqgafcESo94h4kiF13iilNMAL02rxoa4QXWNiRzrhFYwFJBY4moqigW1P7xQy/QEZhB0rnZpvL", - "W6NJKO2YVHkOCJpYSx7zGI65ylqDBJINp8xryIg5wAkgjzgp8obx+/XvrDXY8YhPAF1QdNXr9/reX8aC", - "FlbxlL9vPkXcCho3G1o6yJouv/9yf/c7U46JikwpSGWiKKasFOjGogDJlCbjTawycj3eaMLG8T/LdvXH", - "lkofNU0AfTByeoqAaeJyLZyv+/0zxeU84jdBWRfG0qhkLcEamFxURQfnj/qrNrVmgGiw3VlSVgUpK5DW", - "fbXJ9m8LkX0oX+IlucEyloLEiVg/lqaLEt/Wgs4cuR+b2rGxqRkZJkEUrFY0ZouFL5JbaSaYU3pUAFsY", - "FXV6soC25P6o5aDdy4PHOHkuRRsoz3Fd13HjvAoL0JmRIL8NVpViBInVo83lHlsQT/lwSj5st4vrkYIo", - "4gTPlNhCKL375DhTOfmf6aMldkhXhOZElPHIxF9hWhuUsRUoSiBAl8y89rkHHkFHKv+xlGSZ0GwITIsS", - "JBM5AbJPhrWQbitlB63eT+ZzEFlBNcft8iX9c8Y9Jc0RzCPuFfA0sBLyWqF3OmEF0Q7anv4xPv+VAxZs", - "hkYv3lDVXQYXJWpJHULufEns8lwHf0HTYE3iMg3D7ojban3PcQZ5T75+7j/A815H/hFL37lz+1DCqvDx", - "dc7aVfvQ9o2VdA8WJ0qCSUp7cyDyxUh1FjKVK5Bxu4s42PZaSbg1OkOgzRbIXye0IbYE87ccGgMLDETM", - "GVYDKytHzArnmKKmihQq3JQkbBWPx5Vlt0HTw6qc7vLquxP59N2lPHrTvzp8yfsTx81GK/NKPg5+/Rhk", - "Dr0vHq1nOrDjO57eC6Wzv6TEawOV7hT+KQiszvQM1MR3RFoyBKpQg2QTJRZDgK3cbAFWbu3qhYIZq25o", - "Mdw5pCGKdmJd82jXAOjpDY8nTjk2O1ecVlrtGlM9+t+s7aFfng3K6P/oEEoUBKgFqQn8cJwb5DaK0XCX", - "N5n2wsvRnhqe3l5UzSMe5qahBFVY+DpBZNMkCfPWnqvFaATYUyYRVnkW/g4AAP//Pk3lbjwXAAA=", + "H4sIAAAAAAAC/+xYS2/jNhD+KwO2p4VkOdmcdOsGi227bVM4yanIgRZHNnclkiVHVgzD/72gKL9ixbW3", + "fqDB3vSYF795cmYs06XRChU5ls6YRWe0cti8DLmw+HeFjvybQJdZaUhqxVL2gYtB+28eMYuV48MCF+ye", + "PtOKUDWs3JhCZtyzJl+c558xl42x5P7pR4s5S9kPycqUJPx1CT7z0hTI5vN59MKCu88sYmPkAm1jbXi8", + "2pRNU4MsZY6sVCPmhQSy604yqQhHaL02T9oa4QkWdqQzZqw2aEkGjCa8qLBbU/tFD79gRuEEUuV6G8tb", + "rYhL5UDIPEeLiqAFD7wMB64yRltCAcMpeA0ZgUM7QcsiRpK8Yex+/Tu0BjsWsQlaFxRd9fq9vveXNqi4", + "kSxl75tPETOcxs2Blg4yusvvv97f/QHSAa9Il5xkxotiCiW3bswLFCAVaW9ilZHrsUaTbRz/i2i5P7ZQ", + "+qhpAuiDFtNTBEwTl2vhfN3vnyku5xG7Ccq6ZCyNStYSrBGT86rowPxRfVW6VoDWatueLCmrgqThltZ9", + "tYn27wuSfSBfyktybctYcOInQv1Ymi4KfFsLOnPkfqxrB2NdA2kQyAuoJY1hwfgiuaUCDk6qUYGwMCrq", + "9GSBbcn9SYlBe5YHL+PkuRRtSHmO67qOG+dVtkCVaYHi28TKko8wMWq0ye5lc2IpG07Jh+12cT1SEEWM", + "8JkSU3CpdneOM5WT70gfLbFDulpsOqKIRzr+itNaWxEbbnmJhNYlM6997gWPsCOV/1xSQsYVDBEUL1EA", + "zwktfNLQinRbKTto9X7SnwPJSlTTbpcv6V8z5iFpWjCLmFfA0oBKyGtpvdPJVhjtgO3pX+PzPzlggWYY", + "9OINVd1lcFGiltBZzJ0viV2e68AvaBqsUVxmYNgdcVuj7zl6kPfk633/AZ/3avlHLH3nzu1DAavCx9cx", + "a7n2ge0bK+keKE6kQJ2U5uZAyRcD1RnMZC5RxO0p4mDbayXhVqvMIm2OQP46oTTBUpi/5dAYISAQgdNQ", + "I5SVIzDcOZDUVJFChpuSwK3i8biy7DZoeliV011efXcin767lEdv+leHs7w/cdxsjDKv5OPgt4+B5tD7", + "4tFmpgMnvuPpvVA6+0tKvLZQ6U7hnwPBqqdnKCd+IlICLFJlFQqYSL5YAmzlZitg5dauWSiYsZqGFsud", + "QwaiaKesaxbtWgA9veH1xCnXZueK00rJXWuqR/8b2hn6ZW+QWv1vllBa4V3e5MULn0R7mvD09mJgHrGw", + "5QwFo7KFz2oikyZJ2I72XM1HI7Q9qRNupEfhnwAAAP//4wU1quoWAAA=", } // GetSwagger returns the content of the embedded swagger specification file @@ -1143,16 +1128,16 @@ var swaggerSpec = []string{ 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) + return nil, fmt.Errorf("error base64 decoding spec: %s", err) } zr, err := gzip.NewReader(bytes.NewReader(zipped)) if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) + return nil, fmt.Errorf("error decompressing spec: %s", err) } var buf bytes.Buffer _, err = buf.ReadFrom(zr) if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) + return nil, fmt.Errorf("error decompressing spec: %s", err) } return buf.Bytes(), nil @@ -1170,7 +1155,7 @@ func decodeSpecCached() func() ([]byte, error) { // 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)) + var res = make(map[string]func() ([]byte, error)) if len(pathToFile) > 0 { res[pathToFile] = rawSpec } @@ -1184,12 +1169,12 @@ func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { // 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("") + var resolvePath = PathToRawSpec("") loader := openapi3.NewLoader() loader.IsExternalRefsAllowed = true loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() + var pathToFile = url.String() pathToFile = path.Clean(pathToFile) getSpec, ok := resolvePath[pathToFile] if !ok { diff --git a/internal/test/strict-server/gin/server.gen.go b/internal/test/strict-server/gin/server.gen.go index 99c8608cb..05614bce9 100644 --- a/internal/test/strict-server/gin/server.gen.go +++ b/internal/test/strict-server/gin/server.gen.go @@ -117,7 +117,7 @@ func (siw *ServerInterfaceWrapper) ReservedGoKeywordParameters(c *gin.Context) { err = runtime.BindStyledParameter("simple", false, "type", c.Param("type"), &pType) if err != nil { - siw.ErrorHandler(c, fmt.Errorf("Invalid format for parameter type: %w", err), http.StatusBadRequest) + siw.ErrorHandler(c, fmt.Errorf("Invalid format for parameter type: %s", err), http.StatusBadRequest) return } @@ -217,7 +217,7 @@ func (siw *ServerInterfaceWrapper) HeadersExample(c *gin.Context) { err = runtime.BindStyledParameterWithLocation("simple", false, "header1", runtime.ParamLocationHeader, valueList[0], &Header1) if err != nil { - siw.ErrorHandler(c, fmt.Errorf("Invalid format for parameter header1: %w", err), http.StatusBadRequest) + siw.ErrorHandler(c, fmt.Errorf("Invalid format for parameter header1: %s", err), http.StatusBadRequest) return } @@ -239,7 +239,7 @@ func (siw *ServerInterfaceWrapper) HeadersExample(c *gin.Context) { err = runtime.BindStyledParameterWithLocation("simple", false, "header2", runtime.ParamLocationHeader, valueList[0], &Header2) if err != nil { - siw.ErrorHandler(c, fmt.Errorf("Invalid format for parameter header2: %w", err), http.StatusBadRequest) + siw.ErrorHandler(c, fmt.Errorf("Invalid format for parameter header2: %s", err), http.StatusBadRequest) return } @@ -502,9 +502,9 @@ type ReusableResponsesResponseObject interface { 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.Header().Set("Content-Type", "application/json") w.WriteHeader(200) return json.NewEncoder(w).Encode(response.Body) @@ -722,9 +722,9 @@ type HeadersExample200JSONResponse struct { } 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.Header().Set("Content-Type", "application/json") w.WriteHeader(200) return json.NewEncoder(w).Encode(response.Body) @@ -759,20 +759,6 @@ type UnionExample200ResponseHeaders struct { 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 @@ -781,9 +767,9 @@ type UnionExample200JSONResponse struct { } 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.Header().Set("Content-Type", "application/json") w.WriteHeader(200) return json.NewEncoder(w).Encode(response.Body.union) @@ -924,7 +910,6 @@ 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.ShouldBind(&body); err != nil { ctx.Status(http.StatusBadRequest) @@ -1243,23 +1228,23 @@ func (sh *strictHandler) UnionExample(ctx *gin.Context) { // Base64 encoded, gzipped, json marshaled Swagger object var swaggerSpec = []string{ - "H4sIAAAAAAAC/+xYS2/jNhD+KwTb01aynGxOunWDxbbdtimc5FTkQIsjm7sSyQ5HVgzD/72gKL9ixbW3", - "fhRBb3oMvxl+8+BwZjwzpTUaNDmezjiCs0Y7aF6GQiL8VYEj/ybBZagsKaN5yj8IOWj/zSOOUDkxLGCx", - "3MtnRhPoZqmwtlCZ8EuTL86vn3GXjaEU/ul7hJyn/LtkZUoS/roEnkVpC+Dz+Tx6YcHdZx7xMQgJ2Fgb", - "Hq82sWlqgafcESo94h4kiF13iilNMAL02rxoa4QXWNiRzrhFYwFJBY4moqigW1P7xQy/QEZhB0rnZpvL", - "W6NJKO2YVHkOCJpYSx7zGI65ylqDBJINp8xryIg5wAkgjzgp8obx+/XvrDXY8YhPAF1QdNXr9/reX8aC", - "FlbxlL9vPkXcCho3G1o6yJouv/9yf/c7U46JikwpSGWiKKasFOjGogDJlCbjTawycj3eaMLG8T/LdvXH", - "lkofNU0AfTByeoqAaeJyLZyv+/0zxeU84jdBWRfG0qhkLcEamFxURQfnj/qrNrVmgGiw3VlSVgUpK5DW", - "fbXJ9m8LkX0oX+IlucEyloLEiVg/lqaLEt/Wgs4cuR+b2rGxqRkZJkEUrFY0ZouFL5JbaSaYU3pUAFsY", - "FXV6soC25P6o5aDdy4PHOHkuRRsoz3Fd13HjvAoL0JmRIL8NVpViBInVo83lHlsQT/lwSj5st4vrkYIo", - "4gTPlNhCKL375DhTOfmf6aMldkhXhOZElPHIxF9hWhuUsRUoSiBAl8y89rkHHkFHKv+xlGSZ0GwITIsS", - "JBM5AbJPhrWQbitlB63eT+ZzEFlBNcft8iX9c8Y9Jc0RzCPuFfA0sBLyWqF3OmEF0Q7anv4xPv+VAxZs", - "hkYv3lDVXQYXJWpJHULufEns8lwHf0HTYE3iMg3D7ojban3PcQZ5T75+7j/A815H/hFL37lz+1DCqvDx", - "dc7aVfvQ9o2VdA8WJ0qCSUp7cyDyxUh1FjKVK5Bxu4s42PZaSbg1OkOgzRbIXye0IbYE87ccGgMLDETM", - "GVYDKytHzArnmKKmihQq3JQkbBWPx5Vlt0HTw6qc7vLquxP59N2lPHrTvzp8yfsTx81GK/NKPg5+/Rhk", - "Dr0vHq1nOrDjO57eC6Wzv6TEawOV7hT+KQiszvQM1MR3RFoyBKpQg2QTJRZDgK3cbAFWbu3qhYIZq25o", - "Mdw5pCGKdmJd82jXAOjpDY8nTjk2O1ecVlrtGlM9+t+s7aFfng3K6P/oEEoUBKgFqQn8cJwb5DaK0XCX", - "N5n2wsvRnhqe3l5UzSMe5qahBFVY+DpBZNMkCfPWnqvFaATYUyYRVnkW/g4AAP//Pk3lbjwXAAA=", + "H4sIAAAAAAAC/+xYS2/jNhD+KwO2p4VkOdmcdOsGi227bVM4yanIgRZHNnclkiVHVgzD/72gKL9ixbW3", + "fqDB3vSYF795cmYs06XRChU5ls6YRWe0cti8DLmw+HeFjvybQJdZaUhqxVL2gYtB+28eMYuV48MCF+ye", + "PtOKUDWs3JhCZtyzJl+c558xl42x5P7pR4s5S9kPycqUJPx1CT7z0hTI5vN59MKCu88sYmPkAm1jbXi8", + "2pRNU4MsZY6sVCPmhQSy604yqQhHaL02T9oa4QkWdqQzZqw2aEkGjCa8qLBbU/tFD79gRuEEUuV6G8tb", + "rYhL5UDIPEeLiqAFD7wMB64yRltCAcMpeA0ZgUM7QcsiRpK8Yex+/Tu0BjsWsQlaFxRd9fq9vveXNqi4", + "kSxl75tPETOcxs2Blg4yusvvv97f/QHSAa9Il5xkxotiCiW3bswLFCAVaW9ilZHrsUaTbRz/i2i5P7ZQ", + "+qhpAuiDFtNTBEwTl2vhfN3vnyku5xG7Ccq6ZCyNStYSrBGT86rowPxRfVW6VoDWatueLCmrgqThltZ9", + "tYn27wuSfSBfyktybctYcOInQv1Ymi4KfFsLOnPkfqxrB2NdA2kQyAuoJY1hwfgiuaUCDk6qUYGwMCrq", + "9GSBbcn9SYlBe5YHL+PkuRRtSHmO67qOG+dVtkCVaYHi28TKko8wMWq0ye5lc2IpG07Jh+12cT1SEEWM", + "8JkSU3CpdneOM5WT70gfLbFDulpsOqKIRzr+itNaWxEbbnmJhNYlM6997gWPsCOV/1xSQsYVDBEUL1EA", + "zwktfNLQinRbKTto9X7SnwPJSlTTbpcv6V8z5iFpWjCLmFfA0oBKyGtpvdPJVhjtgO3pX+PzPzlggWYY", + "9OINVd1lcFGiltBZzJ0viV2e68AvaBqsUVxmYNgdcVuj7zl6kPfk633/AZ/3avlHLH3nzu1DAavCx9cx", + "a7n2ge0bK+keKE6kQJ2U5uZAyRcD1RnMZC5RxO0p4mDbayXhVqvMIm2OQP46oTTBUpi/5dAYISAQgdNQ", + "I5SVIzDcOZDUVJFChpuSwK3i8biy7DZoeliV011efXcin767lEdv+leHs7w/cdxsjDKv5OPgt4+B5tD7", + "4tFmpgMnvuPpvVA6+0tKvLZQ6U7hnwPBqqdnKCd+IlICLFJlFQqYSL5YAmzlZitg5dauWSiYsZqGFsud", + "QwaiaKesaxbtWgA9veH1xCnXZueK00rJXWuqR/8b2hn6ZW+QWv1vllBa4V3e5MULn0R7mvD09mJgHrGw", + "5QwFo7KFz2oikyZJ2I72XM1HI7Q9qRNupEfhnwAAAP//4wU1quoWAAA=", } // GetSwagger returns the content of the embedded swagger specification file @@ -1267,16 +1252,16 @@ var swaggerSpec = []string{ 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) + return nil, fmt.Errorf("error base64 decoding spec: %s", err) } zr, err := gzip.NewReader(bytes.NewReader(zipped)) if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) + return nil, fmt.Errorf("error decompressing spec: %s", err) } var buf bytes.Buffer _, err = buf.ReadFrom(zr) if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) + return nil, fmt.Errorf("error decompressing spec: %s", err) } return buf.Bytes(), nil @@ -1294,7 +1279,7 @@ func decodeSpecCached() func() ([]byte, error) { // 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)) + var res = make(map[string]func() ([]byte, error)) if len(pathToFile) > 0 { res[pathToFile] = rawSpec } @@ -1308,12 +1293,12 @@ func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { // 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("") + var resolvePath = PathToRawSpec("") loader := openapi3.NewLoader() loader.IsExternalRefsAllowed = true loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() + var pathToFile = url.String() pathToFile = path.Clean(pathToFile) getSpec, ok := resolvePath[pathToFile] if !ok { diff --git a/internal/test/strict-server/strict-schema.yaml b/internal/test/strict-server/strict-schema.yaml index b75759264..d748b716f 100644 --- a/internal/test/strict-server/strict-schema.yaml +++ b/internal/test/strict-server/strict-schema.yaml @@ -270,9 +270,6 @@ paths: oneOf: - type: string - $ref: "#/components/schemas/example" - application/alternative+json: - schema: - $ref: "#/components/schemas/example" 400: $ref: "#/components/responses/badrequest" default: diff --git a/pkg/chi-middleware/oapi_validate.go b/pkg/chi-middleware/oapi_validate.go index ea64510ea..b654dc3cf 100644 --- a/pkg/chi-middleware/oapi_validate.go +++ b/pkg/chi-middleware/oapi_validate.go @@ -4,6 +4,7 @@ package middleware import ( + "context" "errors" "fmt" "log" @@ -40,7 +41,7 @@ func OapiRequestValidator(swagger *openapi3.T) func(next http.Handler) http.Hand // OapiRequestValidatorWithOptions Creates middleware to validate request by swagger spec. // This middleware is good for net/http either since go-chi is 100% compatible with net/http. func OapiRequestValidatorWithOptions(swagger *openapi3.T, options *Options) func(next http.Handler) http.Handler { - if swagger.Servers != nil && (options == nil || !options.SilenceServersWarning) { + if swagger.Servers != nil && (options == nil || options.SilenceServersWarning) { log.Println("WARN: OapiRequestValidatorWithOptions called with an OpenAPI spec that has `Servers` set. This may lead to an HTTP 400 with `no matching operation was found` when sending a valid request, as the validator performs `Host` header validation. If you're expecting `Host` header validation, you can silence this warning by setting `Options.SilenceServersWarning = true`. See https://github.com/deepmap/oapi-codegen/issues/882 for more information.") } @@ -69,14 +70,14 @@ func OapiRequestValidatorWithOptions(swagger *openapi3.T, options *Options) func } -// validateRequest is called from the middleware above and actually does the work +// This function is called from the middleware above and actually does the work // of validating a request. func validateRequest(r *http.Request, router routers.Router, options *Options) (int, error) { // Find route route, pathParams, err := router.FindRoute(r) if err != nil { - return http.StatusNotFound, err // We failed to find a matching route for the request. + return http.StatusBadRequest, err // We failed to find a matching route for the request. } // Validate request @@ -90,7 +91,7 @@ func validateRequest(r *http.Request, router routers.Router, options *Options) ( requestValidationInput.Options = &options.Options } - if err := openapi3filter.ValidateRequest(r.Context(), requestValidationInput); err != nil { + if err := openapi3filter.ValidateRequest(context.Background(), requestValidationInput); err != nil { me := openapi3.MultiError{} if errors.As(err, &me) { errFunc := getMultiErrorHandlerFromOptions(options) diff --git a/pkg/chi-middleware/oapi_validate_test.go b/pkg/chi-middleware/oapi_validate_test.go index 44816dc51..d10df5cbc 100644 --- a/pkg/chi-middleware/oapi_validate_test.go +++ b/pkg/chi-middleware/oapi_validate_test.go @@ -338,10 +338,10 @@ func testRequestValidatorBasicFunctions(t *testing.T, r *chi.Mux) { called = true }) - // Let's send the request to the wrong server, this should return 404 + // Let's send the request to the wrong server, this should fail validation { rec := doGet(t, r, "http://not.deepmap.ai/resource") - assert.Equal(t, http.StatusNotFound, rec.Code) + assert.Equal(t, http.StatusBadRequest, rec.Code) assert.False(t, called, "Handler should not have been called") } diff --git a/pkg/codegen/codegen.go b/pkg/codegen/codegen.go index 45891aadf..6cb5fec5a 100644 --- a/pkg/codegen/codegen.go +++ b/pkg/codegen/codegen.go @@ -28,7 +28,6 @@ import ( "strings" "text/template" - "github.com/deepmap/oapi-codegen/pkg/util" "github.com/getkin/kin-openapi/openapi3" "golang.org/x/tools/imports" ) @@ -541,15 +540,12 @@ func GenerateTypesForResponses(t *template.Template, responses openapi3.Response responseOrRef := responses[responseName] // We have to generate the response object. We're only going to - // handle media types that conform to JSON. Other responses should + // handle application/json media types here. Other responses should // simply be specified as strings or byte arrays. response := responseOrRef.Value - for mediaType, response := range response.Content { - if !util.IsMediaTypeJson(mediaType) { - continue - } - - goType, err := GenerateGoSchema(response.Schema, []string{responseName}) + jsonResponse, found := response.Content["application/json"] + if found { + goType, err := GenerateGoSchema(jsonResponse.Schema, []string{responseName}) if err != nil { return nil, fmt.Errorf("error generating Go type for schema in response %s: %w", responseName, err) } @@ -573,7 +569,6 @@ func GenerateTypesForResponses(t *template.Template, responses openapi3.Response } typeDef.TypeName = SchemaNameToTypeName(refType) } - types = append(types, typeDef) } } @@ -591,12 +586,9 @@ func GenerateTypesForRequestBodies(t *template.Template, bodies map[string]*open // As for responses, we will only generate Go code for JSON bodies, // the other body formats are up to the user. response := requestBodyRef.Value - for mediaType, body := range response.Content { - if !util.IsMediaTypeJson(mediaType) { - continue - } - - goType, err := GenerateGoSchema(body.Schema, []string{requestBodyName}) + jsonBody, found := response.Content["application/json"] + if found { + goType, err := GenerateGoSchema(jsonBody.Schema, []string{requestBodyName}) if err != nil { return nil, fmt.Errorf("error generating Go type for schema in body %s: %w", requestBodyName, err) } @@ -851,24 +843,24 @@ func SanitizeCode(goCode string) string { // This function will attempt to load a file first, and if it fails, will try to get the // data from the remote endpoint. func GetUserTemplateText(inputData string) (template string, err error) { - // if the input data is more than one line, assume its a template and return that data. + //if the input data is more than one line, assume its a template and return that data. if strings.Contains(inputData, "\n") { return inputData, nil } - // load data from file + //load data from file data, err := os.ReadFile(inputData) - // return data if found and loaded + //return data if found and loaded if err == nil { return string(data), nil } - // check for non "not found" errors + //check for non "not found" errors if !os.IsNotExist(err) { return "", fmt.Errorf("failed to open file %s: %w", inputData, err) } - // attempt to get data from url + //attempt to get data from url resp, err := http.Get(inputData) if err != nil { return "", fmt.Errorf("failed to execute GET request data from %s: %w", inputData, err) @@ -1056,12 +1048,9 @@ func GetRequestBodiesImports(bodies map[string]*openapi3.RequestBodyRef) (map[st res := map[string]goImport{} for _, r := range bodies { response := r.Value - for mediaType, body := range response.Content { - if !util.IsMediaTypeJson(mediaType) { - continue - } - - imprts, err := GoSchemaImports(body.Schema) + jsonBody, found := response.Content["application/json"] + if found { + imprts, err := GoSchemaImports(jsonBody.Schema) if err != nil { return nil, err } @@ -1075,12 +1064,9 @@ func GetResponsesImports(responses map[string]*openapi3.ResponseRef) (map[string res := map[string]goImport{} for _, r := range responses { response := r.Value - for mediaType, body := range response.Content { - if !util.IsMediaTypeJson(mediaType) { - continue - } - - imprts, err := GoSchemaImports(body.Schema) + jsonResponse, found := response.Content["application/json"] + if found { + imprts, err := GoSchemaImports(jsonResponse.Schema) if err != nil { return nil, err } diff --git a/pkg/codegen/codegen_test.go b/pkg/codegen/codegen_test.go index 069597c6d..a127bf0a2 100644 --- a/pkg/codegen/codegen_test.go +++ b/pkg/codegen/codegen_test.go @@ -10,14 +10,13 @@ import ( "net/http" "testing" + examplePetstoreClient "github.com/deepmap/oapi-codegen/examples/petstore-expanded" + examplePetstore "github.com/deepmap/oapi-codegen/examples/petstore-expanded/echo/api" + "github.com/deepmap/oapi-codegen/pkg/util" "github.com/getkin/kin-openapi/openapi3" "github.com/golangci/lint-1" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - - examplePetstoreClient "github.com/deepmap/oapi-codegen/examples/petstore-expanded" - examplePetstore "github.com/deepmap/oapi-codegen/examples/petstore-expanded/echo/api" - "github.com/deepmap/oapi-codegen/pkg/util" ) const ( @@ -157,7 +156,7 @@ func TestExamplePetStoreCodeGenerationWithHTTPUserTemplates(t *testing.T) { defer ln.Close() //nolint:errcheck - // Does not matter if the server returns an error on close etc. + //Does not matter if the server returns an error on close etc. go http.Serve(ln, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, writeErr := w.Write([]byte("//blah")) assert.NoError(t, writeErr) @@ -289,44 +288,6 @@ type GetTestByNameResponse struct { checkLint(t, "test.gen.go", []byte(code)) } -func TestExtPropGoTypeSkipOptionalPointer(t *testing.T) { - packageName := "api" - opts := Configuration{ - PackageName: packageName, - Generate: GenerateOptions{ - EchoServer: true, - Models: true, - EmbeddedSpec: true, - Strict: true, - }, - } - spec := "test_specs/x-go-type-skip-optional-pointer.yaml" - swagger, err := util.LoadSwagger(spec) - require.NoError(t, err) - - // Run our code generation: - code, err := Generate(swagger, opts) - assert.NoError(t, err) - assert.NotEmpty(t, code) - - // Check that we have valid (formattable) code: - _, err = format.Source([]byte(code)) - assert.NoError(t, err) - - // Check that optional pointer fields are skipped if requested - assert.Contains(t, code, "NullableFieldSkipFalse *string `json:\"nullableFieldSkipFalse\"`") - assert.Contains(t, code, "NullableFieldSkipTrue string `json:\"nullableFieldSkipTrue\"`") - assert.Contains(t, code, "OptionalField *string `json:\"optionalField,omitempty\"`") - assert.Contains(t, code, "OptionalFieldSkipFalse *string `json:\"optionalFieldSkipFalse,omitempty\"`") - assert.Contains(t, code, "OptionalFieldSkipTrue string `json:\"optionalFieldSkipTrue,omitempty\"`") - - // Check that the extension applies on custom types as well - assert.Contains(t, code, "CustomTypeWithSkipTrue string `json:\"customTypeWithSkipTrue,omitempty\"`") - - // Check that the extension has no effect on required fields - assert.Contains(t, code, "RequiredField string `json:\"requiredField\"`") -} - func TestGoTypeImport(t *testing.T) { packageName := "api" opts := Configuration{ diff --git a/pkg/codegen/extension.go b/pkg/codegen/extension.go index 29c9727a4..ca4c3b669 100644 --- a/pkg/codegen/extension.go +++ b/pkg/codegen/extension.go @@ -7,9 +7,6 @@ import ( const ( // extPropGoType overrides the generated type definition. extPropGoType = "x-go-type" - // extPropGoTypeSkipOptionalPointer specifies that optional fields should - // be the type itself instead of a pointer to the type. - extPropGoTypeSkipOptionalPointer = "x-go-type-skip-optional-pointer" // extPropGoImport specifies the module to import which provides above type extPropGoImport = "x-go-type-import" // extGoName is used to override a field name @@ -31,19 +28,10 @@ func extString(extPropValue interface{}) (string, error) { } return str, nil } - func extTypeName(extPropValue interface{}) (string, error) { return extString(extPropValue) } -func extParsePropGoTypeSkipOptionalPointer(extPropValue interface{}) (bool, error) { - goTypeSkipOptionalPointer, ok := extPropValue.(bool) - if !ok { - return false, fmt.Errorf("failed to convert type: %T", extPropValue) - } - return goTypeSkipOptionalPointer, nil -} - func extParseGoFieldName(extPropValue interface{}) (string, error) { return extString(extPropValue) } diff --git a/pkg/codegen/extension_test.go b/pkg/codegen/extension_test.go index 7a5f363bd..1d5a21563 100644 --- a/pkg/codegen/extension_test.go +++ b/pkg/codegen/extension_test.go @@ -54,57 +54,3 @@ func Test_extTypeName(t *testing.T) { }) } } - -func Test_extParsePropGoTypeSkipOptionalPointer(t *testing.T) { - type args struct { - extPropValue json.RawMessage - } - tests := []struct { - name string - args args - want bool - wantErr bool - }{ - { - name: "success when set to true", - args: args{json.RawMessage(`true`)}, - want: true, - wantErr: false, - }, - { - name: "success when set to false", - args: args{json.RawMessage(`false`)}, - want: false, - wantErr: false, - }, - { - name: "nil conversion error", - args: args{nil}, - want: false, - wantErr: true, - }, - { - name: "type conversion error", - args: args{json.RawMessage(`"true"`)}, - want: false, - wantErr: true, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - // kin-openapi no longer returns these as RawMessage - var extPropValue interface{} - if tt.args.extPropValue != nil { - err := json.Unmarshal(tt.args.extPropValue, &extPropValue) - assert.NoError(t, err) - } - got, err := extParsePropGoTypeSkipOptionalPointer(extPropValue) - if tt.wantErr { - assert.Error(t, err) - return - } - assert.NoError(t, err) - assert.Equal(t, tt.want, got) - }) - } -} diff --git a/pkg/codegen/inline.go b/pkg/codegen/inline.go index 459255c05..e722337fa 100644 --- a/pkg/codegen/inline.go +++ b/pkg/codegen/inline.go @@ -32,22 +32,22 @@ func GenerateInlinedSpec(t *template.Template, importMapping importMap, swagger // Marshal to json encoded, err := swagger.MarshalJSON() if err != nil { - return "", fmt.Errorf("error marshaling swagger: %w", err) + return "", fmt.Errorf("error marshaling swagger: %s", err) } // gzip var buf bytes.Buffer zw, err := gzip.NewWriterLevel(&buf, gzip.BestCompression) if err != nil { - return "", fmt.Errorf("error creating gzip compressor: %w", err) + return "", fmt.Errorf("error creating gzip compressor: %s", err) } _, err = zw.Write(encoded) if err != nil { - return "", fmt.Errorf("error gzipping swagger file: %w", err) + return "", fmt.Errorf("error gzipping swagger file: %s", err) } err = zw.Close() if err != nil { - return "", fmt.Errorf("error gzipping swagger file: %w", err) + return "", fmt.Errorf("error gzipping swagger file: %s", err) } str := base64.StdEncoding.EncodeToString(buf.Bytes()) diff --git a/pkg/codegen/operations.go b/pkg/codegen/operations.go index 29127b3d3..c802b535a 100644 --- a/pkg/codegen/operations.go +++ b/pkg/codegen/operations.go @@ -323,8 +323,8 @@ func (o *OperationDefinition) GetResponseTypeDefinitions() ([]ResponseTypeDefini ResponseName: responseName, ContentTypeName: contentTypeName, } - if IsGoTypeReference(responseRef.Ref) { - refType, err := RefPathToGoType(responseRef.Ref) + if IsGoTypeReference(contentType.Schema.Ref) { + refType, err := RefPathToGoType(contentType.Schema.Ref) if err != nil { return nil, fmt.Errorf("error dereferencing response Ref: %w", err) } @@ -398,15 +398,7 @@ func (r RequestBodyDefinition) Suffix() string { // IsSupportedByClient returns true if we support this content type for client. Otherwise only generic method will ge generated func (r RequestBodyDefinition) IsSupportedByClient() bool { - return r.IsJSON() || r.NameTag == "Formdata" || r.NameTag == "Text" -} - -// IsJSON returns whether this is a JSON media type, for instance: -// - application/json -// - application/vnd.api+json -// - application/*+json -func (r RequestBodyDefinition) IsJSON() bool { - return util.IsMediaTypeJson(r.ContentType) + return r.NameTag == "JSON" || r.NameTag == "Formdata" || r.NameTag == "Text" } // IsSupported returns true if we support this content type for server. Otherwise io.Reader will be generated @@ -482,14 +474,6 @@ func (r ResponseContentDefinition) NameTagOrContentType() string { return SchemaNameToTypeName(r.ContentType) } -// IsJSON returns whether this is a JSON media type, for instance: -// - application/json -// - application/vnd.api+json -// - application/*+json -func (r ResponseContentDefinition) IsJSON() bool { - return util.IsMediaTypeJson(r.ContentType) -} - type ResponseHeaderDefinition struct { Name string GoName string @@ -658,11 +642,9 @@ func GenerateBodyDefinitions(operationID string, bodyOrRef *openapi3.RequestBody var defaultBody bool switch { - case contentType == "application/json": + case util.IsMediaTypeJson(contentType): tag = "JSON" defaultBody = true - case util.IsMediaTypeJson(contentType): - tag = mediaTypeToCamelCase(contentType) case strings.HasPrefix(contentType, "multipart/"): tag = "Multipart" case contentType == "application/x-www-form-urlencoded": @@ -760,10 +742,8 @@ func GenerateResponseDefinitions(operationID string, responses openapi3.Response content := response.Content[contentType] var tag string switch { - case contentType == "application/json": - tag = "JSON" case util.IsMediaTypeJson(contentType): - tag = mediaTypeToCamelCase(contentType) + tag = "JSON" case contentType == "application/x-www-form-urlencoded": tag = "Formdata" case strings.HasPrefix(contentType, "multipart/"): @@ -933,19 +913,19 @@ func GenerateTypesForOperations(t *template.Template, ops []OperationDefinition) return buf.String(), nil } -// GenerateChiServer generates all the go code for the ServerInterface as well as +// GenerateChiServer This function generates all the go code for the ServerInterface as well as // all the wrapper functions around our handlers. func GenerateChiServer(t *template.Template, operations []OperationDefinition) (string, error) { return GenerateTemplates([]string{"chi/chi-interface.tmpl", "chi/chi-middleware.tmpl", "chi/chi-handler.tmpl"}, t, operations) } -// GenerateFiberServer generates all the go code for the ServerInterface as well as +// GenerateFiberServer This function generates all the go code for the ServerInterface as well as // all the wrapper functions around our handlers. func GenerateFiberServer(t *template.Template, operations []OperationDefinition) (string, error) { return GenerateTemplates([]string{"fiber/fiber-interface.tmpl", "fiber/fiber-middleware.tmpl", "fiber/fiber-handler.tmpl"}, t, operations) } -// GenerateEchoServer generates all the go code for the ServerInterface as well as +// GenerateEchoServer This function generates all the go code for the ServerInterface as well as // all the wrapper functions around our handlers. func GenerateEchoServer(t *template.Template, operations []OperationDefinition) (string, error) { return GenerateTemplates([]string{"echo/echo-interface.tmpl", "echo/echo-wrappers.tmpl", "echo/echo-register.tmpl"}, t, operations) diff --git a/pkg/codegen/schema.go b/pkg/codegen/schema.go index 1b784fb66..b811e7d1b 100644 --- a/pkg/codegen/schema.go +++ b/pkg/codegen/schema.go @@ -276,16 +276,6 @@ func GenerateGoSchema(sref *openapi3.SchemaRef, path []string) (Schema, error) { return outSchema, nil } - // Check x-go-type-skip-optional-pointer, which will override if the type - // should be a pointer or not when the field is optional. - if extension, ok := schema.Extensions[extPropGoTypeSkipOptionalPointer]; ok { - skipOptionalPointer, err := extParsePropGoTypeSkipOptionalPointer(extension) - if err != nil { - return outSchema, fmt.Errorf("invalid value for %q: %w", extPropGoTypeSkipOptionalPointer, err) - } - outSchema.SkipOptionalPointer = skipOptionalPointer - } - // Schema type and format, eg. string / binary t := schema.Type // Handle objects and empty schemas first as a special case @@ -671,14 +661,6 @@ func GenFieldsFromProperties(props []Property) []string { field += fmt.Sprintf("%s\n", DeprecationComment(deprecationReason)) } - // Check x-go-type-skip-optional-pointer, which will override if the type - // should be a pointer or not when the field is optional. - if extension, ok := p.Extensions[extPropGoTypeSkipOptionalPointer]; ok { - if skipOptionalPointer, err := extParsePropGoTypeSkipOptionalPointer(extension); err == nil { - p.Schema.SkipOptionalPointer = skipOptionalPointer - } - } - field += fmt.Sprintf(" %s %s", goFieldName, p.GoTypeDef()) omitEmpty := !p.Nullable && diff --git a/pkg/codegen/template_helpers.go b/pkg/codegen/template_helpers.go index 3f1c1f262..dfaca18db 100644 --- a/pkg/codegen/template_helpers.go +++ b/pkg/codegen/template_helpers.go @@ -44,7 +44,7 @@ var ( titleCaser = cases.Title(language.English) ) -// genParamArgs takes an array of Parameter definition, and generates a valid +// This function takes an array of Parameter definition, and generates a valid // Go parameter declaration from them, eg: // ", foo int, bar string, baz float32". The preceding comma is there to save // a lot of work in the template engine. @@ -60,7 +60,7 @@ func genParamArgs(params []ParameterDefinition) string { return ", " + strings.Join(parts, ", ") } -// genParamTypes is much like the one above, except it only produces the +// This function is much like the one above, except it only produces the // types of the parameters for a type declaration. It would produce this // from the same input as above: // ", int, string, float32". diff --git a/pkg/codegen/templates/chi/chi-interface.tmpl b/pkg/codegen/templates/chi/chi-interface.tmpl index cfc393bde..79a51fd75 100644 --- a/pkg/codegen/templates/chi/chi-interface.tmpl +++ b/pkg/codegen/templates/chi/chi-interface.tmpl @@ -5,13 +5,3 @@ type ServerInterface interface { {{.OperationId}}(w http.ResponseWriter, r *http.Request{{genParamArgs .PathParams}}{{if .RequiresParamObject}}, params {{.OperationId}}Params{{end}}) {{end}} } - -// Unimplemented server implementation that returns http.StatusNotImplemented for each endpoint. - -type Unimplemented struct {} - {{range .}}{{.SummaryAsComment }} - // ({{.Method}} {{.Path}}) - func (_ Unimplemented) {{.OperationId}}(w http.ResponseWriter, r *http.Request{{genParamArgs .PathParams}}{{if .RequiresParamObject}}, params {{.OperationId}}Params{{end}}) { - w.WriteHeader(http.StatusNotImplemented) - } - {{end}} \ No newline at end of file diff --git a/pkg/codegen/templates/chi/chi-middleware.tmpl b/pkg/codegen/templates/chi/chi-middleware.tmpl index 313122a36..33b89c869 100644 --- a/pkg/codegen/templates/chi/chi-middleware.tmpl +++ b/pkg/codegen/templates/chi/chi-middleware.tmpl @@ -173,9 +173,9 @@ func (siw *ServerInterfaceWrapper) {{$opid}}(w http.ResponseWriter, r *http.Requ {{end}} {{end}} - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var handler http.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { siw.Handler.{{.OperationId}}(w, r{{genParamNames .PathParams}}{{if .RequiresParamObject}}, params{{end}}) - })) + }) {{if opts.Compatibility.ApplyChiMiddlewareFirstToLast}} for i := len(siw.HandlerMiddlewares) -1; i >= 0; i-- { diff --git a/pkg/codegen/templates/client-with-responses.tmpl b/pkg/codegen/templates/client-with-responses.tmpl index c0b3ca568..a3fd2b6dd 100644 --- a/pkg/codegen/templates/client-with-responses.tmpl +++ b/pkg/codegen/templates/client-with-responses.tmpl @@ -33,7 +33,7 @@ type ClientWithResponsesInterface interface { {{$hasParams := .RequiresParamObject -}} {{$pathParams := .PathParams -}} {{$opid := .OperationId -}} - // {{$opid}}{{if .HasBody}}WithBody{{end}}WithResponse request{{if .HasBody}} with any body{{end}} + // {{$opid}} request{{if .HasBody}} with any body{{end}} {{$opid}}{{if .HasBody}}WithBody{{end}}WithResponse(ctx context.Context{{genParamArgs .PathParams}}{{if .RequiresParamObject}}, params *{{$opid}}Params{{end}}{{if .HasBody}}, contentType string, body io.Reader{{end}}, reqEditors... RequestEditorFn) (*{{genResponseTypeName $opid}}, error) {{range .Bodies}} {{if .IsSupportedByClient -}} diff --git a/pkg/codegen/templates/client.tmpl b/pkg/codegen/templates/client.tmpl index 10ee5644d..2dabe66d8 100644 --- a/pkg/codegen/templates/client.tmpl +++ b/pkg/codegen/templates/client.tmpl @@ -77,7 +77,7 @@ type ClientInterface interface { {{$hasParams := .RequiresParamObject -}} {{$pathParams := .PathParams -}} {{$opid := .OperationId -}} - // {{$opid}}{{if .HasBody}}WithBody{{end}} request{{if .HasBody}} with any body{{end}} + // {{$opid}} request{{if .HasBody}} with any body{{end}} {{$opid}}{{if .HasBody}}WithBody{{end}}(ctx context.Context{{genParamArgs $pathParams}}{{if $hasParams}}, params *{{$opid}}Params{{end}}{{if .HasBody}}, contentType string, body io.Reader{{end}}, reqEditors... RequestEditorFn) (*http.Response, error) {{range .Bodies}} {{if .IsSupportedByClient -}} @@ -135,7 +135,7 @@ func (c *{{ $clientTypeName }}) {{$opid}}{{.Suffix}}(ctx context.Context{{genPar // New{{$opid}}Request{{.Suffix}} calls the generic {{$opid}} builder with {{.ContentType}} body func New{{$opid}}Request{{.Suffix}}(server string{{genParamArgs $pathParams}}{{if $hasParams}}, params *{{$opid}}Params{{end}}, body {{$opid}}{{.NameTag}}RequestBody) (*http.Request, error) { var bodyReader io.Reader - {{if .IsJSON -}} + {{if eq .NameTag "JSON" -}} buf, err := json.Marshal(body) if err != nil { return nil, err diff --git a/pkg/codegen/templates/fiber/fiber-middleware.tmpl b/pkg/codegen/templates/fiber/fiber-middleware.tmpl index ad3160d73..fd8d00dc1 100644 --- a/pkg/codegen/templates/fiber/fiber-middleware.tmpl +++ b/pkg/codegen/templates/fiber/fiber-middleware.tmpl @@ -23,7 +23,7 @@ func (siw *ServerInterfaceWrapper) {{$opid}}(c *fiber.Ctx) error { {{if .IsJson}} err = json.Unmarshal([]byte(c.Query("{{.ParamName}}")), &{{$varName}}) if err != nil { - return fiber.NewError(fiber.StatusBadRequest, fmt.Errorf("Error unmarshaling parameter '{{.ParamName}}' as JSON: %w", err).Error()) + return fiber.NewError(fiber.StatusBadRequest, fmt.Errorf("Error unmarshalling parameter '{{.ParamName}}' as JSON: %w", err).Error()) } {{end}} {{if .IsStyled}} @@ -66,7 +66,7 @@ func (siw *ServerInterfaceWrapper) {{$opid}}(c *fiber.Ctx) error { var value {{.TypeDef}} err = json.Unmarshal([]byte(paramValue), &value) if err != nil { - return fiber.NewError(fiber.StatusBadRequest, fmt.Errorf("Error unmarshaling parameter '{{.ParamName}}' as JSON: %w", err).Error()) + return fiber.NewError(fiber.StatusBadRequest, fmt.Errorf("Error unmarshalling parameter '{{.ParamName}}' as JSON: %w", err).Error()) } params.{{.GoName}} = {{if not .Required}}&{{end}}value @@ -99,7 +99,7 @@ func (siw *ServerInterfaceWrapper) {{$opid}}(c *fiber.Ctx) error { {{if .IsJson}} err = json.Unmarshal([]byte(value), &{{.GoName}}) if err != nil { - return fiber.NewError(fiber.StatusBadRequest, fmt.Errorf("Error unmarshaling parameter '{{.ParamName}}' as JSON: %w", err).Error()) + return fiber.NewError(fiber.StatusBadRequest, fmt.Errorf("Error unmarshalling parameter '{{.ParamName}}' as JSON: %w", err).Error()) } {{end}} @@ -139,7 +139,7 @@ func (siw *ServerInterfaceWrapper) {{$opid}}(c *fiber.Ctx) error { err = json.Unmarshal([]byte(decoded), &value) if err != nil { - return fiber.NewError(fiber.StatusBadRequest, fmt.Errorf("Error unmarshaling parameter '{{.ParamName}}' as JSON: %w", err).Error()) + return fiber.NewError(fiber.StatusBadRequest, fmt.Errorf("Error unmarshalling parameter '{{.ParamName}}' as JSON: %w", err).Error()) } params.{{.GoName}} = {{if not .Required}}&{{end}}value diff --git a/pkg/codegen/templates/gin/gin-wrappers.tmpl b/pkg/codegen/templates/gin/gin-wrappers.tmpl index b7332b3c3..d1ac19453 100644 --- a/pkg/codegen/templates/gin/gin-wrappers.tmpl +++ b/pkg/codegen/templates/gin/gin-wrappers.tmpl @@ -32,7 +32,7 @@ func (siw *ServerInterfaceWrapper) {{$opid}}(c *gin.Context) { {{if .IsStyled}} err = runtime.BindStyledParameter("{{.Style}}",{{.Explode}}, "{{.ParamName}}", c.Param("{{.ParamName}}"), &{{$varName}}) if err != nil { - siw.ErrorHandler(c, fmt.Errorf("Invalid format for parameter {{.ParamName}}: %w", err), http.StatusBadRequest) + siw.ErrorHandler(c, fmt.Errorf("Invalid format for parameter {{.ParamName}}: %s", err), http.StatusBadRequest) return } {{end}} @@ -62,7 +62,7 @@ func (siw *ServerInterfaceWrapper) {{$opid}}(c *gin.Context) { var value {{.TypeDef}} err = json.Unmarshal([]byte(paramValue), &value) if err != nil { - siw.ErrorHandler(c, fmt.Errorf("Error unmarshaling parameter '{{.ParamName}}' as JSON: %w", err), http.StatusBadRequest) + siw.ErrorHandler(c, fmt.Errorf("Error unmarshaling parameter '{{.ParamName}}' as JSON: %s", err), http.StatusBadRequest) return } @@ -77,7 +77,7 @@ func (siw *ServerInterfaceWrapper) {{$opid}}(c *gin.Context) { {{if .IsStyled}} err = runtime.BindQueryParameter("{{.Style}}", {{.Explode}}, {{.Required}}, "{{.ParamName}}", c.Request.URL.Query(), ¶ms.{{.GoName}}) if err != nil { - siw.ErrorHandler(c, fmt.Errorf("Invalid format for parameter {{.ParamName}}: %w", err), http.StatusBadRequest) + siw.ErrorHandler(c, fmt.Errorf("Invalid format for parameter {{.ParamName}}: %s", err), http.StatusBadRequest) return } {{end}} @@ -110,7 +110,7 @@ func (siw *ServerInterfaceWrapper) {{$opid}}(c *gin.Context) { {{if .IsStyled}} err = runtime.BindStyledParameterWithLocation("{{.Style}}",{{.Explode}}, "{{.ParamName}}", runtime.ParamLocationHeader, valueList[0], &{{.GoName}}) if err != nil { - siw.ErrorHandler(c, fmt.Errorf("Invalid format for parameter {{.ParamName}}: %w", err), http.StatusBadRequest) + siw.ErrorHandler(c, fmt.Errorf("Invalid format for parameter {{.ParamName}}: %s", err), http.StatusBadRequest) return } {{end}} @@ -157,7 +157,7 @@ func (siw *ServerInterfaceWrapper) {{$opid}}(c *gin.Context) { var value {{.TypeDef}} err = runtime.BindStyledParameter("simple",{{.Explode}}, "{{.ParamName}}", cookie, &value) if err != nil { - siw.ErrorHandler(c, fmt.Errorf("Invalid format for parameter {{.ParamName}}: %w", err), http.StatusBadRequest) + siw.ErrorHandler(c, fmt.Errorf("Invalid format for parameter {{.ParamName}}: %s", err), http.StatusBadRequest) return } params.{{.GoName}} = {{if not .Required}}&{{end}}value diff --git a/pkg/codegen/templates/gorilla/gorilla-middleware.tmpl b/pkg/codegen/templates/gorilla/gorilla-middleware.tmpl index 468ed5dd2..0e0a5e17c 100644 --- a/pkg/codegen/templates/gorilla/gorilla-middleware.tmpl +++ b/pkg/codegen/templates/gorilla/gorilla-middleware.tmpl @@ -5,7 +5,7 @@ type ServerInterfaceWrapper struct { ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) } -type MiddlewareFunc func(http.HandlerFunc) http.HandlerFunc +type MiddlewareFunc func(http.Handler) http.Handler {{range .}}{{$opid := .OperationId}} @@ -173,9 +173,9 @@ func (siw *ServerInterfaceWrapper) {{$opid}}(w http.ResponseWriter, r *http.Requ {{end}} {{end}} - handler := func(w http.ResponseWriter, r *http.Request) { + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { siw.Handler.{{.OperationId}}(w, r{{genParamNames .PathParams}}{{if .RequiresParamObject}}, params{{end}}) -} + })) {{if opts.Compatibility.ApplyGorillaMiddlewareFirstToLast}} for i := len(siw.HandlerMiddlewares) -1; i >= 0; i-- { @@ -187,7 +187,7 @@ func (siw *ServerInterfaceWrapper) {{$opid}}(w http.ResponseWriter, r *http.Requ } {{end}} - handler(w, r.WithContext(ctx)) + handler.ServeHTTP(w, r.WithContext(ctx)) } {{end}} diff --git a/pkg/codegen/templates/inline.tmpl b/pkg/codegen/templates/inline.tmpl index 012412156..106a42b24 100644 --- a/pkg/codegen/templates/inline.tmpl +++ b/pkg/codegen/templates/inline.tmpl @@ -9,16 +9,16 @@ var swaggerSpec = []string{ 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) + return nil, fmt.Errorf("error base64 decoding spec: %s", err) } zr, err := gzip.NewReader(bytes.NewReader(zipped)) if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) + return nil, fmt.Errorf("error decompressing spec: %s", err) } var buf bytes.Buffer _, err = buf.ReadFrom(zr) if err != nil { - return nil, fmt.Errorf("error decompressing spec: %w", err) + return nil, fmt.Errorf("error decompressing spec: %s", err) } return buf.Bytes(), nil @@ -36,7 +36,7 @@ func decodeSpecCached() func() ([]byte, error) { // 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)) + var res = make(map[string]func() ([]byte, error)) if len(pathToFile) > 0 { res[pathToFile] = rawSpec } @@ -60,12 +60,12 @@ func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { // 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("") + var resolvePath = PathToRawSpec("") loader := openapi3.NewLoader() loader.IsExternalRefsAllowed = true loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { - pathToFile := url.String() + var pathToFile = url.String() pathToFile = path.Clean(pathToFile) getSpec, ok := resolvePath[pathToFile] if !ok { diff --git a/pkg/codegen/templates/strict/strict-echo.tmpl b/pkg/codegen/templates/strict/strict-echo.tmpl index 717d32654..86def37a3 100644 --- a/pkg/codegen/templates/strict/strict-echo.tmpl +++ b/pkg/codegen/templates/strict/strict-echo.tmpl @@ -31,7 +31,7 @@ type strictHandler struct { {{$multipleBodies := gt (len .Bodies) 1 -}} {{range .Bodies -}} {{if $multipleBodies}}if strings.HasPrefix(ctx.Request().Header.Get("Content-Type"), "{{.ContentType}}") { {{end}} - {{if .IsJSON -}} + {{if eq .NameTag "JSON" -}} var body {{$opid}}{{.NameTag}}RequestBody if err := ctx.Bind(&body); err != nil { return err diff --git a/pkg/codegen/templates/strict/strict-fiber-interface.tmpl b/pkg/codegen/templates/strict/strict-fiber-interface.tmpl index ae00ea5d1..3b1470979 100644 --- a/pkg/codegen/templates/strict/strict-fiber-interface.tmpl +++ b/pkg/codegen/templates/strict/strict-fiber-interface.tmpl @@ -78,7 +78,7 @@ {{end -}} ctx.Status({{if $fixedStatusCode}}{{$statusCode}}{{else}}response.StatusCode{{end}}) {{$hasBodyVar := or ($hasHeaders) (not $fixedStatusCode) (not .IsSupported)}} - {{if .IsJSON }} + {{if eq .NameTag "JSON" -}} {{$hasUnionElements := ne 0 (len .Schema.UnionElements)}} return ctx.JSON(&{{if $hasBodyVar}}response.Body{{else}}response{{end}}{{if $hasUnionElements}}.union{{end}}) {{else if eq .NameTag "Text" -}} diff --git a/pkg/codegen/templates/strict/strict-fiber.tmpl b/pkg/codegen/templates/strict/strict-fiber.tmpl index eeed71bdd..38a819f71 100644 --- a/pkg/codegen/templates/strict/strict-fiber.tmpl +++ b/pkg/codegen/templates/strict/strict-fiber.tmpl @@ -33,7 +33,7 @@ type strictHandler struct { {{$multipleBodies := gt (len .Bodies) 1 -}} {{range .Bodies -}} {{if $multipleBodies}}if strings.HasPrefix(string(ctx.Request().Header.ContentType()), "{{.ContentType}}") { {{end}} - {{if .IsJSON }} + {{if eq .NameTag "JSON" -}} var body {{$opid}}{{.NameTag}}RequestBody if err := ctx.BodyParser(&body); err != nil { return fiber.NewError(fiber.StatusBadRequest, err.Error()) diff --git a/pkg/codegen/templates/strict/strict-gin.tmpl b/pkg/codegen/templates/strict/strict-gin.tmpl index d02dfbc60..0c36f40ee 100644 --- a/pkg/codegen/templates/strict/strict-gin.tmpl +++ b/pkg/codegen/templates/strict/strict-gin.tmpl @@ -31,7 +31,7 @@ type strictHandler struct { {{$multipleBodies := gt (len .Bodies) 1 -}} {{range .Bodies -}} {{if $multipleBodies}}if strings.HasPrefix(ctx.GetHeader("Content-Type"), "{{.ContentType}}") { {{end}} - {{if .IsJSON }} + {{if eq .NameTag "JSON" -}} var body {{$opid}}{{.NameTag}}RequestBody if err := ctx.ShouldBind(&body); err != nil { ctx.Status(http.StatusBadRequest) diff --git a/pkg/codegen/templates/strict/strict-http.tmpl b/pkg/codegen/templates/strict/strict-http.tmpl index 8579655d8..b16ed1d39 100644 --- a/pkg/codegen/templates/strict/strict-http.tmpl +++ b/pkg/codegen/templates/strict/strict-http.tmpl @@ -48,7 +48,7 @@ type strictHandler struct { {{$multipleBodies := gt (len .Bodies) 1 -}} {{range .Bodies -}} {{if $multipleBodies}}if strings.HasPrefix(r.Header.Get("Content-Type"), "{{.ContentType}}") { {{end}} - {{if .IsJSON }} + {{if eq .NameTag "JSON" -}} var body {{$opid}}{{.NameTag}}RequestBody if err := json.NewDecoder(r.Body).Decode(&body); err != nil { sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't decode JSON body: %w", err)) diff --git a/pkg/codegen/templates/strict/strict-interface.tmpl b/pkg/codegen/templates/strict/strict-interface.tmpl index 4b6a9b1a7..c3ed5aa8c 100644 --- a/pkg/codegen/templates/strict/strict-interface.tmpl +++ b/pkg/codegen/templates/strict/strict-interface.tmpl @@ -38,9 +38,7 @@ {{range .Contents}} {{$receiverTypeName := printf "%s%s%s%s" $opid $statusCode .NameTagOrContentType "Response"}} - {{if eq .NameTag "Text" -}} - type {{$receiverTypeName}} string - {{else if and $fixedStatusCode $isRef -}} + {{if and $fixedStatusCode $isRef -}} type {{$receiverTypeName}} struct{ {{$ref}}{{.NameTagOrContentType}}Response } {{else if and (not $hasHeaders) ($fixedStatusCode) (.IsSupported) -}} type {{$receiverTypeName}} {{if eq .NameTag "Multipart"}}func(writer *multipart.Writer)error{{else if .IsSupported}}{{if .Schema.IsRef}}={{end}} {{.Schema.TypeDecl}}{{else}}io.Reader{{end}} @@ -66,6 +64,9 @@ {{end}} func (response {{$receiverTypeName}}) Visit{{$opid}}Response(w http.ResponseWriter) error { + {{range $headers -}} + w.Header().Set("{{.Name}}", fmt.Sprint(response.Headers.{{.GoName}})) + {{end -}} {{if eq .NameTag "Multipart" -}} writer := multipart.NewWriter(w) {{end -}} @@ -75,12 +76,9 @@ w.Header().Set("Content-Length", fmt.Sprint(response.ContentLength)) } {{end -}} - {{range $headers -}} - w.Header().Set("{{.Name}}", fmt.Sprint(response.Headers.{{.GoName}})) - {{end -}} w.WriteHeader({{if $fixedStatusCode}}{{$statusCode}}{{else}}response.StatusCode{{end}}) {{$hasBodyVar := or ($hasHeaders) (not $fixedStatusCode) (not .IsSupported)}} - {{if .IsJSON -}} + {{if eq .NameTag "JSON" -}} {{$hasUnionElements := ne 0 (len .Schema.UnionElements)}} return json.NewEncoder(w).Encode(response{{if $hasBodyVar}}.Body{{end}}{{if $hasUnionElements}}.union{{end}}) {{else if eq .NameTag "Text" -}} diff --git a/pkg/codegen/test_specs/x-go-type-skip-optional-pointer.yaml b/pkg/codegen/test_specs/x-go-type-skip-optional-pointer.yaml deleted file mode 100644 index 404eaca78..000000000 --- a/pkg/codegen/test_specs/x-go-type-skip-optional-pointer.yaml +++ /dev/null @@ -1,54 +0,0 @@ -openapi: "3.0.0" -info: - version: 1.0.0 - title: Example with x-go-type-skip-optional-pointer -paths: - /check: - get: - summary: Return example - responses: - '200': - description: Ok - content: - application/json: - schema: - required: - - requiredField - properties: - # Optional field where the type is a pointer to a string, and - # the x-go-type-skip-optional-pointer is not set. - optionalField: - type: string - # Optional field where the type is a pointer to a string, and - # the x-go-type-skip-optional-pointer is set to false. - optionalFieldSkipFalse: - type: string - x-go-type-skip-optional-pointer: false - # Optional field where the type is a pointer to a string, and - # the x-go-type-skip-optional-pointer is set to true. - optionalFieldSkipTrue: - type: string - x-go-type-skip-optional-pointer: true - # Optional field where the type is a pointer to a string, and - # the x-go-type-skip-optional-pointer is set to true. - customTypeWithSkipTrue: - type: string - x-go-type: string - x-go-type-skip-optional-pointer: true - # Nullable field where the type is a pointer to a string, and - # the x-go-type-skip-optional-pointer is set to false. - nullableFieldSkipFalse: - type: string - nullable: true - x-go-type-skip-optional-pointer: false - # Nullable field where the type is a pointer to a string, and - # the x-go-type-skip-optional-pointer is set to true. - nullableFieldSkipTrue: - type: string - nullable: true - x-go-type-skip-optional-pointer: true - # Check that x-go-type-skip-optional-pointer has no effect on - # required fields. - requiredField: - type: string - x-go-type-skip-optional-pointer: false diff --git a/pkg/codegen/utils.go b/pkg/codegen/utils.go index 79aee7368..cf8826e39 100644 --- a/pkg/codegen/utils.go +++ b/pkg/codegen/utils.go @@ -179,17 +179,6 @@ func replaceInitialism(s string) string { }) } -// mediaTypeToCamelCase converts a media type to a PascalCase representation -func mediaTypeToCamelCase(s string) string { - // ToCamelCase doesn't - and won't - add `/` to the characters it'll allow word boundary - s = strings.Replace(s, "/", "_", 1) - // including a _ to make sure that these are treated as word boundaries by `ToCamelCase` - s = strings.Replace(s, "*", "Wildcard_", 1) - s = strings.Replace(s, "+", "Plus_", 1) - - return ToCamelCaseWithInitialism(s) -} - // SortedSchemaKeys returns the keys of the given SchemaRef dictionary in sorted // order, since Golang scrambles dictionary keys func SortedSchemaKeys(dict map[string]*openapi3.SchemaRef) []string { @@ -852,9 +841,6 @@ func renameRequestBody(requestBodyName string, requestBodyRef *openapi3.RequestB // if the schema wasn't found, and it'll only work successfully for schemas // defined within the spec that we parsed. func findSchemaNameByRefPath(refPath string, spec *openapi3.T) (string, error) { - if spec.Components == nil { - return "", nil - } pathElements := strings.Split(refPath, "/") // All local references will have 4 path elements. if len(pathElements) != 4 { diff --git a/pkg/fiber-middleware/oapi_validate.go b/pkg/fiber-middleware/oapi_validate.go index 830cef5bb..ef30dd8f7 100644 --- a/pkg/fiber-middleware/oapi_validate.go +++ b/pkg/fiber-middleware/oapi_validate.go @@ -149,7 +149,7 @@ func ValidateRequestFromContext(c *fiber.Ctx, router routers.Router, options *Op default: // This should never happen today, but if our upstream code changes, // we don't want to crash the server, so handle the unexpected error. - return fmt.Errorf("error validating request: %w", err) + return fmt.Errorf("error validating request: %s", err) } } return nil diff --git a/pkg/gin-middleware/oapi_validate.go b/pkg/gin-middleware/oapi_validate.go index 3be0a9eac..3406134a6 100644 --- a/pkg/gin-middleware/oapi_validate.go +++ b/pkg/gin-middleware/oapi_validate.go @@ -77,7 +77,7 @@ type Options struct { // OapiRequestValidatorWithOptions creates a validator from a swagger object, with validation options func OapiRequestValidatorWithOptions(swagger *openapi3.T, options *Options) gin.HandlerFunc { - if swagger.Servers != nil && (options == nil || !options.SilenceServersWarning) { + if swagger.Servers != nil && (options == nil || options.SilenceServersWarning) { log.Println("WARN: OapiRequestValidatorWithOptions called with an OpenAPI spec that has `Servers` set. This may lead to an HTTP 400 with `no matching operation was found` when sending a valid request, as the validator performs `Host` header validation. If you're expecting `Host` header validation, you can silence this warning by setting `Options.SilenceServersWarning = true`. See https://github.com/deepmap/oapi-codegen/issues/882 for more information.") } @@ -88,18 +88,10 @@ func OapiRequestValidatorWithOptions(swagger *openapi3.T, options *Options) gin. return func(c *gin.Context) { err := ValidateRequestFromContext(c, router, options) if err != nil { - // using errors.Is did not work - if options != nil && options.ErrorHandler != nil && err.Error() == routers.ErrPathNotFound.Error() { - options.ErrorHandler(c, err.Error(), http.StatusNotFound) + if options != nil && options.ErrorHandler != nil { + options.ErrorHandler(c, err.Error(), http.StatusBadRequest) // in case the handler didn't internally call Abort, stop the chain c.Abort() - } else if options != nil && options.ErrorHandler != nil { - options.ErrorHandler(c, err.Error(), http.StatusBadRequest) - // in case the handler didn't internally call Abort, stop the chain - c.Abort() - } else if err.Error() == routers.ErrPathNotFound.Error() { - // note: i am not sure if this is the best way to handle this - c.AbortWithStatusJSON(http.StatusNotFound, gin.H{"error": err.Error()}) } else { // note: i am not sure if this is the best way to handle this c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()}) @@ -165,7 +157,7 @@ func ValidateRequestFromContext(c *gin.Context, router routers.Router, options * default: // This should never happen today, but if our upstream code changes, // we don't want to crash the server, so handle the unexpected error. - return fmt.Errorf("error validating request: %w", err) + return fmt.Errorf("error validating request: %s", err) } } return nil diff --git a/pkg/gin-middleware/oapi_validate_test.go b/pkg/gin-middleware/oapi_validate_test.go index 4781d34fd..30ad57fc2 100644 --- a/pkg/gin-middleware/oapi_validate_test.go +++ b/pkg/gin-middleware/oapi_validate_test.go @@ -101,10 +101,10 @@ func TestOapiRequestValidator(t *testing.T) { g.GET("/resource", func(c *gin.Context) { called = true }) - // Let's send the request to the wrong server, this should return 404 + // Let's send the request to the wrong server, this should fail validation { rec := doGet(t, g, "http://not.deepmap.ai/resource") - assert.Equal(t, http.StatusNotFound, rec.Code) + assert.Equal(t, http.StatusBadRequest, rec.Code) assert.False(t, called, "Handler should not have been called") } diff --git a/pkg/middleware/oapi_validate.go b/pkg/middleware/oapi_validate.go index e6852760e..0318d2961 100644 --- a/pkg/middleware/oapi_validate.go +++ b/pkg/middleware/oapi_validate.go @@ -43,12 +43,13 @@ const ( func OapiValidatorFromYamlFile(path string) (echo.MiddlewareFunc, error) { data, err := os.ReadFile(path) if err != nil { - return nil, fmt.Errorf("error reading %s: %w", path, err) + return nil, fmt.Errorf("error reading %s: %s", path, err) } swagger, err := openapi3.NewLoader().LoadFromData(data) if err != nil { - return nil, fmt.Errorf("error parsing %s as Swagger YAML: %w", path, err) + return nil, fmt.Errorf("error parsing %s as Swagger YAML: %s", + path, err) } return OapiRequestValidator(swagger), nil } @@ -79,7 +80,7 @@ type Options struct { // OapiRequestValidatorWithOptions creates a validator from a swagger object, with validation options func OapiRequestValidatorWithOptions(swagger *openapi3.T, options *Options) echo.MiddlewareFunc { - if swagger.Servers != nil && (options == nil || !options.SilenceServersWarning) { + if swagger.Servers != nil && (options == nil || options.SilenceServersWarning) { log.Println("WARN: OapiRequestValidatorWithOptions called with an OpenAPI spec that has `Servers` set. This may lead to an HTTP 400 with `no matching operation was found` when sending a valid request, as the validator performs `Host` header validation. If you're expecting `Host` header validation, you can silence this warning by setting `Options.SilenceServersWarning = true`. See https://github.com/deepmap/oapi-codegen/issues/882 for more information.") } @@ -119,7 +120,7 @@ func ValidateRequestFromContext(ctx echo.Context, router routers.Router, options case *routers.RouteError: // We've got a bad request, the path requested doesn't match // either server, or path, or something. - return echo.NewHTTPError(http.StatusNotFound, e.Reason) + return echo.NewHTTPError(http.StatusBadRequest, e.Reason) default: // This should never happen today, but if our upstream code changes, // we don't want to crash the server, so handle the unexpected error. diff --git a/pkg/middleware/oapi_validate_test.go b/pkg/middleware/oapi_validate_test.go index fe7237e3b..8eb53094a 100644 --- a/pkg/middleware/oapi_validate_test.go +++ b/pkg/middleware/oapi_validate_test.go @@ -102,10 +102,10 @@ func TestOapiRequestValidator(t *testing.T) { called = true return nil }) - // Let's send the request to the wrong server, this should return 404 + // Let's send the request to the wrong server, this should fail validation { rec := doGet(t, e, "http://not.deepmap.ai/resource") - assert.Equal(t, http.StatusNotFound, rec.Code) + assert.Equal(t, http.StatusBadRequest, rec.Code) assert.False(t, called, "Handler should not have been called") } diff --git a/pkg/runtime/bindparam.go b/pkg/runtime/bindparam.go index 231b894bb..13d87066e 100644 --- a/pkg/runtime/bindparam.go +++ b/pkg/runtime/bindparam.go @@ -212,7 +212,7 @@ func bindSplitPartsToDestinationArray(parts []string, dest interface{}) error { for i, p := range parts { err := BindStringToObject(p, newArray.Index(i).Addr().Interface()) if err != nil { - return fmt.Errorf("error setting array element: %w", err) + return fmt.Errorf("error setting array element: %s", err) } } v.Set(newArray) diff --git a/pkg/runtime/bindstring.go b/pkg/runtime/bindstring.go index d1ff1ea2c..e2563950f 100644 --- a/pkg/runtime/bindstring.go +++ b/pkg/runtime/bindstring.go @@ -168,7 +168,7 @@ func BindStringToObject(src string, dst interface{}) error { err = fmt.Errorf("can not bind to destination of type: %s", t.Kind()) } if err != nil { - return fmt.Errorf("error binding string parameter: %w", err) + return fmt.Errorf("error binding string parameter: %s", err) } return nil } diff --git a/pkg/runtime/styleparam.go b/pkg/runtime/styleparam.go index 9c486de6f..06b2e2506 100644 --- a/pkg/runtime/styleparam.go +++ b/pkg/runtime/styleparam.go @@ -463,7 +463,7 @@ func primitiveToString(value interface{}) (string, error) { return output, nil } -// escapeParameterString escapes a parameter value bas on the location of that parameter. +// This function escapes a parameter value bas on the location of that parameter. // Query params and path params need different kinds of escaping, while header // and cookie params seem not to need escaping. func escapeParameterString(value string, paramLocation ParamLocation) string { diff --git a/pkg/testutil/request_helpers.go b/pkg/testutil/request_helpers.go index 91eb2fb45..e0f8c08d2 100644 --- a/pkg/testutil/request_helpers.go +++ b/pkg/testutil/request_helpers.go @@ -123,7 +123,7 @@ func (r *RequestBuilder) WithJsonBody(obj interface{}) *RequestBuilder { var err error r.Body, err = json.Marshal(obj) if err != nil { - r.Error = fmt.Errorf("failed to marshal json object: %w", err) + r.Error = fmt.Errorf("failed to marshal json object: %s", err) } return r.WithJsonContentType() } diff --git a/pkg/testutil/response_handlers.go b/pkg/testutil/response_handlers.go index c436f1965..75089e460 100644 --- a/pkg/testutil/response_handlers.go +++ b/pkg/testutil/response_handlers.go @@ -33,7 +33,7 @@ func getHandler(mime string) ResponseHandler { return knownHandlers[mime] } -// jsonHandler assumes that the response contains JSON and unmarshals it +// This function assumes that the response contains JSON and unmarshals it // into the specified object. func jsonHandler(_ string, r io.Reader, obj interface{}, strict bool) error { d := json.NewDecoder(r) diff --git a/pkg/types/email.go b/pkg/types/email.go index e4a1cbdae..00a4cf6b9 100644 --- a/pkg/types/email.go +++ b/pkg/types/email.go @@ -5,36 +5,23 @@ import ( "errors" ) -// ErrValidationEmail is the sentinel error returned when an email fails validation -var ErrValidationEmail = errors.New("email: failed to pass regex validation") - -// Email represents an email address. -// It is a string type that must pass regex validation before being marshalled -// to JSON or unmarshalled from JSON. type Email string func (e Email) MarshalJSON() ([]byte, error) { if !emailRegex.MatchString(string(e)) { - return nil, ErrValidationEmail + return nil, errors.New("email: failed to pass regex validation") } - return json.Marshal(string(e)) } func (e *Email) UnmarshalJSON(data []byte) error { - if e == nil { - return nil - } - var s string if err := json.Unmarshal(data, &s); err != nil { return err } - - *e = Email(s) if !emailRegex.MatchString(s) { - return ErrValidationEmail + return errors.New("email: failed to pass regex validation") } - + *e = Email(s) return nil } diff --git a/pkg/types/email_test.go b/pkg/types/email_test.go index 736056b17..69fb975f2 100644 --- a/pkg/types/email_test.go +++ b/pkg/types/email_test.go @@ -7,170 +7,25 @@ import ( "github.com/stretchr/testify/assert" ) -func TestEmail_MarshalJSON_Validation(t *testing.T) { - type requiredEmail struct { +func TestEmail_MarshalJSON(t *testing.T) { + testEmail := "gaben@valvesoftware.com" + b := struct { EmailField Email `json:"email"` - } - - testCases := map[string]struct { - email Email - expectedJSON []byte - expectedError error }{ - "it should succeed marshalling a valid email and return valid JSON populated with the email": { - email: Email("validemail@openapicodegen.com"), - expectedJSON: []byte(`{"email":"validemail@openapicodegen.com"}`), - expectedError: nil, - }, - "it should fail marshalling an invalid email and return a validation error": { - email: Email("invalidemail"), - expectedJSON: nil, - expectedError: ErrValidationEmail, - }, - "it should fail marshalling an empty email and return a validation error": { - email: Email(""), - expectedJSON: nil, - expectedError: ErrValidationEmail, - }, - } - - for name, tc := range testCases { - tc := tc - t.Run(name, func(t *testing.T) { - t.Parallel() - - jsonBytes, err := json.Marshal(requiredEmail{EmailField: tc.email}) - - if tc.expectedError != nil { - assert.ErrorIs(t, err, tc.expectedError) - } else { - assert.JSONEq(t, string(tc.expectedJSON), string(jsonBytes)) - } - }) + EmailField: Email(testEmail), } + jsonBytes, err := json.Marshal(b) + assert.NoError(t, err) + assert.JSONEq(t, `{"email":"gaben@valvesoftware.com"}`, string(jsonBytes)) } -func TestEmail_UnmarshalJSON_RequiredEmail_Validation(t *testing.T) { - type requiredEmail struct { +func TestEmail_UnmarshalJSON(t *testing.T) { + testEmail := Email("gaben@valvesoftware.com") + jsonStr := `{"email":"gaben@valvesoftware.com"}` + b := struct { EmailField Email `json:"email"` - } - - requiredEmailTestCases := map[string]struct { - jsonStr string - expectedEmail Email - expectedError error - }{ - "it should succeed validating a valid email during the unmarshal process": { - jsonStr: `{"email":"gaben@valvesoftware.com"}`, - expectedError: nil, - expectedEmail: func() Email { - e := Email("gaben@valvesoftware.com") - return e - }(), - }, - "it should fail validating an invalid email": { - jsonStr: `{"email":"not-an-email"}`, - expectedError: ErrValidationEmail, - expectedEmail: func() Email { - e := Email("not-an-email") - return e - }(), - }, - "it should fail validating an empty email": { - jsonStr: `{"email":""}`, - expectedEmail: func() Email { - e := Email("") - return e - }(), - expectedError: ErrValidationEmail, - }, - "it should fail validating a null email": { - jsonStr: `{"email":null}`, - expectedEmail: func() Email { - e := Email("") - return e - }(), - expectedError: ErrValidationEmail, - }, - } - - for name, tc := range requiredEmailTestCases { - tc := tc - t.Run(name, func(t *testing.T) { - t.Parallel() - - b := requiredEmail{} - err := json.Unmarshal([]byte(tc.jsonStr), &b) - assert.Equal(t, tc.expectedEmail, b.EmailField) - assert.ErrorIs(t, err, tc.expectedError) - }) - } - -} - -func TestEmail_UnmarshalJSON_NullableEmail_Validation(t *testing.T) { - - type nullableEmail struct { - EmailField *Email `json:"email,omitempty"` - } - - nullableEmailTestCases := map[string]struct { - body nullableEmail - jsonStr string - expectedEmail *Email - expectedError error - }{ - "it should succeed validating a valid email during the unmarshal process": { - body: nullableEmail{}, - jsonStr: `{"email":"gaben@valvesoftware.com"}`, - expectedError: nil, - expectedEmail: func() *Email { - e := Email("gaben@valvesoftware.com") - return &e - }(), - }, - "it should fail validating an invalid email": { - body: nullableEmail{}, - jsonStr: `{"email":"not-an-email"}`, - expectedError: ErrValidationEmail, - expectedEmail: func() *Email { - e := Email("not-an-email") - return &e - }(), - }, - "it should fail validating an empty email": { - body: nullableEmail{}, - jsonStr: `{"email":""}`, - expectedError: ErrValidationEmail, - expectedEmail: func() *Email { - e := Email("") - return &e - }(), - }, - "it should succeed validating a null email": { - body: nullableEmail{}, - jsonStr: `{"email":null}`, - expectedEmail: nil, - expectedError: nil, - }, - "it should succeed validating a missing email": { - body: nullableEmail{}, - jsonStr: `{}`, - expectedEmail: nil, - expectedError: nil, - }, - } - - for name, tc := range nullableEmailTestCases { - tc := tc - t.Run(name, func(t *testing.T) { - t.Parallel() - - err := json.Unmarshal([]byte(tc.jsonStr), &tc.body) - assert.Equal(t, tc.expectedEmail, tc.body.EmailField) - if tc.expectedError != nil { - assert.ErrorIs(t, err, tc.expectedError) - } - }) - } + }{} + err := json.Unmarshal([]byte(jsonStr), &b) + assert.NoError(t, err) + assert.Equal(t, testEmail, b.EmailField) } diff --git a/pkg/util/inputmapping.go b/pkg/util/inputmapping.go index 613434a98..7b475dbdd 100644 --- a/pkg/util/inputmapping.go +++ b/pkg/util/inputmapping.go @@ -47,7 +47,7 @@ func ParseCommandLineList(input string) []string { return args } -// splitString splits a string along the specified separator, but it +// This function splits a string along the specified separator, but it // ignores anything between double quotes for splitting. We do simple // inside/outside quote counting. Quotes are not stripped from output. func splitString(s string, sep rune) []string { @@ -73,7 +73,7 @@ func splitString(s string, sep rune) []string { part = "" continue } - part += string(c) + part = part + string(c) } return append(parts, part) }