[BUG] go-server doesn't honour the provided headers within EncodeJSONResponse
Created by: mgoltzsche
Bug Report Checklist
-
Have you provided a full/minimal spec to reproduce the issue? -
Have you validated the input using an OpenAPI validator (example)? -
Have you tested with the latest master to confirm the issue still exists? -
Have you searched for related issues/PRs? -
What's the actual output vs expected output? -
[Optional] Sponsorship to speed up the bug fix or feature request (example)
Description
When the option addResponseHeaders
is enabled for the go-server
generator it generates a ResponseWithHeaders
method that calls an EncodeJSONResponse
method which however ignores the headers that are provided to it.
The generated method looks as follows:
func EncodeJSONResponse(i interface{}, status *int, headers map[string][]string, w http.ResponseWriter) error {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
if status != nil {
w.WriteHeader(*status)
} else {
w.WriteHeader(http.StatusOK)
}
return json.NewEncoder(w).Encode(i)
}
This stops me from specifying response headers within my controller implementation.
I would expect this method to apply the headers I provided.
openapi-generator version
openapi-generator 5.1.1
OpenAPI declaration file content or url
This is the example OpenAPI schema example-openapi.yaml
- though you could use any other to reproduce the bug that is described here:
openapi: "3.0.3"
info:
title: "Example API"
version: "1.0.0"
paths:
"/path/{myparam}/myresource":
post:
operationId: createResource
parameters:
- name: myparam
in: path
required: true
schema:
type: string
requestBody:
content:
"application/json":
schema:
type: object
properties:
name:
type: string
responses:
'201':
description: response with headers
headers:
myheader:
schema:
type: string
Generation Details
java -jar ./openapi-generator-5.1.1.jar generate -i ./example-openapi.yaml -g go-server -o ./generated --api-name-suffix API --package-name generated -p addResponseHeaders=true
Steps to reproduce
see generation details
Related issues/PRs
Suggest a fix
Generate the EncodeJSONResponse
method so that it applies the provided headers to the ResponseWriter
:
func EncodeJSONResponse(i interface{}, status *int, headers map[string][]string, w http.ResponseWriter) error {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
if headers != nil {
for k, v := range headers {
w.Header()[k] = v
}
}
if status != nil {
w.WriteHeader(*status)
} else {
w.WriteHeader(http.StatusOK)
}
return json.NewEncoder(w).Encode(i)
}