awesome-back/internal/handler/response.go

56 lines
1.1 KiB
Go

package handler
import (
"errors"
"net/http"
appErr "code.linberg.su/linberg/awesome-back/pkg/errors"
"github.com/gin-gonic/gin"
)
type Response struct {
Success bool `json:"success"`
Data interface{} `json:"data,omitempty"`
Error string `json:"error,omitempty"`
Message string `json:"message,omitempty"`
}
func Success(c *gin.Context, data interface{}) {
c.JSON(http.StatusOK, Response{
Success: true,
Data: data,
})
}
func Created(c *gin.Context, data interface{}) {
c.JSON(http.StatusCreated, Response{
Success: true,
Data: data,
})
}
func Error(c *gin.Context, err error) {
var appErr *appErr.AppError
if errors.As(err, &appErr) {
statusCode := appErr.Code
if statusCode == 0 {
statusCode = http.StatusInternalServerError
}
c.JSON(statusCode, Response{
Success: false,
Error: appErr.Message,
})
return
}
// Ошибка по умолчанию
c.JSON(http.StatusInternalServerError, Response{
Success: false,
Error: "Internal server error",
})
}
// Аналогично для PastryHandler и OrderHandler...