Gin and your data · 8 MIN READ

Streaming CSV exports in Gin: keyset pages, two flushes, formula-safe cells and an abort on late failure

Stream a large CSV from a Gin handler page by page with a safe download filename and formula-safe cells, and make a failure after the first byte visible to the client.

An export of a million rows should cost the server one page of rows at a time, not a million rows of memory and a long silence before the first byte. Writing CSV straight into c.Writer and flushing after every page achieves that. It also changes the error model: once the first page is on the wire the status line has gone, so a database failure on page forty can no longer become a 500, and the handler needs another way to tell the client the file is incomplete.

gin · A MAP OF THE IDEA

  1. Check, fetch page one
  2. Commit the headers
  3. Write a page, flush twice
  4. Abort on late failure

Useful when

  • Memory and query cost stay at one page for any export size.
  • Bytes flow from the start, so idle timeouts do not fire.

Watch out

  • Errors after the first byte cannot change the status code.
  • Pages read at different moments are not one snapshot.

Implementation & operation cost: A keyset query per page, a deliberate middleware order and a client contract for spotting truncation; strict consistency needs a long read-only transaction or a pre-built file.

01

Build the file in memory and you pay three times

The obvious export loads every row, renders the CSV into a buffer and calls c.Data. Memory grows with the export, the first byte waits for the last row, and proxies and browsers with idle timeouts can give up on a large account before anything arrives, while one query materializes the whole result. Streaming fixes all three: read one keyset page, write it, flush it, repeat. The pagination lesson explains why pages of rows after the last key stay fast and stable where OFFSET pages slow down and drift. Two buffers sit between csv.Writer.Write and the network. csv.NewWriter wraps its destination in a 4 KiB bufio.Writer, which csv.Writer.Flush empties into c.Writer, and net/http keeps a 2 KiB buffer of its own, which c.Writer.Flush pushes onto the connection. Calling both after each page keeps delivery steady; skipping the second leaves bytes waiting until net/http's buffer happens to fill.

02

An export handler and the ways it can end

The handler fetches the first page before it writes anything, sets the headers, then loops: write a page, flush both buffers, stop on a short page, a canceled context or a store error. main first prints the Content-Disposition values for three list names, then runs a full export, a client that disconnects during page one, a store that is down before the first byte and a store that fails on page two, once with Gin's Recovery alone and once with abortPassthrough in front of it.

go
package main

import (
	"context"
	"encoding/csv"
	"errors"
	"fmt"
	"io"
	"mime"
	"net/http"
	"net/http/httptest"
	"strconv"
	"strings"
	"unicode"

	"github.com/gin-gonic/gin"
)

type Contact struct {
	ID                int
	Name, Email, Note string
}

// Store models a database read with keyset pagination: rows after a key, in key order.
type Store struct {
	rows   []Contact // sorted by ID
	failAt int       // page number that fails; 0 means never
	served int
	onPage func(page int)
}

func (s *Store) Page(ctx context.Context, afterID, limit int) ([]Contact, error) {
	if err := ctx.Err(); err != nil {
		return nil, err
	}
	s.served++
	if s.served == s.failAt {
		return nil, errors.New("replica connection lost")
	}
	var out []Contact
	for _, r := range s.rows {
		if r.ID > afterID && len(out) < limit {
			out = append(out, r)
		}
	}
	if s.onPage != nil {
		s.onPage(s.served)
	}
	return out, nil
}

// safeCell keeps spreadsheet apps from evaluating user text as a formula.
func safeCell(s string) string {
	if s != "" && strings.ContainsRune("=+-@\t\r\n", rune(s[0])) {
		return "'" + s
	}
	return s
}

// exportName builds a filename from user input: letters, digits, space, - _ only.
func exportName(list string) string {
	name := strings.Map(func(r rune) rune {
		if unicode.IsLetter(r) || unicode.IsDigit(r) || strings.ContainsRune(" -_", r) {
			return r
		}
		return -1
	}, list)
	if name = strings.TrimSpace(name); name == "" || len(name) > 60 {
		name = "contacts"
	}
	return name + ".csv"
}

