fix json response

This commit is contained in:
Livio Amstutz 2021-08-20 07:47:45 +02:00
parent d2d3395c25
commit 38a1f315de
3 changed files with 9 additions and 13 deletions

View file

@ -22,8 +22,7 @@ func keysHandler(k KeyProvider) func(http.ResponseWriter, *http.Request) {
func Keys(w http.ResponseWriter, r *http.Request, k KeyProvider) { func Keys(w http.ResponseWriter, r *http.Request, k KeyProvider) {
keySet, err := k.GetKeySet(r.Context()) keySet, err := k.GetKeySet(r.Context())
if err != nil { if err != nil {
w.WriteHeader(http.StatusInternalServerError) utils.MarshalJSONWithStatus(w, err, http.StatusInternalServerError)
utils.MarshalJSON(w, err)
return return
} }
utils.MarshalJSON(w, keySet) utils.MarshalJSON(w, keySet)

View file

@ -37,8 +37,7 @@ func Userinfo(w http.ResponseWriter, r *http.Request, userinfoProvider UserinfoP
info := oidc.NewUserInfo() info := oidc.NewUserInfo()
err = userinfoProvider.Storage().SetUserinfoFromToken(r.Context(), info, tokenID, subject, r.Header.Get("origin")) err = userinfoProvider.Storage().SetUserinfoFromToken(r.Context(), info, tokenID, subject, r.Header.Get("origin"))
if err != nil { if err != nil {
w.WriteHeader(http.StatusForbidden) utils.MarshalJSONWithStatus(w, err, http.StatusForbidden)
utils.MarshalJSON(w, err)
return return
} }
utils.MarshalJSON(w, info) utils.MarshalJSON(w, info)

View file

@ -5,20 +5,18 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"net/http" "net/http"
"github.com/sirupsen/logrus"
) )
func MarshalJSON(w http.ResponseWriter, i interface{}) { 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 { if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError) 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")
} }
} }