swaggo / gin-swagger

gin middleware to automatically generate RESTful API documentation with Swagger 2.0.
MIT License
3.76k stars 270 forks source link

How to annotate an enum? #238

Open morremeyer opened 2 years ago

morremeyer commented 2 years ago

Summary

Enums do not seem to work out of the box as with go-swagger

Details

go-swagger supports enums as described in https://github.com/go-swagger/go-swagger/pull/2176:

// swagger:enum Level
type Level string

const (
    LEVEL_1 Level = "ONE"
    LEVEL_2 Level = "TWO"
    LEVEL_3 Level = "THREE"
)

// swagger:model
type Model struct {
    level    Level
}

However, annotating and using a struct and enum as follows does not work with gin-swagger:

// swagger:enum AllocationMode
type AllocationMode string

const (
    AllocateLastMonthBudget AllocationMode = "ALLOCATE_LAST_MONTH_BUDGET"
    AllocateLastMonthSpend  AllocationMode = "ALLOCATE_LAST_MONTH_SPEND"
)

type BudgetAllocationMode struct {
    Mode AllocationMode `json:"mode" example:"ALLOCATE_LAST_MONTH_SPEND"`
}

// @Param       mode     body     BudgetAllocationMode true "Budget"
// @Router      /v1/budgets/{budgetId}/{month}/allocations [post]
// Additional swagger comments left out for brevity
func (co Controller) SetAllocationsMonth(c *gin.Context) {
  // function body omitted for brevity
}

It appears in the generated documentation as

        "controllers.BudgetAllocationMode": {
            "type": "object",
            "properties": {
                "mode": {
                    "type": "string",
                    "example": "ALLOCATE_LAST_MONTH_SPEND"
                }
            }
        },

Expected behaviour

I would expect the documentation to be generated as

        "controllers.BudgetAllocationMode": {
            "type": "object",
            "properties": {
                "mode": {
                    "type": "string",
                    "example": "ALLOCATE_LAST_MONTH_SPEND",
            "enum": [
                "ALLOCATE_LAST_MONTH_SPEND",
                "ALLOCATE_LAST_MONTH_BUDGET"
            ]
                }
            }
        },

Any hints on what I'm doing wrong? Full source is in https://github.com/envelope-zero/backend/blob/d2346e9e3b47a644ca91140f9c301d09288a116a/pkg/controllers/budget.go if you want to check it out.