first commit
This commit is contained in:
@@ -0,0 +1,28 @@
|
||||
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})
|
||||
}
|
||||
Reference in New Issue
Block a user