github.com/kyma-incubator/compass/components/director@v0.0.0-20230623144113-d764f56ff805/pkg/httputils/response.go (about) 1 package httputils 2 3 import ( 4 "context" 5 "encoding/json" 6 "net/http" 7 8 "github.com/kyma-incubator/compass/components/director/pkg/log" 9 ) 10 11 // RespondWithBody writes a http response using with the JSON encoded data as payload 12 func RespondWithBody(ctx context.Context, w http.ResponseWriter, status int, data interface{}) { 13 w.Header().Add(HeaderContentTypeKey, ContentTypeApplicationJSON) 14 w.WriteHeader(status) 15 err := json.NewEncoder(w).Encode(data) 16 if err != nil { 17 log.C(ctx).WithError(err).Errorf("Failed to decode error response: %v", err) 18 } 19 } 20 21 // RespondWithError writes a http response using with the JSON encoded error wrapped in an Error struct 22 func RespondWithError(ctx context.Context, w http.ResponseWriter, status int, err error) { 23 log.C(ctx).WithError(err).Errorf("Responding with error: %v", err) 24 w.Header().Add(HeaderContentTypeKey, ContentTypeApplicationJSON) 25 w.WriteHeader(status) 26 errorResponse := ErrorResponse{[]Error{{Message: err.Error()}}} 27 encodingErr := json.NewEncoder(w).Encode(errorResponse) 28 if encodingErr != nil { 29 log.C(ctx).WithError(err).Errorf("Failed to encode error response: %v", err) 30 } 31 } 32 33 // Respond writes a http response only with status, without body 34 func Respond(w http.ResponseWriter, status int) { 35 w.Header().Add(HeaderContentTypeKey, ContentTypeApplicationJSON) 36 w.WriteHeader(status) 37 }