github.com/blong14/gache@v0.0.0-20240124023949-89416fd8bbfa/internal/io/http/writer.go (about) 1 package http 2 3 import ( 4 "encoding/json" 5 "log" 6 7 glog "github.com/blong14/gache/internal/logging" 8 stdhttp "net/http" 9 ) 10 11 func MustWriteJSON(w stdhttp.ResponseWriter, r *stdhttp.Request, status int, resp interface{}) { 12 w.Header().Set("Content-Type", "application/json") 13 if status >= stdhttp.StatusBadRequest { 14 w.WriteHeader(status) 15 } 16 jsonResp, err := json.Marshal(resp) 17 if err != nil { 18 log.Fatalf("Error happened in JSON marshal. Err: %s", err) 19 } 20 if _, err := w.Write(jsonResp); err != nil { 21 log.Fatalf("Error happened in writing JSON. Err: %s", err) 22 } 23 glog.Track("method=%s status=%v", r.Method, status) 24 }