问题:当使用的结构体为嵌套格式,会提示 recursion detectedcannot find type definition

go
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
type Instance struct {
	metav1.TypeMeta
	Instances       []InstanceItem    `json:"instances" yaml:"instances" form:"instances" binding:"required"`
	ServiceSelector map[string]string `json:"serivce_selector" yaml:"serivce_selector" form:"serivce_selector"`
}

type InstanceItem struct {
	Name         string            `json:"name" yaml:"name" form:"name" binding:"required"`
	PromEndpoint string            `json:"prom_endpoint" yaml:"prom_endpoint" form:"prom_endpoint" binding:"required"`
	Labels       map[string]string `json:"labels" yaml:"labels" form:"labels"`
}

go swagger 注释为

text
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// deleteInstance godoc
// @Summary Remove prometheus instance.
// @Description Remove prometheus instance.
// @Tags Instances
// @Accept json
// @Produce json
// @Param query body instance.Instance false "body"
// @securityDefinitions.apikey BearerAuth
// @Success 200 {object} interface{}
// @Router /ph/v1/instance [DELETE]

执行命令时报错如下:

bash
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
$ swag init -g cmd/ph-server/main.go --output ./docs/  --packageName docs
2024/09/22 19:56:19 Generate swagger docs....
2024/09/22 19:56:19 Generate general API Info, search dir:./
2024/09/22 19:56:19 warning: failed to get package name in dir: ./, error: execute go list command, exit status 1, stdout:, stderr:no Go files in /mnt/d/src/go/work/prometheus-hub
2024/09/22 19:56:19 Generating instance.Instance
2024/09/22 19:56:19 Error parsing type definition 'instance.Instance': : cannot find type definition: metav1.TypeMeta
2024/09/22 19:56:19 Skipping 'instance.Instance', recursion detected.
2024/09/22 19:56:19 Skipping 'instance.Instance', recursion detected.
2024/09/22 19:56:19 Skipping 'instance.Instance', recursion detected.
2024/09/22 19:56:19 Generating target.TargetItem

解决: --parseDependency

bash
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
$ swag init -g cmd/ph-server/main.go --output ./docs/  \
	--packageName docs  \
	--parseDependency --parseInternal
	
2024/09/22 20:20:40 Generate swagger docs....
2024/09/22 20:20:40 Generate general API Info, search dir:./
2024/09/22 20:20:40 warning: failed to get package name in dir: ./, error: execute go list command, exit status 1, stdout:, stderr:no Go files in /mnt/d/src/go/work/prometheus-hub
2024/09/22 20:20:41 warning: failed to evaluate const mProfCycleWrap at /usr/local/go/src/runtime/mprof.go:165:7, reflect: call of reflect.Value.Len on zero Value
2024/09/22 20:20:41 Generating github_com_cylonchau_prometheus-hub_pkg_apis_instance.Instance
2024/09/22 20:20:41 Generating github_com_cylonchau_prometheus-hub_pkg_apis_meta_v1.TypeMeta
2024/09/22 20:20:41 Generating github_com_cylonchau_prometheus-hub_pkg_apis_instance.InstanceItem

Reference

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