Add streaming CSV export for payments, users, subscriptions, activity logs, and team members with list-filter parity, RBAC permissions, and admin panel documentation. Co-authored-by: Cursor <cursoragent@cursor.com>
72 lines
1.4 KiB
Go
72 lines
1.4 KiB
Go
package response
|
|
|
|
import (
|
|
"bufio"
|
|
"encoding/csv"
|
|
"fmt"
|
|
|
|
"github.com/gofiber/fiber/v2"
|
|
)
|
|
|
|
const (
|
|
ExportBatchSize = 500
|
|
ExportMaxRows = 50000
|
|
)
|
|
|
|
// StreamCSV writes a UTF-8 CSV attachment, fetching rows in batches until a batch is empty
|
|
// or ExportMaxRows is reached.
|
|
func StreamCSV(
|
|
c *fiber.Ctx,
|
|
filename string,
|
|
headers []string,
|
|
fetchBatch func(offset, limit int32) ([][]string, error),
|
|
) error {
|
|
c.Set("Content-Type", "text/csv; charset=utf-8")
|
|
c.Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, filename))
|
|
|
|
c.Context().SetBodyStreamWriter(func(w *bufio.Writer) {
|
|
if _, err := w.Write([]byte{0xEF, 0xBB, 0xBF}); err != nil {
|
|
return
|
|
}
|
|
writer := csv.NewWriter(w)
|
|
if err := writer.Write(headers); err != nil {
|
|
return
|
|
}
|
|
|
|
var offset int32
|
|
var written int
|
|
for written < ExportMaxRows {
|
|
limit := int32(ExportBatchSize)
|
|
if remaining := ExportMaxRows - written; remaining < ExportBatchSize {
|
|
limit = int32(remaining)
|
|
}
|
|
rows, err := fetchBatch(offset, limit)
|
|
if err != nil {
|
|
return
|
|
}
|
|
if len(rows) == 0 {
|
|
break
|
|
}
|
|
for _, row := range rows {
|
|
if err := writer.Write(row); err != nil {
|
|
return
|
|
}
|
|
}
|
|
writer.Flush()
|
|
if err := writer.Error(); err != nil {
|
|
return
|
|
}
|
|
if err := w.Flush(); err != nil {
|
|
return
|
|
}
|
|
written += len(rows)
|
|
if len(rows) < int(limit) {
|
|
break
|
|
}
|
|
offset += int32(len(rows))
|
|
}
|
|
})
|
|
|
|
return nil
|
|
}
|