| 1234567891011121314151617181920212223242526272829303132333435363738394041424344 |
- package util
-
- import (
- "encoding/json"
- "fmt"
- "net/http"
-
- "git.x2erp.com/qdy/go-base/ctx"
- )
-
- // 最简单的 queryHandler,只处理 []byte 返回
- func QueryHandlerBytes[T any, F any](
- w http.ResponseWriter,
- r *http.Request,
- factory F,
- handlerFunc func(F, T, *ctx.RequestContext) ([]byte, error),
- ) {
- // 解析请求参数
-
- w.Header().Set("Content-Type", "text/csv")
- w.Header().Set("Content-Disposition", "attachment; filename=query_result.csv")
- var req T
- if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
- // 返回 CSV 格式的错误信息
- errorCSV := "error,Invalid request body\n"
- // w.Header().Set("Content-Type", "text/csv")
- w.WriteHeader(http.StatusBadRequest)
- w.Write([]byte(errorCSV))
- return
- }
-
- reqCtx := ctx.GetContext(r)
- // 调用业务逻辑函数
- csvData, err := handlerFunc(factory, req, reqCtx)
- if err != nil {
- w.WriteHeader(http.StatusBadRequest)
- w.Write([]byte(fmt.Sprintf("%v", err)))
- return
- }
- // 直接返回 CSV 数据(包含错误信息时也会被正确处理)
- //w.Header().Set("Content-Type", "text/csv")
- //w.Header().Set("Content-Disposition", "attachment; filename=query_result.csv")
- w.Write(csvData)
- }
|