36 lines
901 B
Go
36 lines
901 B
Go
package utils
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
|
|
"datarush/internal/gw/domain"
|
|
)
|
|
|
|
func RespondJSON(w http.ResponseWriter, statusCode int, data interface{}) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(statusCode)
|
|
|
|
if data != nil {
|
|
if err := json.NewEncoder(w).Encode(data); err != nil {
|
|
http.Error(w, "internal server error", http.StatusInternalServerError)
|
|
}
|
|
}
|
|
}
|
|
|
|
func RespondError(w http.ResponseWriter, err error) {
|
|
if appErr, ok := err.(*domain.AppError); ok {
|
|
RespondJSON(w, appErr.StatusCode, domain.NewErrorResponse(appErr.Err, appErr.Message))
|
|
return
|
|
}
|
|
|
|
RespondJSON(w, http.StatusInternalServerError, domain.NewErrorResponse(err, "internal server error"))
|
|
}
|
|
|
|
func DecodeJSON(r *http.Request, v interface{}) error {
|
|
if err := json.NewDecoder(r.Body).Decode(v); err != nil {
|
|
return domain.NewBadRequestError("invalid JSON body")
|
|
}
|
|
return nil
|
|
}
|