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:
29
server/respond.go
Normal file
29
server/respond.go
Normal 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"`
|
||||
}
|
||||
Reference in New Issue
Block a user