28 lines
754 B
Go
28 lines
754 B
Go
package web
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
)
|
|
|
|
// writeJSON writes v as a JSON response with the given status code.
|
|
func writeJSON(w http.ResponseWriter, status int, v any) {
|
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
|
w.WriteHeader(status)
|
|
_ = json.NewEncoder(w).Encode(v)
|
|
}
|
|
|
|
// writeJSONError writes {"ok":false,"error":msg} with the given status code.
|
|
func writeJSONError(w http.ResponseWriter, status int, msg string) {
|
|
writeJSON(w, status, map[string]any{"ok": false, "error": msg})
|
|
}
|
|
|
|
// writeJSONOK writes {"ok":true, ...extra} with HTTP 200.
|
|
func writeJSONOK(w http.ResponseWriter, extra map[string]any) {
|
|
if extra == nil {
|
|
extra = map[string]any{}
|
|
}
|
|
extra["ok"] = true
|
|
writeJSON(w, http.StatusOK, extra)
|
|
}
|