http: emit indented JSON in the metrics stream endpoint

To remove the need to decode and re-encode in the CLI
This commit is contained in:
Daniel Nephin 2021-07-14 18:52:57 -04:00
parent b5a2cbf369
commit cf2e25c6bb
2 changed files with 7 additions and 12 deletions

View File

@ -181,7 +181,7 @@ func (s *HTTPHandlers) AgentMetricsStream(resp http.ResponseWriter, req *http.Re
flusher, ok := resp.(http.Flusher) flusher, ok := resp.(http.Flusher)
if !ok { if !ok {
return nil, fmt.Errorf("Streaming not supported") return nil, fmt.Errorf("streaming not supported")
} }
resp.WriteHeader(http.StatusOK) resp.WriteHeader(http.StatusOK)
@ -196,6 +196,7 @@ func (s *HTTPHandlers) AgentMetricsStream(resp http.ResponseWriter, req *http.Re
encoder: json.NewEncoder(resp), encoder: json.NewEncoder(resp),
flusher: flusher, flusher: flusher,
} }
enc.encoder.SetIndent("", " ")
s.agent.baseDeps.MetricsHandler.Stream(req.Context(), enc) s.agent.baseDeps.MetricsHandler.Stream(req.Context(), enc)
return nil, nil return nil, nil
} }

View File

@ -2,6 +2,7 @@ package debug
import ( import (
"archive/tar" "archive/tar"
"bufio"
"compress/gzip" "compress/gzip"
"context" "context"
"encoding/json" "encoding/json"
@ -529,17 +530,10 @@ func (c *cmd) captureMetrics(ctx context.Context, timestampDir string) error {
} }
defer fh.Close() defer fh.Close()
decoder := json.NewDecoder(stream) b := bufio.NewReader(stream)
encoder := json.NewEncoder(fh) _, err = b.WriteTo(fh)
// TODO: is More() correct here? if err != nil && !errors.Is(err, context.DeadlineExceeded) {
for decoder.More() { return fmt.Errorf("failed to copy metrics to file: %w", err)
var raw interface{}
if err := decoder.Decode(&raw); err != nil {
return fmt.Errorf("failed to decode metrics: %w", err)
}
if err := encoder.Encode(raw); err != nil {
return fmt.Errorf("failed to write metrics to file: %w", err)
}
} }
return nil return nil
} }