Would it then be better to marshal the json first and write only if it succeeds?
Assistant
Your code is mostly fine, but the order of setting the headers and status code needs adjustment. In Go's http.ResponseWriter, headers must be set before writing the status code or the body. Once you call WriteHeader or write to the response body, headers are sent and cannot be modified.
Specifically:
You should set the Content-Type header before calling w.WriteHeader.
In fact, if you call Encode (which writes to the response), it implicitly sends the status code 200 if you haven't called WriteHeader explicitly.
So, either set the headers before encoding or explicitly write the status code and headers before encoding.
Also, your TODO comments for writing error responses should ideally include a short message to the client (JSON or plain text), otherwise the client gets an empty response.
Here’s a revised version of your handler with these points addressed:
go
func (h *HTTPServer) handleDeliveryHoursRequest(w http.ResponseWriter, r *http.Request) {
query := r.URL.Query()
city := query.Get("city")
if city == "" {
http.Error(w, "`city` query parameter is required", http.StatusBadRequest)
return
}
venueID := query.Get("venue_id")
if venueID == "" {
http.Error(w, "`venue_id` query parameter is required", http.StatusBadRequest)
return
}
venueIDi, err := strconv.ParseInt(venueID, 10, 64)
if err != nil {
http.Error(w, "`venue_id` must be a valid integer", http.StatusBadRequest)
return
}
deliveryHours, err := h.deliveryHoursComposer.GetDeliveryHours(city, int(venueIDi))
if errors.Is(err, ErrNoDeliveryAvailable) {
http.Error(w, "No delivery available for the specified city and venue", http.StatusNotFound)
return
}
if err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
// No need to write header explicitly; the first call to write will send 200 status code
err = json.NewEncoder(w).Encode(&deliveryHours)
if err != nil {
// If error encoding, it may be too late to set headers, but you can still attempt to write an error
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
return
}
}
Summary of changes:
Used http.Error for consistent error responses with message + status code.
Set Content-Type before writing body.
Removed explicit WriteHeader(http.StatusOK) because Encode writes to the response and implicitly sends status 200.
Added meaningful error messages for clients.
Preserved your error handling logic.
This approach is idiomatic Go for HTTP handlers.
Yes, marshaling the JSON first before writing anything to the http.ResponseWriter can be a better approach in some cases, especially if:
You want to guarantee that the response headers and status code are only sent if the entire response body can be marshaled successfully.
You want to avoid partially written responses if JSON encoding fails midway.
When you use json.NewEncoder(w).Encode(...) directly, the encoder starts writing to the response immediately. If an error occurs during encoding (e.g., due to an invalid structure or a write failure), you cannot change the HTTP status code or headers because they have already been sent.
How to do this:
Marshal the JSON response into a []byte.
If marshaling succeeds, set the headers and status code.
Write the marshaled data to the response.
Example:
go
func (h *HTTPServer) handleDeliveryHoursRequest(w http.ResponseWriter, r *http.Request) {
query := r.URL.Query()
city := query.Get("city")
if city == "" {
http.Error(w, "`city` query parameter is required", http.StatusBadRequest)
return
}
venueID := query.Get("venue_id")
if venueID == "" {
http.Error(w, "`venue_id` query parameter is required", http.StatusBadRequest)
return
}
venueIDi, err := strconv.ParseInt(venueID, 10, 64)
if err != nil {
http.Error(w, "`venue_id` must be a valid integer", http.StatusBadRequest)
return
}
deliveryHours, err := h.deliveryHoursComposer.GetDeliveryHours(city, int(venueIDi))
if errors.Is(err, ErrNoDeliveryAvailable) {
http.Error(w, "No delivery available for the specified city and venue", http.StatusNotFound)
return
}
if err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
// Marshal JSON before writing headers/body:
data, err := json.Marshal(deliveryHours)
if err != nil {
http.Error(w, "Failed to marshal response", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, err = w.Write(data)
if err != nil {
// Optional: log error writing response
}
}
Pros of marshaling first:
Clean separation of JSON serialization and response writing.
You avoid partial or corrupted HTTP responses.
You can decide on status codes after marshaling.
Cons:
Uses some additional memory to hold the marshaled bytes before writing.
For very large responses, this buffer can grow significantly.
When to marshal first vs encode directly:
For small or medium responses, marshaling first is fine.
For large streaming responses (e.g., big JSON arrays), encoding directly to the ResponseWriter is more efficient and memory-friendly, at the cost of handling possible partial writes and errors differently.
Summary: For your use case, marshaling first provides safer and cleaner error handling. If performance/memory is not a concern and responses are reasonably sized, go with marshaling first.