Gin Static Files: 404 Not Found
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
Right
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
- Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging - 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
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