go-restful-openapi icon indicating copy to clipboard operation
go-restful-openapi copied to clipboard

AllowedValues and default should attempt to set the value according to the data type

Open zmay2030 opened this issue 2 years ago • 1 comments

AllowedValues and DefaultValue(..) should be setting the values according to the data type. Right now, .AllowedValues(...) accepts a map[string]string as the param and the swagger generated is always an enum of strings even if the datatype is boolean or integer.

As for DefaultValue, it accepts a string but it attempts to auto-detect the type despite the data type already being set. So if the DataType is "string" and the default value is set to "1", it will convert it to an integer!

This results in the default value having a different data type than the allowedvalues which is an invalid swagger.

Example 1:

Setting the following:

      .AllowedValues(map[string]string{"0":"0", "1":"1", "2":"2", "3":"3"})
     .DataType("integer")
     .DefaultValue("2")

results in

...
"parameters": [
     {
      "enum": [
       "0",
       "1",
       "3"
      ],
      "type": "integer",
      "default": 1,
      "description": "test",
      "name": "test",
      "in": "query"
     },
...

But what we want is:

...
"parameters": [
     {
      "enum": [
       0,
       1,
       3
      ],
      "type": "integer",
      "default": 1,
      "description": "test",
      "name": "test",
      "in": "query"
     },
...

Example 2:

     .AllowedValues(map[string]string{"true":"true", "false":"false"})
     .DataType("boolean")
     .DefaultValue("true")

Results in

...
"parameters": [
     {
      "enum": [
       "true",
       "false"
      ],
      "type": "integer",
      "default": true,
      "description": "test",
      "name": "test",
      "in": "query"
     },
...

But we want:

...
"parameters": [
     {
      "enum": [
       true,
       false
      ],
      "type": "integer",
      "default": true,
      "description": "test",
      "name": "test",
      "in": "query"
     },
...

zmay2030 avatar Aug 02 '23 16:08 zmay2030

hi, i think relaxing the type of AllowValues argument is possible i.e. from map[string]string to map[string]any. This needs a test though

emicklei avatar Sep 28 '23 20:09 emicklei