From 38a1f315de3173ad597868aad12d50c1969cf82e Mon Sep 17 00:00:00 2001 From: Livio Amstutz Date: Fri, 20 Aug 2021 07:47:45 +0200 Subject: [PATCH] fix json response --- pkg/op/keys.go | 3 +-- pkg/op/userinfo.go | 3 +-- pkg/utils/marshal.go | 16 +++++++--------- 3 files changed, 9 insertions(+), 13 deletions(-) diff --git a/pkg/op/keys.go b/pkg/op/keys.go index c4b11d4..5875a7b 100644 --- a/pkg/op/keys.go +++ b/pkg/op/keys.go @@ -22,8 +22,7 @@ func keysHandler(k KeyProvider) func(http.ResponseWriter, *http.Request) { func Keys(w http.ResponseWriter, r *http.Request, k KeyProvider) { keySet, err := k.GetKeySet(r.Context()) if err != nil { - w.WriteHeader(http.StatusInternalServerError) - utils.MarshalJSON(w, err) + utils.MarshalJSONWithStatus(w, err, http.StatusInternalServerError) return } utils.MarshalJSON(w, keySet) diff --git a/pkg/op/userinfo.go b/pkg/op/userinfo.go index 9abf378..c3f2d55 100644 --- a/pkg/op/userinfo.go +++ b/pkg/op/userinfo.go @@ -37,8 +37,7 @@ func Userinfo(w http.ResponseWriter, r *http.Request, userinfoProvider UserinfoP info := oidc.NewUserInfo() err = userinfoProvider.Storage().SetUserinfoFromToken(r.Context(), info, tokenID, subject, r.Header.Get("origin")) if err != nil { - w.WriteHeader(http.StatusForbidden) - utils.MarshalJSON(w, err) + utils.MarshalJSONWithStatus(w, err, http.StatusForbidden) return } utils.MarshalJSON(w, info) diff --git a/pkg/utils/marshal.go b/pkg/utils/marshal.go index 4f53b4e..a755e84 100644 --- a/pkg/utils/marshal.go +++ b/pkg/utils/marshal.go @@ -5,20 +5,18 @@ import ( "encoding/json" "fmt" "net/http" - - "github.com/sirupsen/logrus" ) func MarshalJSON(w http.ResponseWriter, i interface{}) { - b, err := json.Marshal(i) + MarshalJSONWithStatus(w, i, http.StatusOK) +} + +func MarshalJSONWithStatus(w http.ResponseWriter, i interface{}, status int) { + w.Header().Set("content-type", "application/json") + w.WriteHeader(status) + err := json.NewEncoder(w).Encode(i) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - w.Header().Set("content-type", "application/json") - _, err = w.Write(b) - if err != nil { - logrus.Error("error writing response") } }