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 anhttp.FileSysteminterface. 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 theContent-Disposition: attachmentheader. 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:
# The -v flag shows the Content-Disposition headercurl -v http://localhost:8080/download --output report.xlsx
# Serve a file inlinecurl http://localhost:8080/local/fileFor 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.