swaggo / swag

Automatically generate RESTful API documentation with Swagger 2.0 for Go.
MIT License
10.71k stars 1.2k forks source link

Error while generic type not explicitly declared in code: cannot find type definition #1431

Open yvvq opened 1 year ago

yvvq commented 1 year ago

Describe the bug Got error cannot find type definition, while generic type is not explicitly declared To Reproduce Steps to reproduce the behavior:

// Got a generic function
func NewSvResponse[T interface{}](body T) *SvResponse[T] {
    return &SvResponse[T]{Body: body, Code: "200"}
}

// Got error : cannot find type definition, while model.Enterprise is not explicitly declared in code
// @BasePath /enterprise
// @Summary Create Enterprise
// @Schemes
// @Description Create Enterprise
// @Tags        enterprise
// @Accept      json
// @Produce     json
// @Param       req body     requests.EnterpriseCreateRequest true "req"
// @Success     200 {object} responses.SvResponse[model.Enterprise]
// @Router      /create [post]
func (c *EnterpriseController) Create(ctx *gin.Context) {
         ret := service.BuildEnterprise()  
    ctx.JSON(http.StatusOK, responses.NewSvResponse(ret))
}

//  Everything runs well while model.Enterprise is explicitly declared in code
// @BasePath /enterprise
// @Summary Create Enterprise
// @Schemes
// @Description Create Enterprise
// @Tags        enterprise
// @Accept      json
// @Produce     json
// @Param       req body     requests.EnterpriseCreateRequest true "req"
// @Success     200 {object} responses.SvResponse[model.Enterprise]
// @Router      /create [post]
func (c *EnterpriseController) Create(ctx *gin.Context) {
        ret := service.BuildEnterprise()  
    ctx.JSON(http.StatusOK, responses.NewSvResponse[*model.Enterprise](ret))
}

Expected behavior Generic type should have been parsed correctly

Your swag version 1.8.9

Your go version 1.18.9

Desktop (please complete the following information):

sdghchj commented 1 year ago

If any model from other package is never used in your code and just be used in swagger comments, you have to import that package like:

import (
     _  path/to/your/package
)