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

Wrong type when using x-go-type-skip-optional-pointer

Open sonu27 opened this issue 2 years ago • 1 comments

When using x-go-type-skip-optional-pointer on an optional header, invalid code gets generated which cannot compile.

openapi: 3.0.3
info:
  title: Form API
  version: '1.0'
paths:
  /api/v1/forms/contact:
    post:
      operationId: sendContactForm
      parameters:
        - in: header
          name: X-Real-IP
          required: false
          schema:
            type: string
            x-go-type-skip-optional-pointer: true # the problem
      responses:
        '204':
          description: Contact form sent
      tags:
        - form

This results in:

// ------------- Optional header parameter "X-Real-IP" -------------
	if valueList, found := headers[http.CanonicalHeaderKey("X-Real-IP")]; found {
		var XRealIP string
		n := len(valueList)
		if n != 1 {
			siw.ErrorHandlerFunc(w, r, &TooManyValuesForParamError{ParamName: "X-Real-IP", Count: n})
			return
		}

		err = runtime.BindStyledParameterWithLocation("simple", false, "X-Real-IP", runtime.ParamLocationHeader, valueList[0], &XRealIP)
		if err != nil {
			siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "X-Real-IP", Err: err})
			return
		}

		params.XRealIP = &XRealIP // the problem, should be without the pointer
		// the fix: params.XRealIP = XRealIP

	}

sonu27 avatar Sep 14 '23 12:09 sonu27

I am seeing something similar (runtime error) if I use x-go-type-skip-optional-pointer: true in a query parameter:

        - name: trueFalse
          in: query
          schema:
            type: boolean
            x-go-type-skip-optional-pointer: true

generated code:

	err = runtime.BindQueryParameter("form", true, false, "trueFalse", r.URL.Query(), &params.TrueFalse)

Runtime error:

panic: reflect: call of reflect.Value.IsNil on bool Value [recovered]
        panic: reflect: call of reflect.Value.IsNil on bool Value

aravindhp avatar Aug 27 '24 10:08 aravindhp

Stumbled into the same issue with:

        - name: pct
          in: query
          required: false
          schema:
            type: integer
            default: 0
            x-go-type-skip-optional-pointer: true
            minimum: 0
            maximum: 100

Code: err = runtime.BindQueryParameter("form", true, false, "pct", r.URL.Query(), &params.Pct)

Getting: panic: reflect: call of reflect.Value.IsNil on int Value Maybe I misunderstood how/when x-go-type-skip-optional-pointer should be used?

marcomayer avatar Jan 23 '25 13:01 marcomayer

This should be fixed, or at least avoid panic and crashing services! Do your nil checks for reflect!

emiago avatar Feb 14 '25 13:02 emiago