func exportContacts(s *Store, pageSize int) gin.HandlerFunc {
	return func(c *gin.Context) {
		ctx := c.Request.Context()
		page, err := s.Page(ctx, 0, pageSize)
		if err != nil { // nothing is written yet, so the status can still say so
			c.JSON(http.StatusServiceUnavailable, gin.H{"error": "export unavailable"})
			return
		}
		disp := mime.FormatMediaType("attachment", map[string]string{"filename": exportName(c.Query("list"))})
		if disp == "" {
			disp = "attachment; filename=contacts.csv"
		}
		c.Header("Content-Type", "text/csv; charset=utf-8")
		c.Header("Content-Disposition", disp)
		c.Header("X-Content-Type-Options", "nosniff")
		c.Status(http.StatusOK)

		w := csv.NewWriter(c.Writer)
		_ = w.Write([]string{"id", "name", "email", "note"})
		for {
			for _, ct := range page {
				_ = w.Write([]string{strconv.Itoa(ct.ID), safeCell(ct.Name), safeCell(ct.Email), safeCell(ct.Note)})
			}
			w.Flush() // csv's buffer -> c.Writer; the first flush commits 200
			if w.Error() != nil {
				return // the client stopped reading; nobody is left to tell
			}
			c.Writer.Flush() // c.Writer -> the connection
			if len(page) < pageSize {
				return // short page: the export is complete
			}
			page, err = s.Page(ctx, page[len(page)-1].ID, pageSize)
			if ctx.Err() != nil {
				return // client gone or server shutting down: stop reading the database
			}
			if err != nil {
				_ = c.Error(err) // for the access log
				panic(http.ErrAbortHandler)
			}
		}
	}
}

// abortPassthrough must run outside gin.Recovery, which swallows http.ErrAbortHandler.
func abortPassthrough(c *gin.Context) {
	c.Next()
	for _, e := range c.Errors {
		if errors.Is(e.Err, http.ErrAbortHandler) {
			panic(http.ErrAbortHandler) // net/http now breaks the connection
		}
	}
}

// serve is what net/http does around a handler: an ErrAbortHandler panic means
// "close the connection without finishing the body".
func serve(h http.Handler, req *http.Request) (w *httptest.ResponseRecorder, aborted bool) {
	w = httptest.NewRecorder()
	defer func() {
		if rec := recover(); rec != nil {
			if rec != http.ErrAbortHandler {
				panic(rec)
			}
			aborted = true
		}
	}()
	h.ServeHTTP(w, req)
	return w, false
}

func newRouter(s *Store, passthrough bool) *gin.Engine {
	r := gin.New()
	if passthrough {
		r.Use(abortPassthrough)
	}
	r.Use(gin.Recovery())
	r.GET("/contacts.csv", exportContacts(s, 3))
	return r
}

