go-swagger – 类型结构体未生成/找到/导入

huangapple go评论152阅读模式
英文:

go-swagger - Type struct not generated / found / imported

问题

我正在尝试使用go-swagger来生成我的Go服务的规范/文档。

swagger generate spec -o ./docs/swagger.json --scan-models

我能够生成基本信息和路由,但在我的结构体中遇到了一个问题。

这里: User结构体没有被导入

docs/docs.go - github

// Package classification Users' Data API
//
// Documentation for Users' Data API
//
//	Schemes: http
//	BasePath: /v1
//	Version: 0.1.0
//
//	Consumes:
//	- application/json
//
//	Produces:
//	- application/json
//
// swagger:meta
package classification

import (
	M "service-users-data/internals/database/models"
)

// A list of all Users
// swagger:response usersResponse
type productsResponseWrapper struct {
	// All current Users
	// in: body
	Body []M.User
}

// Generic error message returned as a string
// swagger:response errorResponse
type errorResponseWrapper struct {
	// Description of the error
	// in: body
	Body M.GenericError
}

Swagger结果:
docs/swagger.json - github

  "responses": {
    "errorResponse": {
      "description": "Generic error message returned as a string"
    },
    "usersResponse": {
      "description": "A list of all Users",
      "schema": {
        "type": "array",
        "items": {}
      }
    }
  }

这里: User结构体的属性没有生成

models/user.go - github

// User type define user object that will be stored in the DB
// swagger:model User
type User struct {
	// the firstname
	FirstName         string   `bson:"first_name" json:"firstName" validate:"required,max=50"`
	MiddleNames       []string `bson:"middle_names" json:"middleNames"`
	LastName          string   `bson:"last_name" json:"lastName" validate:"required,max=50"`
	Age               uint8    `bson:"age" json:"age" validate:"gte=16,lte=99"`
	Email             string   `bson:"email" json:"email" validate:"required,email"`
	Adress            adress   `bson:"adress" json:"adress"`
	Salary            salary   `bson:"salary" json:"salary"`
	Job               string   `bson:"job" json:"job" validate:"max=50"`
	JoStatus          string   `bson:"job_status" json:"jobStatus" validate:"omitempty,oneof=intern extern"`
	BeginingDate      int      `bson:"begining_date" json:"beginingDate"`
	NextInterviewDate int      `bson:"next_interview_date" json:"nextInterviewDate"`
	LastInterviewDate int      `bson:"last_interview_date" json:"lastInterViewDate"`
	ActivityStatus    string   `bson:"activity_status" json:"activityStatus" validate:"omitempty,oneof=active inactive"`
	CreatedOn         int      `bson:"created_on" json:"-"`
	UpdatedOn         int      `bson:"updated_on" json:"-"`
	DeletedOn         int      `bson:"deleted_on" json:"-"`
}

type adress struct {
	Number   uint16 `bson:"number" json:"number"`
	Street   string `bson:"street" json:"street"`
	City     string `bson:"city" json:"city"`
	Province string `bson:"province" json:"province"`
}

type salary struct {
	AmountYear int    `bson:"amount_year" json:"amountYear"`
	Bonus      string `bson:"bonus" json:"bonus"`
}

Swagger结果: docs/swagger.json - github

  "definitions": {
    "User": {
      "description": "User type define user object that will be stored in the DB",
      "x-go-package": "service-users-data/internals/database/models"
    }
  },

这里: User结构体似乎没有被使用

$ swagger validate docs/swagger.json

2022/12/18 09:07:52
The swagger spec at "docs/swagger.json" is valid against swagger specification 2.0
2022/12/18 09:07:52
The swagger spec at "docs/swagger.json" showed up some valid but possibly unwanted constructs.
2022/12/18 09:07:52 See warnings below:
2022/12/18 09:07:52 - WARNING: definition "#/definitions/User" is not used anywhere

我想了解为什么我的结构体没有被识别/找到/导入?

谢谢你花时间阅读 go-swagger – 类型结构体未生成/找到/导入

编辑:

这里: 路由定义

// Package api regroup all http related files
package api

import (
	"github.com/go-chi/chi"
)

// UserRoutes function attach each route to the right handler
func UserRoutes() *chi.Mux {
	r := chi.NewRouter()

	userH := &UserH{}

	// swagger:route GET /users User listUsers
	// Return a list of all Users
	//
	// responses:
	//	200: usersResponse
	//  500: errorResponse
	//  503: errorResponse
	r.Get("/", userH.GetUsers)
	r.Post("/", userH.CreateUser)

	return r
}
英文:

I'm trying to use go-swagger to generate specs / docs of my Go service

swagger generate spec -o ./docs/swagger.json --scan-models

I'm able to generate basics infos + routes but i encountered an issue with my struct\

Here: User struct is not imported

docs/docs.go - github

// Package classification Users' Data API
//
// Documentation for Users' Data API
//
//	Schemes: http
//	BasePath: /v1
//	Version: 0.1.0
//
//	Consumes:
//	- application/json
//
//	Produces:
//	- application/json
//
// swagger:meta
package classification

