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

ResponseErrorHandlerFunc cannot set status code

Open sean-cunniffe opened this issue 9 months ago • 0 comments

Version: 2.4.1

Issue: Status code is set to 200 before marshalling data into body inside visit<ResponseName> functions, so when an error occurs marshalling the ResponseErrorHandlerFunc cannot set the status code.

Reproduce:

openapi: 3.0.1
info:
  title: error-handler-example
  version: 1.0.0
paths:
  /api/example:
    post:
      operationId: exampleHandler
      responses:
        200:
          description: example
          content:
            application/json:
              schema:
                type: object
                properties:
                  example:
                    type: string
                    format: email
package: api
generate:
  gorilla-server: true
  strict-server: true
  models: true
output: generated/gen.go
package main

import (
	"context"
	"net/http"

	api "example.go/generated"
	openapi_types "github.com/oapi-codegen/runtime/types"
)

type ExampleHandler struct {
}

func main() {
	e := &ExampleHandler{}
	h := api.NewStrictHandlerWithOptions(e, nil, api.StrictHTTPServerOptions{
		ResponseErrorHandlerFunc: func(w http.ResponseWriter, r *http.Request, err error) {
			w.WriteHeader(500)
		},
	})
	handler := api.Handler(h)
	err := http.ListenAndServe(":8080", handler)
	panic(err)
}

func (*ExampleHandler) ExampleHandler(ctx context.Context,
	request api.ExampleHandlerRequestObject) (api.ExampleHandlerResponseObject, error) {
	email := openapi_types.Email("invalid email")
	return api.ExampleHandler200JSONResponse{
		Example: &email,
	}, nil
}

Generated visit function

func (response ExampleHandler200JSONResponse) VisitExampleHandlerResponse(w http.ResponseWriter) error {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(200)

	return json.NewEncoder(w).Encode(response)
}

sean-cunniffe avatar May 04 '25 02:05 sean-cunniffe