| 123456789101112131415161718192021222324252627282930313233 |
- package myhandle
-
- import (
- "encoding/json"
- "net/http"
- )
-
- // 最简单的 queryHandler,只处理 []byte 返回
- func QueryHandlerBytes[T any, F any](
- w http.ResponseWriter,
- r *http.Request,
- factory F,
- handlerFunc func(F, T) []byte,
- ) {
- // 解析请求参数
- 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
- }
-
- // 调用业务逻辑函数
- csvData := handlerFunc(factory, req)
-
- // 直接返回 CSV 数据(包含错误信息时也会被正确处理)
- w.Header().Set("Content-Type", "text/csv")
- w.Header().Set("Content-Disposition", "attachment; filename=query_result.csv")
- w.Write(csvData)
- }
|