Skip to content

Commit

Permalink
fix(lib): avoid to print invalid JSON even if target is nil
Browse files Browse the repository at this point in the history
  • Loading branch information
macrat committed Nov 19, 2022
1 parent 3788e84 commit a1f0bcb
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 1 deletion.
7 changes: 6 additions & 1 deletion lib-ayd/record.go
Original file line number Diff line number Diff line change
Expand Up @@ -180,13 +180,18 @@ func (r *Record) UnmarshalJSON(data []byte) error {
func (r Record) MarshalJSON() ([]byte, error) {
head := bytes.NewBuffer(make([]byte, 0, 256))

target := ""
if r.Target != nil {
target = r.Target.String()
}

_, err := fmt.Fprintf(
head,
`{"time":"%s", "status":"%s", "latency":%.3f, "target":%q`,
r.Time.Format(time.RFC3339),
r.Status,
float64(r.Latency.Microseconds())/1000,
r.Target,
target,
)
if err != nil {
return nil, err
Expand Down
4 changes: 4 additions & 0 deletions lib-ayd/record_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -377,6 +377,10 @@ func TestRecord_MarshalJSON(t *testing.T) {
},
`{"time":"2021-01-02T15:04:05Z", "status":"HEALTHY", "latency":0.000, "target":"dummy:", "foo":"bar"}`,
},
{
ayd.Record{},
`{"time":"0001-01-01T00:00:00Z", "status":"UNKNOWN", "latency":0.000, "target":""}`,
},
}

for i, tt := range tests {
Expand Down

0 comments on commit a1f0bcb

Please sign in to comment.