Няма описание
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

query_handler_bytes.go 834B

123456789101112131415161718192021222324252627282930313233
  1. package myhandle
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. )
  6. // 最简单的 queryHandler,只处理 []byte 返回
  7. func QueryHandlerBytes[T any, F any](
  8. w http.ResponseWriter,
  9. r *http.Request,
  10. factory F,
  11. handlerFunc func(F, T) []byte,
  12. ) {
  13. // 解析请求参数
  14. var req T
  15. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  16. // 返回 CSV 格式的错误信息
  17. errorCSV := "error,Invalid request body\n"
  18. w.Header().Set("Content-Type", "text/csv")
  19. w.WriteHeader(http.StatusBadRequest)
  20. w.Write([]byte(errorCSV))
  21. return
  22. }
  23. // 调用业务逻辑函数
  24. csvData := handlerFunc(factory, req)
  25. // 直接返回 CSV 数据(包含错误信息时也会被正确处理)
  26. w.Header().Set("Content-Type", "text/csv")
  27. w.Header().Set("Content-Disposition", "attachment; filename=query_result.csv")
  28. w.Write(csvData)
  29. }