func main() {
	gin.SetMode(gin.TestMode)
	gin.DefaultErrorWriter = io.Discard // keep Recovery's log out of the demo
	rows := []Contact{
		{1, "Avery", "avery@example.com", `=HYPERLINK("https://attacker.example","invoice")`},
		{2, "Blake, Jr.", "blake@example.com", "+44 20 7946 0000"},
		{3, "Casey", "casey@example.com", "-2+3"},
		{4, "Devon", "devon@example.com", "@SUM(A1:A9)"},
		{5, "Emery", "emery@example.com", `says "hi"`},
		{6, "Finley", "finley@example.com", "plain note"},
		{7, "Gray", "gray@example.com", ""},
	}
	for _, list := range []string{"Q4 leads", "Zoë's list", "../../etc/passwd\r\nX: 1"} {
		fmt.Printf("%q -> %s\n", list, mime.FormatMediaType("attachment", map[string]string{"filename": exportName(list)}))
	}

	s := &Store{rows: rows}
	w, _ := serve(newRouter(s, true), httptest.NewRequest("GET", "/contacts.csv?list=Q4+leads", nil))
	fmt.Println(w.Code, w.Header().Get("Content-Type"), "pages:", s.served, "flushed:", w.Flushed)
	fmt.Print(w.Body.String())

	ctx, disconnect := context.WithCancel(context.Background())
	s = &Store{rows: rows, onPage: func(int) { disconnect() }}
	w, aborted := serve(newRouter(s, true), httptest.NewRequest("GET", "/contacts.csv", nil).WithContext(ctx))
	fmt.Println("client gone after page 1:", w.Code, "pages:", s.served, "lines:", strings.Count(w.Body.String(), "\n"), "aborted:", aborted)

	s = &Store{rows: rows, failAt: 1}
	w, _ = serve(newRouter(s, true), httptest.NewRequest("GET", "/contacts.csv", nil))
	fmt.Println("store down before first byte:", w.Code, w.Body.String())

	for _, passthrough := range []bool{false, true} {
		s = &Store{rows: rows, failAt: 2}
		w, aborted = serve(newRouter(s, passthrough), httptest.NewRequest("GET", "/contacts.csv", nil))
		fmt.Println("store fails on page 2, passthrough", passthrough, "->", w.Code, "lines:", strings.Count(w.Body.String(), "\n"), "aborted:", aborted)
	}
}
Read the code

Seven contacts at three per page take three queries; the third page is short, which ends the loop without a fourth. Every user-supplied cell that starts with =, +, -, @, tab, carriage return or line feed gains a leading apostrophe, and encoding/csv quotes the fields that contain commas or quotes and doubles the inner quotes. When the request context is canceled during page one, the handler still writes that page, then its next Page call returns the context error and the loop ends without querying again. A store that fails before the first byte still gets an honest 503. On page two the status is already 200, so the only signal left is the connection itself. With Recovery alone the response ends normally after four lines, which a client cannot tell from a complete export; with abortPassthrough the ErrAbortHandler panic reaches serve, which plays the part of net/http.

03

Filenames and cells are user input too

Content-Disposition carries a filename the browser proposes to the user, so build it like any other output. exportName keeps letters, digits, spaces, hyphens and underscores, falls back to a fixed name when nothing usable is left or the result is too long, and appends the extension itself, so path separators and CR LF never reach the header. mime.FormatMediaType then picks the encoding: a bare token, a quoted string with escaped quotes for ASCII with spaces, or the RFC 2231 form filename*=utf-8'' with percent-encoding for anything else. RFC 6266 defines that filename* parameter for HTTP and current browsers read it. FormatMediaType returns an empty string for an invalid type or parameter name, so keep the fallback. Gin's c.FileAttachment is no substitute: it serves a file from disk, and for non-ASCII names v1.12.0 encodes with url.QueryEscape, which writes spaces as + that RFC 8187 decoding keeps literally, so the browser saves Zoë+list.csv. CSV injection is the second risk. Spreadsheet apps can evaluate a cell that starts with =, +, - or @ as a formula, and OWASP's list adds control characters such as tab and carriage return, so an exported note can build links that leak neighboring cells. OWASP recommends prefixing such cells with a single quote, as safeCell does, while the encoder handles quotes and separators inside the field. That changes the data, so apply it only to free-text columns from users, never to values you format yourself: a negative balance would become text. Offer JSON for machine consumers that need raw values.

04

After the first byte, the status line is history

