Files
httpx/server/respond.go
Aleksey Shakhmatov 7a2cef00c3 Add server WriteJSON and WriteError response helpers
Eliminates repeated marshal-set-header-write boilerplate in handlers.
WriteError produces consistent {"error": "..."} JSON responses.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-22 21:47:45 +03:00

30 lines
728 B
Go

package server
import (
"encoding/json"
"net/http"
)
// WriteJSON encodes v as JSON and writes it to w with the given status code.
// It sets Content-Type to application/json.
func WriteJSON(w http.ResponseWriter, status int, v any) error {
b, err := json.Marshal(v)
if err != nil {
return err
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_, err = w.Write(b)
return err
}
// WriteError writes a JSON error response with the given status code and
// message. The response body is {"error": "<message>"}.
func WriteError(w http.ResponseWriter, status int, msg string) error {
return WriteJSON(w, status, errorBody{Error: msg})
}
type errorBody struct {
Error string `json:"error"`
}