Skip to content

'Response' suffix causes duplicated structs #386

Closed

Description

@amanbolat

I have some endpoints in my spec like this one:

  /v1/auth/phone/login:
    post:
      summary: 用手机登陆/注册
      tags:
        - Auth
      operationId: LoginByPhone
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/LoginWithPhoneRequest'
      responses:
        "200":
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/LoginWithPhoneResponse'

If I generate server code it is ok, but when I generate client code oapi-codegen creates structs with Response suffix which causes deduplication of my structs.

Maybe it would be better to make this suffix configurable or change it and other suffix/prefix literals to with _ at the beginning so it would be OperationName_Response?

Initially I wanted to use a custom template, but this suffix is generated by the function.

Activity

  1. amanbolat commented on Jun 20, 2021

    @amanbolat
    Author

    I was able to tackle this issue by replacing genResponseTypeName and genResponsePayload by custom ones and do the generation in code.

    There is my code:

    package main
    
    import (
    	"bytes"
    	_ "embed"
    	"fmt"
    	"github.com/deepmap/oapi-codegen/pkg/codegen"
    	"github.com/getkin/kin-openapi/openapi3"
    	"io/ioutil"
    	"os"
    )
    
    //go:embed client-with-responses.go.tpl
    var clientWithResponsesTpl []byte
    
    //go:embed spec.yaml
    var SpecData []byte
    
    func main() {
    	opts := codegen.Options{
    		GenerateTypes: true,
    		GenerateClient: true,
    		UserTemplates: map[string]string{
    			"client-with-responses.tmpl": string(clientWithResponsesTpl),
    		},
    	}
    
    	loader := openapi3.NewSwaggerLoader()
    	loader.IsExternalRefsAllowed = true
    	swagger, err := loader.LoadSwaggerFromData(SpecData)
    	if err != nil {
    		_, _ = fmt.Fprintf(os.Stderr, "error loading swagger spec\n: %s", err)
    		os.Exit(1)
    	}
    
    	codegen.TemplateFunctions["genResponseTypeName"] = genResponseTypeName
    	codegen.TemplateFunctions["genResponsePayload"] = genResponsePayload
    	code, err := codegen.Generate(swagger, "apiclientv1", opts)
    	if err != nil {
    		_, _ = fmt.Fprintf(os.Stderr, "error generating code: %s\n", err)
    		os.Exit(1)
    	}
    
    	err = ioutil.WriteFile("../gen.go", []byte(code), 0644)
    	if err != nil {
    		_, _ = fmt.Fprintf(os.Stderr, "error writing generated code to file: %s", err)
    		os.Exit(1)
    	}
    }
    
    func genResponseTypeName(operationID string) string {
    	return fmt.Sprintf("%s%s", codegen.UppercaseFirstCharacter(operationID), "_Response")
    }
    
    func genResponsePayload(operationID string) string {
    	var buffer = bytes.NewBufferString("")
    
    	// Here is where we build up a response:
    	fmt.Fprintf(buffer, "&%s{\n", genResponseTypeName(operationID))
    	fmt.Fprintf(buffer, "Body: bodyBytes,\n")
    	fmt.Fprintf(buffer, "HTTPResponse: rsp,\n")
    	fmt.Fprintf(buffer, "}")
    
    	return buffer.String()
    }
  2. migueleliasweb commented on Aug 26, 2021

    @migueleliasweb
    Contributor

    I have the same problem with the docker v1.41 api (I've converted the format to openapi v3 with the official converter).

    curl "https://converter.swagger.io/api/convert?url=https://docs.docker.com/engine/api/v1.41.yaml" -H "Accept: application/yaml" -o v1.41.yaml
    

    This produces many duplicates of all types: structs, consts and even methods.

    I ran the generation with v1.8.2:

    $ oapi-codegen -package openapigen -generate server
    
  3. added a commit that references this issue on Aug 29, 2021
    c0d4b93
  4. ghost closed this as completedin #436on Oct 4, 2021
  5. added 2 commits that reference this issue on Dec 6, 2021
    d5cf64d
    bc864d2
  6. added a commit that references this issue on Jan 16, 2024
    318bc63
  7. added a commit that references this issue on May 31, 2024
    6d84c11
  8. jamietanna commented on May 3, 2025

    @jamietanna
    Member

    For posterity, this still can occur when using the Client generation, i.e.:

    internal/endoflifedate/client/client.gen.go:976:6: ProductResponse redeclared in this block
            internal/endoflifedate/client/client.gen.go:187:6: other declaration of ProductResponse
    internal/endoflifedate/client/client.gen.go:984:7: r.HTTPResponse undefined (type ProductResponse has no field or method HTTPResponse)
    

    From code:

    // ProductReleaseResponse A response containing a release cycle.
    type ProductReleaseResponse struct {
    	// Result Full information about a product release cycle.
    	Result ProductRelease `json:"result"`
    
    	// SchemaVersion Version of this schema.
    	SchemaVersion string `json:"schema_version"`
    }
    
    // ClientWithResponsesInterface is the interface specification for the client with responses above.
    type ClientWithResponsesInterface interface {
    
    	// ProductReleaseWithResponse request
    	ProductReleaseWithResponse(ctx context.Context, product string, release string, reqEditors ...RequestEditorFn) (*ProductReleaseResponse, error)
    }
    
    type ProductReleaseResponse struct {
    	Body         []byte
    	HTTPResponse *http.Response
    	JSON200      *ProductReleaseResponse
    }
    
    // Status returns HTTPResponse.Status
    func (r ProductReleaseResponse) Status() string {
    	if r.HTTPResponse != nil {
    		return r.HTTPResponse.Status
    	}
    	return http.StatusText(0)
    }

    This can be overridden when using output-options.response-type-suffix:

    # yaml-language-server: $schema=https://raw.githubusercontent.com/oapi-codegen/oapi-codegen/v2.4.1/configuration-schema.json
    # ...
    output-options:
      response-type-suffix: Resp

    I'll look at getting this more prominently documented.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions