Skip to content

Serving data from file

Gin provides several methods for serving files to clients. Each method suits a different use case:

  • c.File(path) — Serves a file from the local filesystem. The content type is detected automatically. Use this when you know the exact file path at compile time or have already validated it.
  • c.FileFromFS(path, fs) — Serves a file from an http.FileSystem interface. Useful when serving files from embedded filesystems (embed.FS), custom storage backends, or when you want to restrict access to a specific directory tree.
  • c.FileAttachment(path, filename) — Serves a file as a download by setting the Content-Disposition: attachment header. The browser will prompt the user to save the file using the filename you provide, regardless of the original file name on disk.
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
// Serve a file inline (displayed in browser)
router.GET("/local/file", func(c *gin.Context) {
c.File("local/file.go")
})
// Serve a file from an http.FileSystem
var fs http.FileSystem = http.Dir("/var/www/assets")
router.GET("/fs/file", func(c *gin.Context) {
c.FileFromFS("fs/file.go", fs)
})
// Serve a file as a downloadable attachment with a custom filename
router.GET("/download", func(c *gin.Context) {
c.FileAttachment("local/report-2024-q1.xlsx", "quarterly-report.xlsx")
})
router.Run(":8080")
}

You can test the download endpoint with curl:

Terminal window
# The -v flag shows the Content-Disposition header
curl -v http://localhost:8080/download --output report.xlsx
# Serve a file inline
curl http://localhost:8080/local/file

For streaming data from an io.Reader (such as a remote URL or dynamically generated content), use c.DataFromReader() instead. See Serving data from reader for details.