package response import ( "encoding/json" "fmt" "time" "git.x2erp.com/qdy/go-base/ctx" ) // TabulatorResponse Tabulator期望的响应格式 type TabulatorResponse struct { LastPage int `json:"last_page"` // 总页数 Data interface{} `json:"data"` // 数据数组 } // CreateTabulatorResponse 创建Tabulator格式的响应 func CreateTabulatorResponse[T any](data T, totalCount int, pageSize int, reqCtx *ctx.RequestContext) *QueryResult[map[string]interface{}] { // 计算总页数 lastPage := 1 if pageSize > 0 && totalCount > 0 { lastPage = (totalCount + pageSize - 1) / pageSize } // 构建Tabulator格式数据 tabulatorData := map[string]interface{}{ "last_page": lastPage, "data": data, } // 创建成功结果 result := &QueryResult[map[string]interface{}]{ Success: true, Data: tabulatorData, TotalCount: totalCount, Time: time.Now().Format(time.RFC3339), Metadata: reqCtx, } // 如果数据是数组,设置Count switch v := any(data).(type) { case []interface{}: result.Count = len(v) case []map[string]interface{}: result.Count = len(v) default: // 尝试通过反射获取长度 // 简化处理,如果无法获取长度,使用TotalCount result.Count = totalCount } return result } // AdaptToTabulator 将现有QueryResult适配为Tabulator格式 // 此函数主要用于中间件或处理器直接输出Tabulator格式 func AdaptToTabulator[T any](result *QueryResult[T], pageSize int) []byte { if !result.Success { // 错误响应格式 errorResponse := map[string]interface{}{ "error": result.Error, } if result.Message != "" { errorResponse["message"] = result.Message } jsonData, _ := json.Marshal(errorResponse) return jsonData } // 计算总页数 lastPage := 1 if pageSize > 0 && result.TotalCount > 0 { lastPage = (result.TotalCount + pageSize - 1) / pageSize } // 构建Tabulator格式响应 tabulatorResponse := map[string]interface{}{ "last_page": lastPage, "data": result.Data, } // 编码为JSON jsonData, err := json.Marshal(tabulatorResponse) if err != nil { // 编码失败,返回错误 errorResponse := map[string]interface{}{ "error": fmt.Sprintf("JSON编码失败: %v", err), } errorData, _ := json.Marshal(errorResponse) return errorData } return jsonData } // CreateTabulatorErrorResponse 创建Tabulator格式的错误响应 func CreateTabulatorErrorResponse(errorMsg string, reqCtx *ctx.RequestContext) *QueryResult[map[string]interface{}] { errorResponse := map[string]interface{}{ "error": errorMsg, } return &QueryResult[map[string]interface{}]{ Success: false, Data: errorResponse, Error: errorMsg, Time: time.Now().Format(time.RFC3339), Metadata: reqCtx, } }