57 lines
1.3 KiB
Go
57 lines
1.3 KiB
Go
package handler
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
)
|
|
|
|
type APIResponse struct {
|
|
Success bool `json:"success"`
|
|
Data any `json:"data,omitempty"`
|
|
Errors []APIError `json:"errors,omitempty"`
|
|
Message string `json:"message,omitempty"`
|
|
}
|
|
|
|
type APIError struct {
|
|
Code int `json:"code"`
|
|
Message string `json:"message"`
|
|
Details string `json:"details,omitempty"`
|
|
}
|
|
|
|
const content_type = "Content-Type"
|
|
const application_json = "application/json"
|
|
|
|
func JSONSuccess(w http.ResponseWriter, data any, message string, statusCode int) {
|
|
w.Header().Set(content_type, application_json)
|
|
w.WriteHeader(statusCode)
|
|
json.NewEncoder(w).Encode(APIResponse{
|
|
Success: true,
|
|
Data: data,
|
|
Message: message,
|
|
})
|
|
}
|
|
|
|
func JSONError(w http.ResponseWriter, message, details string, code, statusCode int) {
|
|
w.Header().Set(content_type, application_json)
|
|
w.WriteHeader(statusCode)
|
|
json.NewEncoder(w).Encode(APIResponse{
|
|
Success: false,
|
|
Errors: []APIError{
|
|
{
|
|
Code: code,
|
|
Message: message,
|
|
Details: details,
|
|
},
|
|
},
|
|
})
|
|
}
|
|
|
|
func JSONErrors(w http.ResponseWriter, errors []APIError, statusCode int) {
|
|
w.Header().Set(content_type, application_json)
|
|
w.WriteHeader(statusCode)
|
|
json.NewEncoder(w).Encode(APIResponse{
|
|
Success: false,
|
|
Errors: errors,
|
|
})
|
|
}
|