86 lines
2.5 KiB
Go
86 lines
2.5 KiB
Go
package responses
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// Response is a standardized API response structure
|
|
type Response struct {
|
|
Success bool `json:"success"`
|
|
Data interface{} `json:"data,omitempty"`
|
|
Error *ErrorInfo `json:"error,omitempty"`
|
|
}
|
|
|
|
// ErrorInfo contains detailed error information
|
|
type ErrorInfo struct {
|
|
Code string `json:"code"`
|
|
Message string `json:"message"`
|
|
}
|
|
|
|
// ErrorResponse codes
|
|
const (
|
|
ErrorCodeValidation = "VALIDATION_ERROR"
|
|
ErrorCodeNotFound = "NOT_FOUND"
|
|
ErrorCodeUnauthorized = "UNAUTHORIZED"
|
|
ErrorCodeForbidden = "FORBIDDEN"
|
|
ErrorCodeInternal = "INTERNAL_ERROR"
|
|
ErrorCodeBadRequest = "BAD_REQUEST"
|
|
ErrorCodeConflict = "CONFLICT"
|
|
)
|
|
|
|
// SuccessResponse sends a successful response with data
|
|
func SuccessResponse(c *gin.Context, statusCode int, data interface{}) {
|
|
c.JSON(statusCode, Response{
|
|
Success: true,
|
|
Data: data,
|
|
})
|
|
}
|
|
|
|
// ErrorResponse sends an error response
|
|
func ErrorResponse(c *gin.Context, statusCode int, errorCode string, message string) {
|
|
c.JSON(statusCode, Response{
|
|
Success: false,
|
|
Error: &ErrorInfo{
|
|
Code: errorCode,
|
|
Message: message,
|
|
},
|
|
})
|
|
}
|
|
|
|
// BadRequestResponse sends a 400 Bad Request response
|
|
func BadRequestResponse(c *gin.Context, message string) {
|
|
ErrorResponse(c, http.StatusBadRequest, ErrorCodeBadRequest, message)
|
|
}
|
|
|
|
// ValidationErrorResponse sends a 400 Bad Request response for validation errors
|
|
func ValidationErrorResponse(c *gin.Context, message string) {
|
|
ErrorResponse(c, http.StatusBadRequest, ErrorCodeValidation, message)
|
|
}
|
|
|
|
// NotFoundResponse sends a 404 Not Found response
|
|
func NotFoundResponse(c *gin.Context, message string) {
|
|
ErrorResponse(c, http.StatusNotFound, ErrorCodeNotFound, message)
|
|
}
|
|
|
|
// UnauthorizedResponse sends a 401 Unauthorized response
|
|
func UnauthorizedResponse(c *gin.Context, message string) {
|
|
ErrorResponse(c, http.StatusUnauthorized, ErrorCodeUnauthorized, message)
|
|
}
|
|
|
|
// ForbiddenResponse sends a 403 Forbidden response
|
|
func ForbiddenResponse(c *gin.Context, message string) {
|
|
ErrorResponse(c, http.StatusForbidden, ErrorCodeForbidden, message)
|
|
}
|
|
|
|
// InternalErrorResponse sends a 500 Internal Server Error response
|
|
func InternalErrorResponse(c *gin.Context, message string) {
|
|
ErrorResponse(c, http.StatusInternalServerError, ErrorCodeInternal, message)
|
|
}
|
|
|
|
// ConflictResponse sends a 409 Conflict response
|
|
func ConflictResponse(c *gin.Context, message string) {
|
|
ErrorResponse(c, http.StatusConflict, ErrorCodeConflict, message)
|
|
}
|