Static Files
Serve CSS, JavaScript, images, and favicon files from a local directory using a URL prefix.
The router package can serve static assets from a local directory.
This is useful for:
- CSS files
- JavaScript files
- images
- icons
- fonts
- public frontend assets
Static files are mapped from a real filesystem path to a public URL prefix.
For example:
r.Static("/assets/", "./public")This means:
./public/style.css → /assets/style.css
./public/favicon.ico → /assets/favicon.ico
./public/images/logo.png → /assets/images/logo.pngThe local directory name is not exposed in the URL. Only the files inside the directory are served under the configured prefix.
Directory Structure
Example project structure:
static_files/
├── public/
│ ├── favicon.ico
│ └── style.css
└── main.goIn this example, the real static directory is:
./publicand the public URL prefix is:
/assets/Example
package main
import (
"log/slog"
"net/http"
"os"
"github.com/netlifeguru/router"
)
func main() {
r := router.New()
r.Static("/assets/", "./public")
r.GET("/", func(w http.ResponseWriter, req *http.Request, ctx *router.Context) {
w.Header().Set("Content-Type", "text/html")
w.Write([]byte(`
<html>
<head>
<link rel="stylesheet" href="/assets/style.css">
</head>
<body>
<h1>Static Files Example</h1>
<p>Static assets are served from the ./public directory.</p>
</body>
</html>
`))
})
if err := r.ListenAndServe(":4000"); err != nil {
slog.Error("failed to start server", "error", err)
os.Exit(1)
}
}Run the application:
go run .Open the page:
http://localhost:4000The CSS file is served from:
http://localhost:4000/assets/style.cssFavicon Support
Browsers commonly request favicon.ico from the root path:
/favicon.icoWhen favicon.ico exists inside the static directory, the router automatically registers an additional root-level favicon route.
For example:
./public/favicon.icois available at both:
/assets/favicon.ico
/favicon.icoThis prevents unnecessary 404 responses when browsers request the favicon from the root of the domain.
Notes
Static file serving uses Go’s standard http.FileServer internally.
The configured URL prefix does not have to match the local directory name:
r.Static("/assets/", "./public")In this case, files are loaded from ./public, but exposed publicly under /assets/.