Gin in the wider system · 6 MIN READ
File downloads in Gin: ServeContent for ranges and validators, a safe Content-Disposition, files opened by ID
Serve downloadable files from Gin with correct Range, If-Range, ETag and HEAD behavior, a Content-Disposition built by mime.FormatMediaType and file access confined to an os.Root.
A download endpoint looks like one line, c.File(path), and that line hides most of the behavior: byte ranges for resumed and parallel downloads, conditional requests, HEAD, the content type and the filename the browser saves. Knowing what Gin delegates to net/http and what it adds decides whether a large export resumes after a dropped connection or starts over, and whether a user-chosen filename can break the response header.
gin · A MAP OF THE IDEA
- Authorize the ID
- Open via os.Root
- Set type, ETag and name
- Hand to ServeContent
Useful when
- Resumable, parallel and conditional downloads come from the stdlib.
- Filenames with quotes and non-ASCII letters encode correctly.
Watch out
- c.File follows symlinks and lists directories; never pass user paths.
- If-Range needs a strong ETag, or resumes restart from zero.
- Gin's FileAttachment encodes spaces as + in filename*.
Implementation & operation cost: A metadata lookup per download and a stored strong validator per file; very large files also need their own write deadline or offloading to object storage.
c.File, c.FileAttachment and http.ServeContent, read from the source
In Gin v1.12.0, c.File(path) is one line: http.ServeFile(c.Writer, c.Request, path). c.FileAttachment(path, name) sets Content-Disposition and then makes the same call, and c.FileFromFS temporarily rewrites c.Request.URL.Path and runs http.FileServer. ServeFile opens the path through http.Dir, which, as its documentation warns, follows symlinks out of the directory and serves dotfiles such as .git. It rejects requests whose URL path contains a .. element with 400, redirects URL paths ending in /index.html, lists directories and sets Last-Modified but no ETag. All three paths end in the same serveContent code, so Range, If-Range, If-None-Match, If-Modified-Since and HEAD work everywhere. http.ServeContent(w, r, name, modtime, content) is the level below: you pass an io.ReadSeeker and a modification time, name is used only to guess a type, and an ETag takes part only if you set the header before the call. That makes ServeContent the right tool when files are looked up by ID, opened through os.Root or an embedded file system, or need a validator you control.
Serve by ID through ServeContent
The handler maps an export ID to a server-chosen path and a display name, opens the file through an fs.FS, checks that it is a regular, seekable file, sets Content-Type, Content-Disposition, ETag and Cache-Control, and hands over to ServeContent. An in-memory fstest.MapFS plays the file system. main sends ten requests, then compares the header Gin's FileAttachment builds with mime.FormatMediaType, using a temporary file because FileAttachment only accepts a path.
package main
import (
"fmt"
"io"
"io/fs"
"mime"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing/fstest"
"time"
"github.com/gin-gonic/gin"
)
// Export is a row from your database: the client sends only the ID.
type Export struct {
Path string // storage name chosen by the server, relative to the root
Filename string // the name the user sees; never used to open anything
ETag string // a version you already track, quoted and strong
}
var exports = map[string]Export{
"e-42": {Path: "exports/e-42.csv", Filename: `Q3 "final" résumé.csv`, ETag: `"v3"`},
}
// download serves from an fs.FS. In production that is root.FS() for an
// os.Root opened once at startup; here it is an in-memory fstest.MapFS.
func download(fsys fs.FS) gin.HandlerFunc {
return func(c *gin.Context) {
exp, ok := exports[c.Param("id")] // authorize the caller for this ID here
if !ok {
c.AbortWithStatusJSON(http.StatusNotFound, gin.H{"error": "unknown_export"})
return
}
f, err := fsys.Open(exp.Path)
if err != nil {
c.AbortWithStatusJSON(http.StatusNotFound, gin.H{"error": "unknown_export"})
return
}
defer f.Close()
info, err := f.Stat()
content, seekable := f.(io.ReadSeeker)
if err != nil || !seekable || !info.Mode().IsRegular() {
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "export_unavailable"})
return
}
h := c.Writer.Header()
h.Set("Content-Type", "text/csv; charset=utf-8") // explicit: no sniffing
h.Set("Content-Disposition", mime.FormatMediaType("attachment", map[string]string{"filename": exp.Filename}))
h.Set("ETag", exp.ETag)
h.Set("Cache-Control", "private, no-cache")
h.Set("X-Content-Type-Options", "nosniff")
http.ServeContent(c.Writer, c.Request, "", info.ModTime(), content)
}
}
func main() {
gin.SetMode(gin.TestMode)
data := "region,orders,total\neu-west,1200,98000.00\nus-east,900,71000.00\n"
fsys := fstest.MapFS{"exports/e-42.csv": &fstest.MapFile{
Data: []byte(data), ModTime: time.Date(2026, 11, 2, 9, 30, 0, 0, time.UTC)}}
r := gin.New()
r.Match([]string{http.MethodGet, http.MethodHead}, "/exports/:id", download(fsys))
send := func(label, method, path string, kv ...string) *httptest.ResponseRecorder {
req := httptest.NewRequest(method, path, nil)
for i := 0; i+1 < len(kv); i += 2 {
req.Header.Set(kv[i], kv[i+1])
}
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
h := w.Header()
line := fmt.Sprintf("%-15s %d", label, w.Code)
if n := h.Get("Content-Length"); n != "" && !strings.HasPrefix(h.Get("Content-Type"), "multipart/") {
line += " len=" + n
}
if cr := h.Get("Content-Range"); cr != "" {
line += " range=" + cr
}
if mt, _, _ := mime.ParseMediaType(h.Get("Content-Type")); mt == "multipart/byteranges" {
line += " type=" + mt
} else if w.Code == http.StatusPartialContent {
line += fmt.Sprintf(" body=%q", w.Body.String())
}
line += " etag=" + cmpOr(h.Get("ETag"), "-")
fmt.Println(line)
return w
}
first := send("GET", "GET", "/exports/e-42")
fmt.Println(" Accept-Ranges:", first.Header().Get("Accept-Ranges"))
fmt.Println(" Last-Modified:", first.Header().Get("Last-Modified"))
fmt.Println(" Content-Disposition:", first.Header().Get("Content-Disposition"))
send("HEAD", "HEAD", "/exports/e-42")
send("first 10 bytes", "GET", "/exports/e-42", "Range", "bytes=0-9")
send("last 9 bytes", "GET", "/exports/e-42", "Range", "bytes=-9")
send("two ranges", "GET", "/exports/e-42", "Range", "bytes=0-5,20-26")
send("past the end", "GET", "/exports/e-42", "Range", "bytes=500-")
send("If-Range fresh", "GET", "/exports/e-42", "Range", "bytes=20-26", "If-Range", `"v3"`)
send("If-Range stale", "GET", "/exports/e-42", "Range", "bytes=20-26", "If-Range", `"v2"`)
send("If-None-Match", "GET", "/exports/e-42", "If-None-Match", `"v3"`)
send("unknown id", "GET", "/exports/e-7")
// c.FileAttachment builds the header itself; compare it on a temp file.
tmp, err := os.CreateTemp("", "gf-export-*.csv")
if err != nil {
panic(err)
}
defer os.Remove(tmp.Name())
tmp.WriteString(data)
tmp.Close()
for _, name := range []string{`Q3 "final".csv`, "résumé 2026.csv"} {
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodGet, "/download", nil)
c.Request.Header.Set("Range", "bytes=0-5")
c.FileAttachment(tmp.Name(), name)
fmt.Printf("FileAttachment %d %s\n", w.Code, w.Header().Get("Content-Disposition"))
fmt.Printf("FormatMediaType %s\n", mime.FormatMediaType("attachment", map[string]string{"filename": name}))
}
}
func cmpOr(s, fallback string) string {
if s == "" {
return fallback
}
return s
}The full GET advertises Accept-Ranges: bytes and derives Last-Modified from the MapFile ModTime. HEAD reports the same Content-Length while ServeContent skips the body, but only because the route is registered for both methods: Gin does not send HEAD to a GET handler, it answers 404. bytes=0-9 returns 206 with Content-Range: bytes 0-9/63, and the suffix form bytes=-9 returns the last nine bytes. Two ranges produce multipart/byteranges with a random boundary, so the program prints only the media type. A range past the end gives 416 with Content-Range: bytes /63, and the ETag is gone: since Go 1.23, ServeContent's error path deletes ETag, Last-Modified, Cache-Control and Content-Encoding, unless GODEBUG=httpservecontentkeepheaders=1. If-Range with the current ETag honors the range; with a stale one the client gets the whole new file. If-None-Match yields 304. The last four lines compare the two header builders: they agree on the ASCII name, but for the non-ASCII one Gin encodes the space as + in filename while FormatMediaType writes %20.
Range and If-Range depend on a strong validator
A client resuming a download sends Range: bytes=N- together with If-Range carrying the ETag or Last-Modified of the copy it holds. If the file changed in between, it must receive the whole new file, not bytes of a new version spliced onto an old prefix. ServeContent compares If-Range strongly: a weak ETag such as W/"v3" never matches, so every resume silently restarts from zero, and a date matches only to the second. Store a strong validator with the file, a version number or a content hash computed once at write time; hashing a large file on every request is far too expensive. The Go 1.27 source adds defensive rules worth knowing: a range starting beyond the end is a 416 except for empty files, which get 200; ranges whose sizes add up to more than the file are ignored and answered with 200, which defeats overlapping-range amplification; and a header with more than 200 ranges is ignored. Never compress a ServeContent response: ranges address identity bytes, and the source comments that it omits Content-Length when you set Content-Encoding because that combination is already wrong.
Build Content-Disposition, never concatenate it
The name a user sees is display data. It contains spaces, quotes and non-ASCII letters, and when users choose it, semicolons, control characters and very long strings too. Concatenation produces headers that parse wrongly: an unescaped quote ends the parameter early and a semicolon starts a new one. mime.FormatMediaType("attachment", map[string]string{"filename": name}) writes a bare token when it can, a quoted string with backslash escapes for ASCII with spaces or quotes, and RFC 2231 percent-encoding in filename* when the name contains non-ASCII or control characters; it returns an empty string for an invalid type or parameter name, so check for that. Gin's FileAttachment escapes quotes for ASCII names but uses url.QueryEscape otherwise, which turns spaces into +, and browsers decode filename* by RFC 8187, where + is a literal plus. RFC 6266 suggests an ASCII filename fallback next to filename* for old clients; FormatMediaType cannot emit both from one map, so add it yourself if you need it. Set an explicit Content-Type and nosniff, as the security-headers lesson recommends, so an HTML file is never rendered inline from your origin.
Open through os.Root at startup and keep large files in budget
The handler takes an fs.FS, so production passes root.FS() for an os.Root opened once at startup, and every name then resolves beneath that directory; the path-traversal lesson in the security course explains what os.Root guarantees and what it does not. Look files up by ID after an authorization check, keep the storage path and display name in your database, and never let a client name a path. Large files collide with http.Server.WriteTimeout, which the server-lifecycle lesson describes as one deadline for the entire response: a 2 GB export on a slow link needs its own deadline through http.ResponseController, sized to the file, or a separate download server. For heavy traffic, redirect to a signed object-storage URL or let the proxy send the file. Test with a table of Range, If-Range, If-None-Match and HEAD requests through ServeHTTP, assert byte-exact 206 bodies and the 416 Content-Range, and feed hostile filenames with quotes, semicolons, CR LF and non-ASCII letters into the header builder.
root, err := os.OpenRoot(cfg.ExportsDir)
if err != nil {
return fmt.Errorf("open exports root: %w", err)
}
defer root.Close()
r.Match([]string{http.MethodGet, http.MethodHead}, "/exports/:id", download(root.FS()))
// Inside download, before ServeContent, for very large files:
// http.NewResponseController(c.Writer).SetWriteDeadline(time.Now().Add(budgetFor(info.Size())))This fragment belongs in your composition root and runs in your own native environment against a real directory. os.OpenRoot fails early if the directory is missing, which is better than a 404 on the first download. root.FS() returns an fs.FS whose files are *os.File values, so the seekability check in download passes and ServeContent can serve ranges. The commented line shows where a per-response write deadline goes for very large files; budgetFor is your own policy function.
TAKE THIS WITH YOU
Look files up by ID, open them through os.Root, set Content-Type, a strong ETag and a Content-Disposition from mime.FormatMediaType, then let http.ServeContent handle Range, If-Range, conditional requests and HEAD, and never compress the result.
Check your understanding
A client resumes with Range: bytes=1000- and If-Range: W/"v3", and the handler set ETag: W/"v3" before calling http.ServeContent. What does the client receive?
Go to the source
Progress stays in this browser. No account needed.