Bez popisu
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 1.2KB

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