Skip to content

Commit d440e08

Browse files
committed
jcall: Add -i (indent) flag for output
1 parent 5c6aa04 commit d440e08

File tree

1 file changed

+14
-3
lines changed

1 file changed

+14
-3
lines changed

cmd/jcall/jcall.go

+14-3
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
package main
77

88
import (
9+
"bytes"
910
"context"
1011
"encoding/json"
1112
"errors"
@@ -33,6 +34,7 @@ var (
3334
chanFraming = flag.String("f", envOrDefault("JCALL_FRAMING", "raw"), "Channel framing")
3435
doBatch = flag.Bool("batch", false, "Issue calls as a batch rather than sequentially")
3536
doErrors = flag.Bool("e", false, "Print error values to stdout")
37+
doIndent = flag.Bool("i", false, "Indent JSON output")
3638
doMulti = flag.Bool("m", false, "Issue the same call repeatedly with different arguments")
3739
doTiming = flag.Bool("T", false, "Print call timing stats")
3840
withLogging = flag.Bool("v", false, "Enable verbose logging")
@@ -171,7 +173,7 @@ func printResults(rsps []*jrpc2.Response) (time.Duration, error) {
171173
if rerr := rsp.Error(); rerr != nil {
172174
if *doErrors {
173175
etxt, _ := json.Marshal(rerr)
174-
fmt.Println(string(etxt))
176+
fmt.Println(formatJSON(etxt))
175177
} else {
176178
log.Printf("Error (%d): %v", i+1, rerr)
177179
}
@@ -185,7 +187,7 @@ func printResults(rsps []*jrpc2.Response) (time.Duration, error) {
185187
set(perr)
186188
continue
187189
}
188-
fmt.Println(string(result))
190+
fmt.Println(formatJSON(result))
189191
dur += time.Since(pstart)
190192
}
191193
return dur, err
@@ -235,7 +237,7 @@ func issueSequential(ctx context.Context, cli *jrpc2.Client, specs []jrpc2.Spec)
235237
if perr := rsp.UnmarshalResult(&result); perr != nil {
236238
return dur, err
237239
}
238-
fmt.Println(string(result))
240+
fmt.Println(formatJSON(result))
239241
pdur := time.Since(pstart)
240242
dur += pdur
241243
tprintf("[call %s]: %v call, %v print [%s]\n", spec.Method, cdur, pdur, callStatus(err))
@@ -274,6 +276,15 @@ func param(s string) interface{} {
274276
return json.RawMessage(s)
275277
}
276278

279+
func formatJSON(data []byte) string {
280+
if *doIndent {
281+
var buf bytes.Buffer
282+
json.Indent(&buf, data, "", " ")
283+
return buf.String()
284+
}
285+
return string(data)
286+
}
287+
277288
func isHTTP(addr string) bool {
278289
return strings.HasPrefix(addr, "http:") || strings.HasPrefix(addr, "https:")
279290
}

0 commit comments

Comments
 (0)