package common import ( "encoding/json" "errors" "fmt" "log/slog" "net/http" "reflect" "runtime/debug" ) import ( "gorm.io/gorm" ) import ( "github.com/gin-gonic/gin" "github.com/go-playground/validator/v10" ) func HttpSuccess(c *gin.Context, data ...interface{}) { if len(data) > 0 { c.JSON(http.StatusOK, OK.Translator(GetTrans(c.GetHeader("Language"))).H(data[0])) } else { c.JSON(http.StatusOK, OK.H()) } } func ErrToH(err interface{}, locale string) gin.H { h := gin.H{} switch err.(type) { case *ResStatus: h = err.(*ResStatus).Translator(GetTrans(locale)).H() case *json.UnmarshalTypeError: utErr := err.(*json.UnmarshalTypeError) h = InvalidParam.Desc(FieldTypeError).SetParam(utErr.Field, utErr.Type.String()).Translator(GetTrans(locale)).H() case validator.ValidationErrors: for _, fieldError := range err.(validator.ValidationErrors) { return InvalidParam.Desc(ResDesc(fieldError.Error())).Translator(GetTrans(locale)).H() } default: if fmt.Sprintf("%v", err) == "EOF" { return InvalidParam.Desc("empty body").Translator(GetTrans(locale)).H() } if fmt.Sprintf("%v", err) == "unexpected EOF" { return InvalidParam.Desc("body must be in json format").Translator(GetTrans(locale)).H() } if errors.Is(err.(error), gorm.ErrRecordNotFound) { return NotExists.Translator(GetTrans(locale)).H() } slog.Error("uncaught error occurred", "type", reflect.TypeOf(err), "err", err, "stack", string(debug.Stack())) h = Unknown.Desc(ResDesc(fmt.Sprintf("%v", err))).Translator(GetTrans(locale)).H() } return h } func HttpErr(c *gin.Context, err interface{}) { h := ErrToH(err, c.GetHeader("Language")) slog.Warn("http err response", "method", c.Request.Method, "uri", c.Request.RequestURI, "msg", h) c.JSON(http.StatusOK, h) }