58 lines
971 B
Go
Raw Normal View History

2025-04-18 17:17:23 +08:00
package context
import (
"admin/internal/errcode"
"admin/lib/web"
2025-04-22 15:46:48 +08:00
"admin/lib/xlog"
2025-04-18 17:17:23 +08:00
"context"
2025-04-22 15:46:48 +08:00
"github.com/gin-gonic/gin"
2025-04-18 17:17:23 +08:00
)
type WebContext struct {
context.Context
2025-04-22 15:46:48 +08:00
rawCtx *gin.Context
alreadySetRsp bool
2025-04-18 17:17:23 +08:00
}
2025-04-22 15:46:48 +08:00
func NewWebContext(rawCtx *gin.Context) web.IContext {
return &WebContext{rawCtx: rawCtx}
2025-04-18 17:17:23 +08:00
}
func (ctx *WebContext) Ok(data any) {
2025-04-22 15:46:48 +08:00
if ctx.alreadySetRsp {
return
}
ctx.rawCtx.JSON(200, map[string]any{
2025-04-18 17:17:23 +08:00
"code": 200,
"msg": "",
"data": data,
})
2025-04-22 15:46:48 +08:00
ctx.alreadySetRsp = true
2025-04-18 17:17:23 +08:00
}
func (ctx *WebContext) Fail(err error) {
2025-04-22 15:46:48 +08:00
if ctx.alreadySetRsp {
return
}
2025-04-18 17:17:23 +08:00
code, stack, msg := errcode.ParseError(err)
2025-04-22 15:46:48 +08:00
ctx.rawCtx.JSON(200, map[string]any{
2025-04-18 17:17:23 +08:00
"code": code,
"stack": stack,
"msg": msg,
"data": "",
})
2025-04-22 15:46:48 +08:00
ctx.alreadySetRsp = true
2025-04-18 17:17:23 +08:00
}
2025-04-22 15:46:48 +08:00
func (ctx *WebContext) HandleError(path string, err error) {
xlog.Errorf("path:%v handle error:%v ", path, err)
ctx.Fail(err)
2025-04-18 17:17:23 +08:00
}
2025-04-22 15:46:48 +08:00
func (ctx *WebContext) HandleSuccess(rspData any) {
ctx.Ok(rspData)
2025-04-18 17:17:23 +08:00
}