24 lines
586 B
Go
24 lines
586 B
Go
package utils
|
|
|
|
import (
|
|
"encoding/json"
|
|
"log/slog"
|
|
"net/http"
|
|
)
|
|
|
|
type ErrorResponse struct {
|
|
Message string `json:"message"`
|
|
Code int `json:"code,omitempty"`
|
|
}
|
|
|
|
func WriteJSONError(w http.ResponseWriter, message string, statusCode int) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(statusCode)
|
|
errorRes := ErrorResponse{Message: message, Code: statusCode}
|
|
enc := json.NewEncoder(w)
|
|
enc.SetIndent("", " ")
|
|
err := enc.Encode(errorRes) // Encode and write the JSON response
|
|
if err != nil {
|
|
slog.Error("Error in WriteJSONError", "error", err)
|
|
}
|
|
}
|