emicklei / go-restful-openapi

OpenAPI extension in Go for the go-restful package
MIT License
135 stars 73 forks source link

When a slice of primitive type is used the primitive type is added to the model #64

Closed iainduncani closed 4 years ago

iainduncani commented 4 years ago

Usually primitive types are not added to the model as they are not required but if you have a []string then the string is added to the model. For instance:

package main

import (
    "net/http"

    restful "github.com/emicklei/go-restful"
    restfulspec "github.com/emicklei/go-restful-openapi"
)

func main() {
    restful.DefaultContainer.Add(webService())
    restfulConfig := restfulspec.Config{
        WebServices: restful.RegisteredWebServices(),
        APIPath:     "/apidocs.json",
    }
    restful.DefaultContainer.Add(restfulspec.NewOpenAPIService(restfulConfig))

    http.ListenAndServe(":9080", nil)
}

func webService() *restful.WebService {
    ws := new(restful.WebService)
    ws.Filter(restful.NoBrowserCacheFilter)

    ws.Path("/example").
        Produces(restful.MIME_JSON)

    ws.Route(ws.GET("readsStringSlice").
        Reads([]string{}, "List of strings").
        To(handler))

    return ws
}

func handler(req *restful.Request, resp *restful.Response) {

}

Produces:

{
 "swagger": "2.0",
 "paths": {
  "/example/readsStringSlice": {
   "get": {
    "produces": [
     "application/json"
    ],
    "operationId": "handler",
    "parameters": [
     {
      "description": "List of strings",
      "name": "body",
      "in": "body",
      "required": true,
      "schema": {
       "type": "array",
       "items": {
        "type": "string"
       }
      }
     }
    ],
    "responses": {
     "200": {
      "description": "OK"
     }
    }
   }
  }
 },
 "definitions": {
  "string": {}
 }
}

Instead of:

{
 "swagger": "2.0",
 "paths": {
  "/example/readsStringSlice": {
   "get": {
    "produces": [
     "application/json"
    ],
    "operationId": "handler",
    "parameters": [
     {
      "description": "List of strings",
      "name": "body",
      "in": "body",
      "required": true,
      "schema": {
       "type": "array",
       "items": {
        "type": "string"
       }
      }
     }
    ],
    "responses": {
     "200": {
      "description": "OK"
     }
    }
   }
  }
 }
}
iainduncani commented 4 years ago

I have a fix ready for this here:

https://github.com/iainduncani/go-restful-openapi/tree/primitive-slice-support

But as it is built on top of the code in PR #63 I will wait and see what happens with that PR before raising a separate PR for this fix.