Skip to content

Gin Static Files: 404 Not Found

DodaTech Updated 2026-06-24 1 min read

In this tutorial, you'll learn about Gin Static Files: 404 Not Found. We cover key concepts, practical examples, and best practices.

Static files with Gin -- Serve static files in Gin using r.Static() for directories or r.StaticFile() for single files.

The Problem

Gin provides r.Static() for serving static directories. If the path is wrong or the directory doesn't exist relative to the working directory, files return 404.

Wrong

r := gin.Default()
r.Static("/static", "./static")

Output:

$ curl http://localhost:8080/static/style.css
// 404 page not found
r := gin.Default()
r.Static("/static", "./static")
r.StaticFS("/more-static", gin.Dir("./static", false))
r.StaticFile("/favicon.ico", "./static/favicon.ico")

Output:

$ curl http://localhost:8080/static/style.css
body { color: red; }

Prevention

  • Use r.Static("/url", "./dir") for directory serving
  • Use r.StaticFile("/url", "./path") for individual files
  • Use r.StaticFS() for custom http.FileSystem
  • Set directory listing off with gin.Dir(dir, false)
  • Verify working directory matches expectations

Common Mistakes with gin static files

  1. Using foldl instead of foldl' causing stack overflow on large lists
  2. Forgetting deriving (Show, Eq) on custom data types needed for debugging
  3. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable

These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

**Does Gin support embedded static files?**

Yes. Use embed.FS with http.FS(): r.StaticFS("/static", http.FS(embededFiles)).

How do I disable directory listing?

Use gin.Dir(path, false) or implement your own http.FileSystem.

Can I use a different root for static files?

Yes. The second argument to r.Static is the filesystem path.


Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro