swagger-codegen icon indicating copy to clipboard operation
swagger-codegen copied to clipboard

bug: incorrect logic and missing imports in generated Golang client

Open HarikrishnanBalagopal opened this issue 2 years ago • 4 comments

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

HarikrishnanBalagopal avatar May 04 '23 16:05 HarikrishnanBalagopal

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

char0n avatar May 10 '23 08:05 char0n

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

cbrom-huma avatar May 18 '23 09:05 cbrom-huma

This makes the client forget about unmarshalling errors. It's a pretty serious bug, and also trivial to fix.

john8329 avatar Sep 29 '24 08:09 john8329

Meanwhile, for us poor souls trying to fix this illogical world:

    # Fix incorrect swagger logic
    find . -name "api_*.go" | xargs perl -i -pe's/localVarHttpResponse\.StatusCode >= 300/localVarHttpResponse\.StatusCode >= 300 || localVarHttpResponse\.StatusCode == 200/g'

Make sure to run this only from inside the generated folder.

john8329 avatar Sep 29 '24 08:09 john8329