117 lines
2.4 KiB
Go
117 lines
2.4 KiB
Go
package context
|
||
|
||
import (
|
||
"admin/internal/errcode"
|
||
"admin/lib/web"
|
||
"admin/lib/xlog"
|
||
"context"
|
||
"fmt"
|
||
"github.com/gin-gonic/gin"
|
||
"github.com/gin-gonic/gin/render"
|
||
"net/http"
|
||
"net/url"
|
||
"strings"
|
||
)
|
||
|
||
type WebHeader struct {
|
||
UserId int `json:"UserId"` // 用户id,会与下面token解析出用户id做匹配校验
|
||
Token string `json:"Token"` // jwt token,内置一些信息
|
||
Ip string `json:"IP"`
|
||
UserName string `json:"-"`
|
||
}
|
||
|
||
type WebContext struct {
|
||
context.Context
|
||
rawCtx *gin.Context
|
||
Header *WebHeader
|
||
alreadySetRsp bool
|
||
}
|
||
|
||
func NewWebContext(rawCtx *gin.Context) web.IContext {
|
||
return &WebContext{Context: context.Background(), rawCtx: rawCtx}
|
||
}
|
||
|
||
func (ctx *WebContext) ExtractHeader() error {
|
||
header := &WebHeader{}
|
||
err := ctx.rawCtx.ShouldBindHeader(header)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
//xlog.Debugf("提取请求头:%+v", ctx.GinCtx().Request.Header)
|
||
ctx.Header = header
|
||
return nil
|
||
}
|
||
|
||
func (ctx *WebContext) IsUserLogin() bool {
|
||
return ctx.Header != nil && ctx.Header.UserId > 0
|
||
}
|
||
|
||
func (ctx *WebContext) GinCtx() *gin.Context {
|
||
return ctx.rawCtx
|
||
}
|
||
|
||
func (ctx *WebContext) Ok(data any) {
|
||
if ctx.alreadySetRsp {
|
||
return
|
||
}
|
||
|
||
ctx.rawCtx.JSON(200, map[string]any{
|
||
"code": 200,
|
||
"msg": "",
|
||
"data": data,
|
||
})
|
||
|
||
ctx.alreadySetRsp = true
|
||
}
|
||
|
||
func (ctx *WebContext) Fail(err error) {
|
||
if ctx.alreadySetRsp {
|
||
return
|
||
}
|
||
|
||
code, codeContent, stack, msg := errcode.ParseError(err)
|
||
ctx.rawCtx.JSON(200, map[string]any{
|
||
"code": code,
|
||
"stack": stack,
|
||
"msg": codeContent,
|
||
"detail_msg": msg,
|
||
"data": "",
|
||
})
|
||
|
||
ctx.alreadySetRsp = true
|
||
}
|
||
|
||
func (ctx *WebContext) OkFile(fileName string, content string) {
|
||
if ctx.alreadySetRsp {
|
||
return
|
||
}
|
||
|
||
reader := strings.NewReader(string(content))
|
||
contentLength := len(content)
|
||
contentType := ""
|
||
|
||
fileName = url.QueryEscape(fileName)
|
||
valueName := fmt.Sprintf(`"attachment; filename*=utf-8''%v"`, fileName)
|
||
extraHeaders := map[string]string{
|
||
"Content-Disposition": valueName,
|
||
"Content-Transfer-Encoding": "binary",
|
||
}
|
||
|
||
ctx.GinCtx().Render(http.StatusOK, render.Reader{
|
||
Headers: extraHeaders,
|
||
ContentType: contentType,
|
||
ContentLength: int64(contentLength),
|
||
Reader: reader,
|
||
})
|
||
|
||
ctx.alreadySetRsp = true
|
||
}
|
||
|
||
func (ctx *WebContext) HandleError(path string, err error) {
|
||
xlog.Errorf("path:%v handle error:%v ", path, err)
|
||
ctx.Fail(err)
|
||
}
|
||
func (ctx *WebContext) HandleSuccess(rspData any) {
|
||
ctx.Ok(rspData)
|
||
}
|