How to use a type definition in another file with swaggo?

14.2k Views Asked by At

I am using swaggo generate API document based on godoc syntax.

Source folder and files

|-post
|--controller.go
|--response.go

For this definition:

controller.go

package post

...

// Index godoc
// @Summary Index Post
// @Success 200 {array} []*Response
// @Router /v1/posts [get]
func Index(ctx *gin.Context) {
  ...
}

The Response is been defined in an another file but the same package.

response.go

package post

// Response  is post response body
type Response struct {
    ID   int64  `json:"id"`
    Name string `json:"name"`

    CreatedAt string `json:"created_at"`
    UpdatedAt string `json:"updated_at"`
}

But when run swag init to generate swagger docs, it said:

2021/01/29 09:39:56 Generate swagger docs....
2021/01/29 09:39:56 Generate general API Info, search dir:./
2021/01/29 09:39:56 ParseComment error in file application/post/controller.go :cannot find type definition:

When I move the Response struct to controller.go, it works.

How to import it with godoc or swaggo?

4

There are 4 best solutions below

0
obo On

You need to append --parseDependency to the swag init command.

0
Farouk Salem On

swag init --parseDependency true should solve your issue

1
Lai Lee On

I also encountered this problem, but I solved it with the below command:

swag init --parseDependency --parseInternal
0
The Oracle On

For a quick solution, run

go get -u github.com/swaggo/swag/cmd/[email protected]

You can find more about this solution here.