Skip to content

ResponseErrorHandlerFunc cannot set status code #1964

Description

@sean-cunniffe

Version: 2.4.1

Issue: Status code is set to 200 before marshalling data into body inside visit 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)
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions