go-swagger不验证POST请求中的主体

时间:2019-05-22 13:18:27

标签: go swagger go-swagger

大摇大摆地忽略了POST请求正文中的必填字段。

复制步骤:

  1. 描述swaggerfile
swagger: "2.0"
info:
  title: Sample API
  description: API description in Markdown.
  version: 1.0.0
host: api.example.com
schemes:
  - http
paths:
  /users:
    post:
      operationId: UserCreate
      parameters:
        - name: body
          in: body
          required: true
          schema:
            allOf:
              - $ref: "#/definitions/ID"
              - $ref: "#/definitions/User_object"
              - type: object
                required:  # HERE! IT IS NOT WORKING
                  - ID
                  - genderCode
                  - birthDate
                  - code
      produces:
        - application/json
      consumes:
        - application/json
      responses:
        200:
          description: "OK"

definitions:
  ID:
    title: ID
    properties:
      GUID:
        type: string
        description: "ID"
        format: uuid

  User_object:
    title: User_object
    properties:
      genderCode:
        type: string
      birthDate:
        type: string
        format: date
      code:
        type: string
  1. 生成api
  

swagger生成服务器-f swaggerfile.yaml -t api

  1. 描述单个处理程序:
api.UserCreateHandler = operations.UserCreateHandlerFunc(func(params operations.UserCreateParams) middleware.Responder {
        return middleware.NotImplemented("MUST NOT BE PRINTED")
    })
  1. 请求生成的api:
  

curl -X POST -H“内容类型:application / json” -d'{“ foo”:“ bar”}'localhost:{{host}} /用户

预期结果:

  

400错误的请求

给出结果:

  

不得打印501

1 个答案:

答案 0 :(得分:0)

我的个人解决方法是

api.UserCreateHandler = operations.UserCreateHandlerFunc(func(params operations.UserCreateParams) middleware.Responder {
        if params.Body.UserObject == (models.UserObject{}) {
            return //... your BAD REQUEST type
        }
        return middleware.NotImplemented("MUST NOT BE PRINTED")
    })