27 lines
666 B
Go
27 lines
666 B
Go
|
|
package httperrors
|
||
|
|
|
||
|
|
import (
|
||
|
|
"encoding/json"
|
||
|
|
"net/http"
|
||
|
|
)
|
||
|
|
|
||
|
|
// ErrorResponse is the standard JSON error body for API responses.
|
||
|
|
type ErrorResponse struct {
|
||
|
|
Error struct {
|
||
|
|
Code string `json:"code"`
|
||
|
|
Message string `json:"message"`
|
||
|
|
} `json:"error"`
|
||
|
|
}
|
||
|
|
|
||
|
|
// WriteJSON writes a JSON error response with the given status code and message.
|
||
|
|
func WriteJSON(w http.ResponseWriter, statusCode int, code, message string) {
|
||
|
|
w.Header().Set("Content-Type", "application/json")
|
||
|
|
w.WriteHeader(statusCode)
|
||
|
|
json.NewEncoder(w).Encode(ErrorResponse{
|
||
|
|
Error: struct {
|
||
|
|
Code string `json:"code"`
|
||
|
|
Message string `json:"message"`
|
||
|
|
}{Code: code, Message: message},
|
||
|
|
})
|
||
|
|
}
|