import (
	M "service-users-data/internals/database/models"
)

// A list of all Users
// swagger:response usersResponse
type productsResponseWrapper struct {
	// All current Users
	// in: body
	Body []M.User
}

// Generic error message returned as a string
// swagger:response errorResponse
type errorResponseWrapper struct {
	// Description of the error
	// in: body
	Body M.GenericError
}

Swagger result:
docs/swagger.json - github

  "responses": {
    "errorResponse": {
      "description": "Generic error message returned as a string"
    },
    "usersResponse": {
      "description": "A list of all Users",
      "schema": {
        "type": "array",
        "items": {}
      }
    }
  }

Here: User struct properties are not generated

models/user.go - github

// User type define user object that will be stored in the DB
// swagger:model User
type User struct {
	// the firstname
	FirstName         string   `bson:"first_name" json:"firstName" validate:"required,max=50"`
	MiddleNames       []string `bson:"middle_names" json:"middleNames"`
	LastName          string   `bson:"last_name" json:"lastName" validate:"required,max=50"`
	Age               uint8    `bson:"age" json:"age" validate:"gte=16,lte=99"`
	Email             string   `bson:"email" json:"email" validate:"required,email"`
	Adress            adress   `bson:"adress" json:"adress"`
	Salary            salary   `bson:"salary" json:"salary"`
	Job               string   `bson:"job" json:"job" validate:"max=50"`
	JoStatus          string   `bson:"job_status" json:"jobStatus" validate:"omitempty,oneof=intern extern"`
	BeginingDate      int      `bson:"begining_date" json:"beginingDate"`
	NextInterviewDate int      `bson:"next_interview_date" json:"nextInterviewDate"`
	LastInterviewDate int      `bson:"last_interview_date" json:"lastInterViewDate"`
	ActivityStatus    string   `bson:"activity_status" json:"activityStatus" validate:"omitempty,oneof=active inactive"`
	CreatedOn         int      `bson:"created_on" json:"-"`
	UpdatedOn         int      `bson:"updated_on" json:"-"`
	DeletedOn         int      `bson:"deleted_on" json:"-"`
}

type adress struct {
	Number   uint16 `bson:"number" json:"number"`
	Street   string `bson:"street" json:"street"`
	City     string `bson:"city" json:"city"`
	Province string `bson:"province" json:"province"`
}

type salary struct {
	AmountYear int    `bson:"amount_year" json:"amountYear"`
	Bonus      string `bson:"bonus" json:"bonus"`
}

Swagger result: docs/swagger.json - github

  "definitions": {
    "User": {
      "description": "User type define user object that will be stored in the DB",
      "x-go-package": "service-users-data/internals/database/models"
    }
  },

Here: User struct seems to not being used

$ swagger validate docs/swagger.json

2022/12/18 09:07:52
The swagger spec at "docs/swagger.json" is valid against swagger specification 2.0
2022/12/18 09:07:52
The swagger spec at "docs/swagger.json" showed up some valid but possibly unwanted constructs.
2022/12/18 09:07:52 See warnings below:
2022/12/18 09:07:52 - WARNING: definition "#/definitions/User" is not used anywhere

I would like to understand why my struct is not recognized / found / imported ?

Thank you for taking the time to read go-swagger – 类型结构体未生成/找到/导入

Edited:

Here: Route definition

// Package api regroup all http related files
package api

import (
	"github.com/go-chi/chi"
)

// UserRoutes function attach each route to the right handler
func UserRoutes() *chi.Mux {
	r := chi.NewRouter()

	userH := &UserH{}

	// swagger:route GET /users User listUsers
	// Return a list of all Users
	//
	// responses:
	//	200: usersResponse
	//  500: errorResponse
	//  503: errorResponse
	r.Get("/", userH.GetUsers)
	r.Post("/", userH.CreateUser)

	return r
}

答案1

得分: 3

我遇到了同样的问题,但成功解决了。
问题与我安装swagger-cli的方式有关。
安装指南页面上,我选择了在静态二进制部分的指导下安装swagger。
我遇到了相同的问题,即模型/结构名称会出现在规范中,但没有捕获到任何结构字段。
我移除了这个cli的安装,并改为按照从源代码安装的指导进行操作。
下次我执行以下命令:
swagger generate spec -o ./docs/swagger.json --scan-models
规范中将包含所有结构字段及其注释,就像我最初期望的那样。

英文:

I had the same issue but managed to resolve it.
The issue had to do with the way I had installed the swagger-cli.
On the installation guide page I had chosen to install swagger using the guidance under the Static binary section.
I was running into the same issue in which the model/struct names would be part of the spec but none of the struct fields would be picked up.
I removed this installation of the cli and instead followed the guidance under Installing from source.
Next time I executed the
swagger generate spec -o ./docs/swagger.json --scan-models
command, the spec included all the struct fields and their annotations as I had originally expected

huangapple
  • 本文由 发表于 2022年12月18日 16:14:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/74839951.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定