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

5

6

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?

Conclusion answered 29/1, 2021 at 0:49 Comment(0)
E
16

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

swag init --parseDependency --parseInternal
Eusebiaeusebio answered 16/9, 2021 at 7:27 Comment(1)
I tried this for echo, and is working fineMilwaukee
F
8

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

Fealty answered 27/4, 2021 at 13:52 Comment(0)
C
2

For a quick solution, run

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

You can find more about this solution here.

Cheston answered 3/10, 2021 at 15:5 Comment(0)
D
0

swag init --parseDependency true should solve your issue

Doridoria answered 4/5, 2021 at 1:57 Comment(0)
M
0

with swag v1.8.12, you can use full path for a type, replacing any . or / with _.

For example, for type MyStruct defined in github.com/john/project/controller, you can use github_com_john_project_controller.MyStruct

It doesn't work for older swag versions, at least not for v1.8.0

Medicine answered 24/7 at 2:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.