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>
This commit is contained in:
2026-03-22 21:47:45 +03:00
parent de5bf9a6d9
commit 7a2cef00c3
2 changed files with 101 additions and 0 deletions

29
server/respond.go Normal file
View File

@@ -0,0 +1,29 @@
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"`
}