The first flush sends the 200 and the headers. From then on Gin's responseWriter ignores WriteHeader, printing a warning only in debug mode, so a c.JSON(500, ...) in the error path would append a JSON object to the CSV and still report success. Two rules follow. First, do everything that can fail cheaply before the first byte: authorize, validate parameters and run the first query, which is why the store-down case can still answer 503. Second, make a late failure visible as truncation. A panic with http.ErrAbortHandler makes net/http close the connection without the final zero-length chunk on HTTP/1.1, or reset the stream on HTTP/2, so curl, browsers and HTTP libraries report an error instead of saving a short file; net/http also skips the stack trace for that value. The surprise is gin.Recovery: v1.12.0 classifies ErrAbortHandler with broken pipes, records it with c.Error, aborts the chain and returns normally, so net/http finishes the response cleanly. abortPassthrough, registered before Recovery, finds the recorded error after c.Next returns and panics again outside Recovery's reach. Log the failure with the request ID and the last key written. Programmatic clients can also check an HTTP trailer or a final row count, but browsers ignore trailers, so the abort is the signal that works everywhere.

05

Cancellation, write deadlines and one consistent snapshot

net/http cancels the request context when the client disconnects or an HTTP/2 stream is reset. Pass that context to every query so the one in flight is canceled, and check it before the next page, or the handler keeps reading the database for nobody; a write error from csv.Writer.Error after Flush is the same signal from the other side. A long export also outlives http.Server.WriteTimeout, so renew the write deadline per page with ResponseController, as the SSE lesson does for event streams. Each page is its own statement, so the file is not a point-in-time snapshot: a row edited between pages shows whichever value its page saw. When the export must be consistent, read every page inside one read-only REPEATABLE READ transaction, which in PostgreSQL gives all its statements the same snapshot, and accept that a transaction open for the whole download delays vacuum. For very large or audited exports, generate the file as a job, which the async-jobs lesson builds, and serve the finished file with a Content-Length.

go
tx, err := db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelRepeatableRead, ReadOnly: true})
if err != nil {
	return err // still before the first byte: the handler can answer 503
}
defer tx.Rollback() // read-only: rolling back just releases the snapshot

rc := http.NewResponseController(c.Writer)
nextPage := func(afterID int64) (*sql.Rows, error) {
	// A fresh write budget per page instead of the server-wide WriteTimeout.
	if err := rc.SetWriteDeadline(time.Now().Add(30 * time.Second)); err != nil && !errors.Is(err, http.ErrNotSupported) {
		return nil, err
	}
	return tx.QueryContext(ctx, `SELECT id, name, email, note FROM contacts
		WHERE account_id = $1 AND id > $2 ORDER BY id LIMIT $3`, accountID, afterID, pageSize)
}
Read the code

This fragment runs against a real PostgreSQL database in your own environment. BeginTx with LevelRepeatableRead and ReadOnly pins one snapshot for every page, and the deferred Rollback releases it, which is all a read-only transaction needs. nextPage renews the write deadline before each page, tolerating http.ErrNotSupported from writers that cannot set one, then selects rows strictly after the last ID. With an index on (account_id, id), every page is a short range scan however deep into the export it is.

06

Test it the way a client reads it

Parse the body back with csv.NewReader and compare records rather than raw text, so a quoting change does not break tests while a content change does. Include hostile cells for every formula prefix, embedded commas, quotes and newlines, a non-ASCII list name, and page boundaries: zero rows, exactly one page, one row more than a page. Cancel mid-stream and assert that the store stopped being called, and fail both before and after the first byte. Build the test engine with the same middleware order as production, because the abort works only when abortPassthrough runs outside Recovery; a test with a different chain would pass while production silently truncates. Finally, run one integration test against a real listener and assert that reading the body of a failed export ends in an error such as io.ErrUnexpectedEOF rather than a clean EOF.

TAKE THIS WITH YOU

Fetch the first page before writing, stream CSV page by page with csv.Writer.Flush and c.Writer.Flush, stop on the request context, build Content-Disposition with mime.FormatMediaType, prefix formula-leading cells, and abort the connection on late failures from outside gin.Recovery.

Check your understanding

In Gin v1.12.0, a streaming handler panics with http.ErrAbortHandler after its first page, under gin.Recovery(). What does the client receive?

Go to the source

Progress stays in this browser. No account needed.