29 lines
963 B
Go
29 lines
963 B
Go
package mw
|
|
|
|
import (
|
|
"encoding/json"
|
|
"log"
|
|
"net/http"
|
|
)
|
|
|
|
// RespondJSON writes a JSON response with the given status code.
|
|
// The Content-Type is always set to application/json, overriding any
|
|
// middleware-set value, to ensure consistent JSON error responses.
|
|
func RespondJSON(w http.ResponseWriter, status int, data any) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(status)
|
|
if err := json.NewEncoder(w).Encode(data); err != nil {
|
|
log.Printf("Failed to encode JSON response: %v", err)
|
|
}
|
|
}
|
|
|
|
// RespondError sends a JSON error response with the given status code and message.
|
|
// It preserves the application/json Content-Type set by middleware.
|
|
func RespondError(w http.ResponseWriter, status int, msg string) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(status)
|
|
if err := json.NewEncoder(w).Encode(map[string]string{"error": msg}); err != nil {
|
|
log.Printf("Failed to encode error response: %v", err)
|
|
}
|
|
}
|