From c575b2fd5c1ebe8e42a1ab83dfa74ec05d5896b4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ferdinand=20M=C3=BCtsch?= Date: Fri, 16 Oct 2020 15:16:43 +0200 Subject: [PATCH] fix: json serialization error when percentage is nan --- models/compat/wakatime/v1/summaries.go | 6 +++++- utils/http.go | 3 ++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/models/compat/wakatime/v1/summaries.go b/models/compat/wakatime/v1/summaries.go index 327bfb8..9383e02 100644 --- a/models/compat/wakatime/v1/summaries.go +++ b/models/compat/wakatime/v1/summaries.go @@ -158,13 +158,17 @@ func convertEntry(e *models.SummaryItem, entityTotal time.Duration) *summariesEn hrs := int(total.Hours()) mins := int((total - time.Duration(hrs)*time.Hour).Minutes()) secs := int((total - time.Duration(hrs)*time.Hour - time.Duration(mins)*time.Minute).Seconds()) + percentage := math.Round((total.Seconds()/entityTotal.Seconds())*1e4) / 100 + if math.IsNaN(percentage) || math.IsInf(percentage, 0) { + percentage = 0 + } return &summariesEntry{ Digital: fmt.Sprintf("%d:%d:%d", hrs, mins, secs), Hours: hrs, Minutes: mins, Name: e.Key, - Percent: math.Round((total.Seconds()/entityTotal.Seconds())*1e4) / 100, + Percent: percentage, Seconds: secs, Text: utils.FmtWakatimeDuration(total), TotalSeconds: total.Seconds(), diff --git a/utils/http.go b/utils/http.go index b003578..ae96d9c 100644 --- a/utils/http.go +++ b/utils/http.go @@ -2,6 +2,7 @@ package utils import ( "encoding/json" + "log" "net/http" ) @@ -9,7 +10,7 @@ func RespondJSON(w http.ResponseWriter, status int, object interface{}) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(status) if err := json.NewEncoder(w).Encode(object); err != nil { - w.WriteHeader(http.StatusInternalServerError) + log.Printf("error while writing json response: %v", err) } }