Gin and your data · 7 MIN READ
NDJSON imports in Gin: cap the body, decode one bounded line at a time, report each row by its line number
Build an NDJSON import endpoint that bounds the body and each line, validates rows one at a time and returns a per-line report whose status matches what was written.
A bulk import receives the largest bodies your service will ever see, from clients that may have produced part of the file wrong. Reading it whole turns file size into memory, and one bad row into an unexplained 400. Newline-delimited JSON lets the handler work one record at a time: bound the request, bound each line, judge each row on its own, and tell the client exactly which lines were written.
gin · A MAP OF THE IDEA
- Cap the body
- Read one bounded line
- Decode, validate the row
- Commit or roll back
Useful when
- Memory is bounded by one line, not by the file.
- Clients get a line number and reason for every rejected row.
Watch out
- One transaction per upload holds a pooled connection at the client's pace.
- Partial mode needs idempotent rows so a resend does not duplicate.
Implementation & operation cost: A line reader, a per-row report and a transaction that stays open for the upload; large files usually graduate to an asynchronous job.
Why ShouldBindJSON and io.ReadAll fail on a file
In Gin v1.12.0, c.ShouldBindJSON hands the body to binding.JSON, which makes a single Decode call and then validates. On an NDJSON body it binds the first record, returns nil and never reads the other lines; the last line of the program below shows exactly that. Binding a []Product from a JSON array works, but it holds the whole file as Go values before validation starts, and one type error fails the entire decode without a line number. io.ReadAll followed by a split has the same memory profile. One json.Decoder over the whole stream is closer, but it accepts records that span lines or share one, reports byte offsets instead of line numbers, buffers each value whole however large it is, and after a syntax error it keeps returning that error, so one broken line ends the import. NDJSON offers a framing to exploit: one JSON value per line, so each line can be read, decoded and judged on its own.
Three bounds: the body, each line and the row count
The handler wraps the body in http.MaxBytesReader, reads it through a bufio.Reader whose buffer is exactly the line limit, and stops after maxRows rows. ReadSlice returns bufio.ErrBufferFull when a line does not fit; the loop then discards the rest of that line chunk by chunk, so an oversized record costs one buffer of memory and becomes a rejected row instead of a failed request. Each valid row goes into a transaction, and the mode decides whether it commits. main sends the same file in both modes, then a body over the cap, then the file to ShouldBindJSON.
package main
import (
"bufio"
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"reflect"
"strings"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"github.com/go-playground/validator/v10"
)
const (
maxBody = 1 << 10 // whole request; a real service allows megabytes
maxLine = 120 // one record, newline included
maxRows = 1000 // bounds the transaction and the report
)
type Product struct {
SKU string `json:"sku" binding:"required,alphanum,max=12"`
Name string `json:"name" binding:"required,max=40"`
PriceCents int `json:"price_cents" binding:"gt=0"`
}
type Row struct {
Line int `json:"line"`
Status string `json:"status"` // "valid" or "rejected"
SKU string `json:"sku,omitempty"`
Reason string `json:"reason,omitempty"`
}
type Report struct {
Mode string `json:"mode"`
Imported int `json:"imported"`
Rows []Row `json:"rows"`
}
// Catalog models the database; Tx models one transaction.
type Catalog struct{ items map[string]Product }
type Tx struct {
cat *Catalog
pending []Product
}
func (c *Catalog) Begin() *Tx { return &Tx{cat: c} }
func (t *Tx) Put(p Product) { t.pending = append(t.pending, p) }
func (t *Tx) Rollback() { t.pending = nil }
func (t *Tx) Commit() (n int) {
for _, p := range t.pending {
t.cat.items[p.SKU] = p
}
n, t.pending = len(t.pending), nil
return n
}
var errTooManyRows = errors.New("too many rows")
// readLines calls fn once per non-blank line. A line longer than limit bytes is
// reported with a nil slice and skipped without ever being held in memory.
func readLines(r io.Reader, limit int, fn func(n int, line []byte) error) error {
br := bufio.NewReaderSize(r, limit)
for n := 1; ; n++ {
line, err := br.ReadSlice('\n')
tooLong := errors.Is(err, bufio.ErrBufferFull)
for errors.Is(err, bufio.ErrBufferFull) {
_, err = br.ReadSlice('\n') // discard the rest of the line
}
if err != nil && err != io.EOF {
return err // *http.MaxBytesError or a broken connection
}
if tooLong {
line = nil
}
if tooLong || len(bytes.TrimSpace(line)) > 0 { // blank lines count, but are skipped
if ferr := fn(n, line); ferr != nil {
return ferr
}
}
if err == io.EOF {
return nil
}
}
}
// decodeRow decodes exactly one JSON object and validates it with Gin's validator.
func decodeRow(line []byte) (Product, string) {
var p Product
dec := json.NewDecoder(bytes.NewReader(line))
dec.DisallowUnknownFields()
if err := dec.Decode(&p); err != nil {
var syn *json.SyntaxError
var typ *json.UnmarshalTypeError
switch {
case errors.As(err, &syn), errors.Is(err, io.ErrUnexpectedEOF):
return p, "invalid JSON"
case errors.As(err, &typ):
return p, typ.Field + " has the wrong type"
default:
return p, strings.TrimPrefix(err.Error(), "json: ")
}
}
if dec.Decode(new(json.RawMessage)) != io.EOF {
return p, "more than one JSON value on the line"
}
if err := binding.Validator.ValidateStruct(&p); err != nil {
var ves validator.ValidationErrors
if errors.As(err, &ves) {
return p, ves[0].Field() + " fails " + ves[0].Tag()
}
return p, "invalid"
}
return p, ""
}
func importProducts(cat *Catalog) gin.HandlerFunc {
return func(c *gin.Context) {
if c.ContentType() != "application/x-ndjson" {
c.JSON(http.StatusUnsupportedMediaType, gin.H{"error": "send application/x-ndjson"})
return
}
mode := c.DefaultQuery("mode", "all")
if mode != "all" && mode != "partial" {
c.JSON(http.StatusBadRequest, gin.H{"error": "mode is all or partial"})
return
}
body := http.MaxBytesReader(c.Writer, c.Request.Body, maxBody)
tx := cat.Begin()
rep := Report{Mode: mode, Rows: []Row{}}
seen := map[string]int{} // sku -> first line, to catch duplicates in one file
valid := 0
err := readLines(body, maxLine, func(n int, line []byte) error {
if len(rep.Rows) == maxRows {
return errTooManyRows
}
if line == nil {
rep.Rows = append(rep.Rows, Row{Line: n, Status: "rejected", Reason: fmt.Sprintf("longer than %d bytes", maxLine)})
return nil
}
p, reason := decodeRow(line)
if first, dup := seen[p.SKU]; reason == "" && dup {
reason = fmt.Sprintf("duplicate sku %s, first on line %d", p.SKU, first)
}
if reason != "" {
rep.Rows = append(rep.Rows, Row{Line: n, Status: "rejected", Reason: reason})
return nil
}
seen[p.SKU] = n
tx.Put(p) // the database holds pending rows, not the handler
valid++
rep.Rows = append(rep.Rows, Row{Line: n, Status: "valid", SKU: p.SKU})
return nil
})
var tooBig *http.MaxBytesError
switch {
case errors.As(err, &tooBig):
tx.Rollback()
c.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": fmt.Sprintf("body exceeds %d bytes", tooBig.Limit)})
return
case errors.Is(err, errTooManyRows):
tx.Rollback()
c.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": fmt.Sprintf("more than %d rows", maxRows)})
return
case err != nil:
tx.Rollback()
c.JSON(http.StatusBadRequest, gin.H{"error": "could not read body"})
return
case len(rep.Rows) == 0:
tx.Rollback()
c.JSON(http.StatusBadRequest, gin.H{"error": "no rows"})
return
}
if valid == 0 || (mode == "all" && valid < len(rep.Rows)) {
tx.Rollback() // 422 always means nothing was written
c.JSON(http.StatusUnprocessableEntity, rep)
return
}
rep.Imported = tx.Commit() // 200 means every row marked valid was written
c.JSON(http.StatusOK, rep)
}
}
func main() {
gin.SetMode(gin.TestMode)
if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
v.RegisterTagNameFunc(func(f reflect.StructField) string {
name, _, _ := strings.Cut(f.Tag.Get("json"), ",")
return name
})
}
cat := &Catalog{items: map[string]Product{}}
r := gin.New()
r.POST("/products/import", importProducts(cat))
file := strings.Join([]string{
`{"sku":"MUG1","name":"Gopher mug","price_cents":1200}`,
`{"sku":"CAP2","name":"Cap","price_cents":0}`,
`{"sku":"PIN3","name":"Pin","price_cents":300,"color":"red"}`,
`{"sku":"HAT4","name":"Hat",`,
`{"sku":"TEE5","name":"` + strings.Repeat("x", 100) + `","price_cents":2500}`,
`{"sku":"MUG1","name":"Mug again","price_cents":900}`,
``,
`{"sku":"PIN3","name":"Pin","price_cents":300}`,
}, "\n") + "\n"
send := func(mode, body string) (int, Report, string) {
req := httptest.NewRequest("POST", "/products/import?mode="+mode, strings.NewReader(body))
req.Header.Set("Content-Type", "application/x-ndjson")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
var rep Report
_ = json.Unmarshal(w.Body.Bytes(), &rep)
return w.Code, rep, w.Body.String()
}
code, rep, _ := send("all", file)
fmt.Println("mode=all:", code, "imported:", rep.Imported, "catalog:", len(cat.items))
for _, row := range rep.Rows {
if row.Status == "valid" {
fmt.Printf(" line %d valid %s\n", row.Line, row.SKU)
} else {
fmt.Printf(" line %d rejected: %s\n", row.Line, row.Reason)
}
}
code, rep, _ = send("partial", file)
fmt.Println("mode=partial:", code, "imported:", rep.Imported, "catalog:", len(cat.items))
big := strings.Repeat(`{"sku":"MUG1","name":"Gopher mug","price_cents":1200}`+"\n", 25)
code, _, raw := send("partial", big)
fmt.Println("oversized body:", code, raw, "catalog:", len(cat.items))
// The usual binder on the same body: one Decode call, the rest is ignored.
c, _ := gin.CreateTestContext(httptest.NewRecorder())
c.Request = httptest.NewRequest("POST", "/", strings.NewReader(file))
var first Product
err := c.ShouldBindJSON(&first)
fmt.Println("ShouldBindJSON on NDJSON: err =", err, "sku =", first.SKU)
}Line 2 fails the gt=0 rule from its binding tag, line 3 carries a field the struct does not declare, and line 4 is a record cut short, which the decoder reports as io.ErrUnexpectedEOF rather than a syntax error. Line 5 is over 120 bytes and is never decoded at all. Line 6 is valid JSON but repeats the SKU from line 1, a rule only the handler can check. Line 7 is blank: skipped, but still counted, so the report uses the numbers an editor shows. With mode=all one rejected row rolls the transaction back and the answer is 422; with mode=partial the two valid rows commit with 200. The 25-line body trips MaxBytesReader partway through, the handler rolls back the rows it had already staged, and the catalog stays at two items.
Decode one line strictly and reuse Gin's validator
decodeRow gives every line its own json.Decoder. DisallowUnknownFields is set on that decoder alone, so the strictness applies to this endpoint without flipping the process-wide binding.EnableDecoderDisallowUnknownFields; the binding-limits lesson discusses when strict input is the right contract. A second Decode must return io.EOF, which rejects two values on one line yet tolerates the trailing carriage return of CRLF files, because JSON treats it as whitespace. Validation reuses the binding tags a ShouldBindJSON handler would use: binding.Validator is the StructValidator Gin itself calls, and ValidateStruct runs it on one row. Registering a tag-name function, as in the custom-validators lesson, makes errors say price_cents rather than PriceCents. encoding/json has no typed error for an unknown field, so the program trims the json: prefix from the message; keep that mapping in one function so a reworded message in a future release is a one-line fix.
All-or-nothing or partial: give each status one meaning
Decide what each status code promises and keep it true in both modes. 422 Unprocessable Content means nothing was written: in mode=all because at least one row was rejected, in mode=partial because no row was valid. 200 means every row the report marks valid was written. 413 means the request itself was too large, by bytes or by rows, and nothing was written in either mode, because a request-level failure must never leave half a file behind. 415 answers a body that is not application/x-ndjson, and 400 a bad mode or an empty file. Avoid 207 Multi-Status: it comes from WebDAV, whose body is an XML multistatus document, and generic clients attach no meaning to it in a JSON API. Default to all-or-nothing, because a client can retry it blindly. Partial mode suits large hand-edited files, but the client must read the report, and resending a corrected file has to be safe: make rows idempotent, for example an upsert keyed by SKU, and accept an Idempotency-Key for retries of the same request, as the idempotency-keys lesson describes.
Let the database hold the pending rows
Tx stands in for a database transaction: the handler streams rows into it and never holds the file itself, and rolling back on every request-level error is what keeps a 413 honest. With PostgreSQL that is an INSERT per row or per batch inside one transaction, or COPY into a staging table followed by a single INSERT ... SELECT. The systems.transaction-boundary lesson explains why a use case rather than the handler should own that transaction; the program opens it in the handler only to stay short. A transaction that lasts as long as an upload runs at the client's pace: a slow client keeps a pooled connection and its locks busy, and http.Server.ReadTimeout, which covers reading the whole body, may cut the request off. http.ResponseController.SetReadDeadline can extend it for this route only. Past a few megabytes, store the file and process it as a job behind 202, which the async-jobs lesson builds. One detail of MaxBytesReader under Gin: net/http marks the connection for closing when the limit is hit only if it receives its own response writer, through an unexported method that c.Writer cannot forward. With c.Writer the server applies its general rule when the 413 is written instead: it drains up to 256 KiB of unread body or closes the connection.
Test the framing, not only a happy file
Assert line numbers and reasons, not just counts. Cover a blank line, CRLF endings, a last line without a newline, a line exactly at the limit and one byte over, a record split across two lines, two records on one line, a UTF-8 byte order mark at the start, which makes line 1 invalid JSON unless you strip it deliberately, a body over the cap in each mode and a row count over maxRows. After every rejected request, assert that the store is unchanged. Wrap test bodies in testing/iotest.OneByteReader to prove the line reader copes with short reads, since a network delivers bytes in arbitrary chunks. From a shell, send files with --data-binary.
curl -i -X POST 'http://localhost:8080/products/import?mode=partial' \
-H 'Content-Type: application/x-ndjson' \
--data-binary @products.ndjsonRun this against the service in your own development environment. --data-binary sends the file byte for byte; -d @products.ndjson would strip carriage returns and newlines, so the server would see one long line, reject it as over the line limit and, with no valid row, answer 422. -i prints the status line before the JSON report, so you can check that the status follows the rules above.
TAKE THIS WITH YOU
Cap the body with http.MaxBytesReader, read NDJSON one bounded line at a time, decode each line strictly and validate it with Gin's validator, and let the status say what was written: 422 nothing, 200 every valid row, 413 nothing because the request was too large.
Check your understanding
In Gin v1.12.0, what does c.ShouldBindJSON(&p) do when the request body is NDJSON holding many valid records?
Go to the source
Progress stays in this browser. No account needed.