diff --git a/cmd/rc/rc.go b/cmd/rc/rc.go index cad7f2d77..58aba8478 100644 --- a/cmd/rc/rc.go +++ b/cmd/rc/rc.go @@ -106,9 +106,7 @@ func run(args []string) (err error) { // Write the JSON blob to stdout if required if out != nil && !noOutput { - enc := json.NewEncoder(os.Stdout) - enc.SetIndent("", "\t") - err = enc.Encode(out) + err := rc.WriteJSON(os.Stdout, out) if err != nil { return errors.Wrap(err, "failed to output JSON") } diff --git a/fs/rc/rc.go b/fs/rc/rc.go index a0d3b614d..eef6c169e 100644 --- a/fs/rc/rc.go +++ b/fs/rc/rc.go @@ -62,17 +62,6 @@ func (s *server) serve() { s.srv.Serve() } -// writes JSON in out to w -func writeJSON(w http.ResponseWriter, out Params) { - enc := json.NewEncoder(w) - enc.SetIndent("", "\t") - err := enc.Encode(out) - if err != nil { - // can't return the error at this point - fs.Errorf(nil, "rc: failed to write JSON output: %v", err) - } -} - // handler reads incoming requests and dispatches them func (s *server) handler(w http.ResponseWriter, r *http.Request) { path := strings.Trim(r.URL.Path, "/") @@ -81,10 +70,14 @@ func (s *server) handler(w http.ResponseWriter, r *http.Request) { writeError := func(err error, status int) { fs.Errorf(nil, "rc: %q: error: %v", path, err) w.WriteHeader(status) - writeJSON(w, Params{ + err = WriteJSON(w, Params{ "error": err.Error(), "input": in, }) + if err != nil { + // can't return the error at this point + fs.Errorf(nil, "rc: failed to write JSON output: %v", err) + } } if r.Method != "POST" { @@ -131,5 +124,9 @@ func (s *server) handler(w http.ResponseWriter, r *http.Request) { } fs.Debugf(nil, "rc: %q: reply %+v: %v", path, out, err) - writeJSON(w, out) + err = WriteJSON(w, out) + if err != nil { + // can't return the error at this point + fs.Errorf(nil, "rc: failed to write JSON output: %v", err) + } } diff --git a/fs/rc/rc_new.go b/fs/rc/rc_new.go new file mode 100644 index 000000000..32c988001 --- /dev/null +++ b/fs/rc/rc_new.go @@ -0,0 +1,15 @@ +//+build go1.7 + +package rc + +import ( + "encoding/json" + "io" +) + +// WriteJSON writes JSON in out to w +func WriteJSON(w io.Writer, out Params) error { + enc := json.NewEncoder(w) + enc.SetIndent("", "\t") + return enc.Encode(out) +} diff --git a/fs/rc/rc_old.go b/fs/rc/rc_old.go new file mode 100644 index 000000000..1ce9f6184 --- /dev/null +++ b/fs/rc/rc_old.go @@ -0,0 +1,14 @@ +//+build !go1.7 + +package rc + +import ( + "encoding/json" + "io" +) + +// WriteJSON writes JSON in out to w +func WriteJSON(w io.Writer, out Params) error { + enc := json.NewEncoder(w) + return enc.Encode(out) +}