oapi-codegen icon indicating copy to clipboard operation
oapi-codegen copied to clipboard

Default values not applied on incoming requests

Open devzaak opened this issue 3 years ago • 0 comments

Hi, I am trying to understand how the generation is supposed to handle default values that are part of the open api spec. In my case, I have the following spec that expects request to have default values. If I send the request to server generated and implemented with this spec the validations work, but if even a single field is not present the validation passes but request then crashes as it tries to access null pointer

As I am relatively new to golang, can you help me understand how the handling of defaults is expected to work, should I expect this to be handled by generated code, some extra middleware or something else?

Thank you

spec:

openapi: "3.0.0"
info:
  title: OAM Translation - OpenAPI 3.0
  version: 0.1.0
paths:
  /translations:
    post:
      summary: Translation endpoint receives request 
      operationId: createTranslation
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/TranslationRequest'
        required: true
      responses:
        '200':
          description: TranslationResponse
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TranslationResponse'
        '405':
          description: Validation exception
      tags:
        - translations
components:
  schemas:
    TranslationRequest:
      properties:
        min:
          type: integer
          minimum: 0
          default: 2
        max:
          type: integer
          minimum: 0
          default: 30
        name:
          description: environment variable name
          type: string
          pattern: ^[A-Z_0-9]+$
          maxLength: 4

      type: object
    
    TranslationResponse:
      properties:
          body:
            type: string
          error:
              type: string
      type: object

config:

output: server.gen.go
package: api
generate:
  gorilla-server: true
  models: true
  embedded-spec: true
  strict-server: true

golang structs:

// TranslationRequest defines model for TranslationRequest.
type TranslationRequest struct {
	Max *int `json:"max,omitempty"`
	Min *int `json:"min,omitempty"`

	// Name environment variable name
	Name *string `json:"name,omitempty"`
}

// TranslationResponse defines model for TranslationResponse.
type TranslationResponse struct {
	Body  *string `json:"body,omitempty"`
	Error *string `json:"error,omitempty"`
}

request:

curl --location --request POST 'localhost:8080/translations' --header 'Content-Type: application/json' --data-raw '{
    "max":3,
    "name": "TE1"
}'

devzaak avatar Oct 26 '22 12:10 devzaak