swaggo / swag

Automatically generate RESTful API documentation with Swagger 2.0 for Go.
MIT License
10.51k stars 1.19k forks source link

x-example for integers gets translated into a string #1596

Open bekabaz opened 1 year ago

bekabaz commented 1 year ago

Describe the bug When setting an example for a path variable via extensions(x-example=1) the resulting Swagger doc contains x-example: "1" even though the parameter is an integer.

To Reproduce Here's an example path param definition:

//  @Param      account_id  path        int                                 true    "The account id to update." minimum(1)  extensions(x-example=1)

Generate the swag docs, and you will find this in the swagger.yaml file:

- description: The account id to update.
        in: path
        minimum: 1
        name: account_id
        required: true
        type: integer
        x-example: "1"

Expected behavior I would expect this output:

- description: The account id to update.
        in: path
        minimum: 1
        name: account_id
        required: true
        type: integer
        x-example: 1

Your swag version 1.8.12

Your go version go1.19.3 linux/amd64

hohobilly commented 1 year ago

I'm interested in improving this but need some insights from maintainers 🙏

Right now all the extensions with key-value style is generated as string, otherwise true

... x-example=1,x-nullable

x-example: "1"
x-nullable: true
... x-example={"key": "value"},x-nullable

x-example: "{\"key\": \"value\"}"
x-nullable: true

I believe it generate everything as string because extension fields can be any types, but we lack the placeholder to declare the syntax.

I think there can be 2 solutions

  1. Only handle a specific field name like x-example automatically, by referring to the schema type For example: with above case, account_id is specified as int. We can convert the x-example value accordingly.
  2. Improve extension syntax to allow type declaration. For example: x-author=John(string),x-example=1(int)

In either ways I can give a try 🙏

takanuva15 commented 1 month ago

Hi, I'm dealing with this exact issue with the x-order extension. My struct has more than 10 fields, so after specifying x-order=0 through x-order=9, I started doing x-order=10, etc. After init though, it immediately put that 10 in 2nd place because it's trying to sort the order by the string value rather than the expected int value lol.

Issue discussing how the x-order extension works: https://github.com/swaggo/swag/issues/715

Please let me know if I can assist. I think the best option would be to check whether the value contains only digits and auto-parse it to int. If not, maybe something simple like x-order=int(1) would be intuitive and straightforward.