// services/response.go
package services
import (
"crud-api/model"
"encoding/json"
"net/http"
)
func JsonResponse(w http.ResponseWriter, code int, payload interface{}, r *http.Request) {
var response []byte
var err error
w.Header().Set("Content-Type", "application/json")
response, err = json.MarshalIndent(payload, "", " ")
if err != nil {
errorResponse := model.ErrorResponse{
Status: http.StatusInternalServerError,
Message: "Error while running json.MarshalIndent on payload.",
}
response, _ = json.Marshal(errorResponse)
code = http.StatusInternalServerError
}
w.WriteHeader(code)
w.Write(response)
}