Go: how to force file download in Fiber

Go: how to force file download in Fiber

One of the useful aspects of Fiber is its ability to manage static files and downloads efficiently, allowing developers to create web applications with robust and customizable file download capabilities.

Go Fiber is an Express-inspired web framework designed to simplify the process of developing web applications and APIs in Go thanks to its simplicity, speed and "don't repeat yourself" philosophy. One of the useful aspects of Fiber is its ability to manage static files and downloads efficiently, allowing developers to create web applications with robust and customizable file download capabilities.

To force a file to be downloaded in a Go Fiber application, you can use the SendFile method of the request context to specify the path of the file to send to the client. However, for the browser to start downloading the file instead of displaying it directly (for example, for PDF or image files), you need to modify the Content-Disposition header of the HTTP response.

To force the download of a file, define a route that uses SendFile to send the file to the client, setting the Content-Disposition header to attachment with the desired file name:


package main

import (
     "github.com/gofiber/fiber/v2"
)

func setupRoutes(app *fiber.App) {
     app.Get("/download", func(c *fiber.Ctx) error {
         // Set the header to force the download
         c.Set("Content-Disposition", "attachment; filename=\"yourfile.pdf\"")

         // Send the file to the client
         return c.SendFile("./files/yourfile.pdf")
     })
}

func main() {
     app := fiber.New()

     // Set the routes
     setupRoutes(app)

     app.Listen(":3000")
}

In the example above, when the user accesses /download, the server configures the Content-Disposition header to force the specified file to be downloaded instead of displayed in the browser. Make sure the file path (./files/yourfile.pdf in the example) is correct and that the file exists on the server.

Conclusion

Forcing a file download with Go Fiber is a simple and straightforward process. By modifying HTTP response headers and using the SendFile method, you can control how files are sent to the client, providing a customized user experience and advanced functionality for your web application. Remember to always test your implementations in different browsers to ensure that download behavior is consistent.