| 1234567891011121314151617181920212223242526272829303132333435363738 |
- package util
-
- import (
- "encoding/json"
- "net/http"
- "time"
-
- "git.x2erp.com/qdy/go-base/ctx"
- "git.x2erp.com/qdy/go-base/model/response"
- )
-
- // queryHandler - 最简单的版本
- func QueryHandlerJson[T any, F any](
- w http.ResponseWriter,
- r *http.Request,
- factory F,
- handlerFunc func(F, T, *ctx.RequestContext) *response.QueryResult[[]map[string]interface{}],
- ) {
- // 解析请求参数
- var req T
- if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
- // 如果解析失败,也返回 QueryResult 格式
- w.Header().Set("Content-Type", "application/json")
- json.NewEncoder(w).Encode(&response.QueryResult[[]map[string]interface{}]{
- Success: false,
- Error: "Invalid request body: " + err.Error(),
- Time: time.Now().Format(time.RFC3339),
- })
- return
- }
-
- // 执行业务逻辑
- result := handlerFunc(factory, req, ctx.GetContext(r))
-
- // 设置头,写入结果
- w.Header().Set("Content-Type", "application/json")
- json.NewEncoder(w).Encode(result)
- }
|