swagger-api / swagger-codegen

swagger-codegen contains a template-driven engine to generate documentation, API clients and server stubs in different languages by parsing your OpenAPI / Swagger definition.
http://swagger.io
Apache License 2.0
16.88k stars 6.03k forks source link

bug: incorrect logic and missing imports in generated Golang client #12142

Open HarikrishnanBalagopal opened 1 year ago

HarikrishnanBalagopal commented 1 year ago

Problem statement

Swagger UI https://editor.swagger.io/ generated some invalid Golang client code and the code has some logical errors.

Steps to reproduce

  1. Go to the Swagger editor https://editor.swagger.io/
  2. Copy paste our OpenAPI V3 spec json https://github.com/konveyor/move2kube-api/blob/a8382d16546ff3da9867357b0787bbb45bb4fcd4/assets/openapi.json
  3. Generate a client for Golang. image
  4. Unpack the archive/zip file and look at the code. Use it as a package in a new project and try to build.

Actual behaviour

$ go run main.go 
# foo.com/b/swagger
swagger/api_project_outputs.go:110:131: undefined: os
swagger/api_project_outputs.go:116:24: undefined: os
swagger/api_project_outputs.go:176:11: undefined: os

The code did not contain an import for os package in api_project_outputs.go and few other files.

        localVarReturnValue *os.File

Also the code contains logical errors like this snippet in api_workspaces.go which checks if the status is >= 300 and also if it is == 200 inside the nested if block.

    if localVarHttpResponse.StatusCode >= 300 {
        newErr := GenericSwaggerError{
            body:  localVarBody,
            error: localVarHttpResponse.Status,
        }
        if localVarHttpResponse.StatusCode == 200 {
            var v []Workspace
            err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type"))
            if err != nil {
                newErr.error = err.Error()
                return localVarReturnValue, localVarHttpResponse, newErr
            }
            newErr.model = v
            return localVarReturnValue, localVarHttpResponse, newErr
        }
        return localVarReturnValue, localVarHttpResponse, newErr
    }

Swagger specification

Open API V3 openapi: 3.0.1

Environment

swagger version: Swagger UI
go version: go version go1.19.2 darwin/amd64 OS: MacOS Ventura 13.3

Related

https://github.com/go-swagger/go-swagger/issues/2939

char0n commented 1 year ago

This issue is https://github.com/swagger-api/swagger-codegen related. Transferring the issue.

cbrom-huma commented 1 year ago

Any update on this? @char0n the issue you linked is not an issue at all.