spark-server/internal/transport/http/respond/respond.go
2026-09-18 14:50:41 +08:00

40 lines
1.1 KiB
Go

package respond
import (
"net/http"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"spark-server/internal/infrastructure/logger"
"spark-server/internal/pkg/errs"
"spark-server/internal/pkg/i18n"
"spark-server/internal/pkg/reply"
"spark-server/internal/pkg/reqctx"
"spark-server/internal/pkg/validate"
)
func JSON(c *gin.Context, data any) {
c.JSON(http.StatusOK, reply.Stamp(c.Request.Context(), reply.OK(data)))
}
func JSONError(c *gin.Context, err error) {
if app, ok := errs.AsAppError(err); ok && app.LogPrint {
logger.From(c.Request.Context()).Error("app_error",
zap.String("code", app.Code),
zap.String("msg", app.Msg),
zap.String("inner_msg", app.InnerMsg),
)
}
c.JSON(http.StatusOK, reply.FromContext(c.Request.Context(), err))
}
// BindJSON decodes JSON then runs go-playground/validator. label/errmsg are i18n keys.
func BindJSON(c *gin.Context, dst any) error {
lang := reqctx.Lang(c.Request.Context())
if err := c.ShouldBindJSON(dst); err != nil {
return errs.ErrInvalidArgument.WithMsg(i18n.T(lang, i18n.KeyValidateInvalidJSON, nil))
}
return validate.StructLang(lang, dst)
}