Files
go-simple-api/internal/handlers/respond.go
T
2026-07-16 10:13:46 +03:30

29 lines
1.0 KiB
Go

package handlers
import (
"encoding/json"
"net/http"
)
// writeJSON is a tiny shared helper used by every handler in this package
// to avoid repeating the "set Content-Type header, write status code,
// encode body as JSON" sequence over and over.
//
// data is typed `any` (Go's built-in alias for interface{}, since Go 1.18)
// so this one function can serialize maps, structs, slices - anything
// encoding/json knows how to handle.
func writeJSON(w http.ResponseWriter, status int, data any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
// Encoder writes JSON directly to the ResponseWriter (which is just an
// io.Writer under the hood) - no need to build the JSON bytes in a
// separate variable first.
json.NewEncoder(w).Encode(data)
}
// writeError is a thin wrapper around writeJSON for the extremely common
// case of returning a single {"error": "..."} body.
func writeError(w http.ResponseWriter, status int, message string) {
writeJSON(w, status, map[string]string{"error": message})
}