【问题标题】:go-swagger do not validates Body in POST requestgo-swagger 不验证 POST 请求中的 Body
【发布时间】:2019-10-09 00:00:39
【问题描述】:

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 "Content-Type: application/json" -d '{"foo":"bar"}' localhost:{{host}}/users

预期结果:

400 错误请求

给定结果:

501 不得打印

【问题讨论】:

标签: go swagger go-swagger


【解决方案1】:

我个人的解决方法是

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")
    })

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-27
    • 1970-01-01
    • 2022-01-09
    • 2018-03-23
    • 2017-06-20
    • 2020-11-04
    • 1970-01-01
    相关资源
    最近更新 更多