From 8e97a7dbf08d8930a440daa49e71d73822bde205 Mon Sep 17 00:00:00 2001 From: Ethel Morgan Date: Tue, 7 Jul 2020 16:01:10 +0100 Subject: import MustWriteJSON --- json.go | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 json.go diff --git a/json.go b/json.go new file mode 100644 index 0000000..62894cb --- /dev/null +++ b/json.go @@ -0,0 +1,21 @@ +// SPDX-FileCopyrightText: 2020 Ethel Morgan +// +// SPDX-License-Identifier: MIT + +package httputil + +import ( + "encoding/json" + "fmt" + "net/http" +) + +// MustWriteJSON writes data to w, panicking if it cannot. +// It panics because being unable to marshal JSON is programmer error, and not recoverable. +func MustWriteJSON(w http.ResponseWriter, data interface{}) { + blob, err := json.Marshal(data) + if err != nil { + panic(fmt.Sprintf("could not marshal JSON: %v", err)) + } + w.Write(blob) +} -- cgit v1.2.3