Skip to content

Header should not be set before the message is written #1175

Description

@tadejsv

This is a function generated for a strict echo server:

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

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

The problem is that the response object here can still fail validation (in my case, if I set "abc" in the email field, I get an error from the JSON marshalling function) and thus return an error - but the header is already set (and sent) to 200, so the respnse will have a status code of 200 - no matter what middlewares/error handlers are used (request also gets r.Commited = true on WriteHeader).

I think the proper way of implementing this function would be something like

func (response GetUsers200JSONResponse) aVisitGetUsersResponse(w http.ResponseWriter) error {
   err := json.NewEncoder(w).Encode(response)
   if err != nil {
   	return err    
   }

   w.Header().Set("Content-Type", "application/json")
   w.WriteHeader(200)
   return nil
}

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