You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

go-swagger生成API文档时User结构体未被识别的问题求助

使用go-swagger生成API文档时的结构体识别问题

我用go-swagger为Go服务生成API规格文档,执行命令:

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

成功生成基础信息和路由,但遇到三个结构体相关问题:

问题1:User结构体未被正确导入

参考代码(docs/docs.go)

// 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.json片段

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

问题2:User结构体属性未生成

参考代码(internals/database/models/user.go)

// 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.json片段

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

问题3:提示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

补充:路由定义代码

// 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. 导入别名干扰扫描:docs.go中使用别名M导入models包,go-swagger无法正确关联别名对应的结构体类型,导致[]M.User的类型信息丢失。
  2. 未导出嵌套结构体:User中的adress、salary是首字母小写的包私有类型,go-swagger无法扫描未导出类型,进而无法生成这些嵌套结构的属性,最终导致整个User结构体的属性缺失。
  3. 引用关联断裂:前两个问题导致usersResponse的schema未正确关联到User定义,验证时就会提示User未被使用。

具体解决步骤

  1. 移除导入别名:修改docs.go的导入语句,直接引用models包,同时更新结构体字段的引用:
    import (
        "service-users-data/internals/database/models"
    )
    
    // ...
    
    Body []models.User
    // ...
    Body models.GenericError
    
  2. 导出嵌套结构体:将adress、salary改为首字母大写的导出类型,并更新User结构体中的对应字段:
    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"`
    }
    
    // 在User结构体中更新
    Adress            Adress `bson:"adress" json:"adress"`
    Salary            Salary `bson:"salary" json:"salary"`
    
  3. 重新生成并验证:执行命令重新生成文档并验证:
    swagger generate spec -o ./docs/swagger.json --scan-models
    swagger validate docs/swagger.json
    

内容的提问来源于stack exchange,提问作者Corentin TRUFFAUT

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 12:55:23