package api import ( "bytes" "encoding/json" "git.sxidc.com/go-framework/baize/framework/core/infrastructure/logger" "git.sxidc.com/service-supports/fserr" "github.com/gin-gonic/gin" "io" "mime/multipart" "strings" ) type Context struct { *gin.Context } // GetFileHeaderBytes 获取传递的文件名和文件内容 func (c *Context) GetFileHeaderBytes(fileHeader *multipart.FileHeader) (string, []byte, error) { file, err := fileHeader.Open() if err != nil { return "", nil, fserr.New(err.Error()) } defer func(file multipart.File) { err := file.Close() if err != nil { logger.GetInstance().Error(fserr.New(err.Error())) return } }(file) contentBytes, err := io.ReadAll(file) if err != nil { return "", nil, fserr.New(err.Error()) } return fileHeader.Filename, contentBytes, nil } func (c *Context) GetHeaders() map[string]string { headers := make(map[string]string, 0) for key, values := range c.Request.Header { headers[key] = strings.Join(values, ",") } return headers } func (c *Context) ReadBody() ([]byte, error) { if c.Request.Body == nil { return make([]byte, 0), nil } body, err := io.ReadAll(c.Request.Body) if err != nil { return nil, fserr.New(err.Error()) } defer func(Body io.ReadCloser) { err := Body.Close() if err != nil { logger.GetInstance().Error(fserr.New(err.Error())) return } }(c.Request.Body) c.Request.Body = io.NopCloser(bytes.NewBuffer(body)) return body, nil } func (c *Context) ReplaceBody(body []byte) error { if c.Request.Body != nil { err := c.Request.Body.Close() if err != nil { return fserr.New(err.Error()) } } c.Request.Body = io.NopCloser(bytes.NewBuffer(body)) return nil } func (c *Context) ReadJsonBody(output any) error { body, err := c.ReadBody() if err != nil { return err } return json.Unmarshal(body, output) } func (c *Context) ReplaceJsonBody(body any) error { bodyBytes, err := json.Marshal(body) if err != nil { return fserr.New(err.Error()) } return c.ReplaceBody(bodyBytes) } func (c *Context) GetAllQueryParams() map[string]string { queryParams := make(map[string]string, 0) for key, values := range c.Request.URL.Query() { queryParams[key] = strings.Join(values, ",") } return queryParams } func (c *Context) GetAllPathParams() map[string]string { pathParams := make(map[string]string, 0) for _, params := range c.Params { pathParams[params.Key] = params.Value } return pathParams } const ( tenantInfoKey = "context-tenant-info" userInfoKey = "context-user-info" ) type TenantInfo interface { GetID() string GetName() string } type UserInfo interface { GetID() string GetUserName() string GetName() string } func (c *Context) GetTenantInfo() TenantInfo { tenantInfo, exist := c.Get(tenantInfoKey) if !exist { return nil } return tenantInfo.(TenantInfo) } func (c *Context) GetUserInfo() UserInfo { userInfo, exist := c.Get(userInfoKey) if !exist { return nil } return userInfo.(UserInfo) }