go
39 lines · 7 steps
Serving a single-page app with Gin
Wire a Gin engine to serve static assets and fall back to index.html for client-side routes.
Explained by
highlit
1package server
2
3import (
4 "net/http"
5 "os"
6 "path/filepath"
7 "strings"
8
9 "github.com/gin-gonic/gin"
10)
11
12func RegisterSPA(r *gin.Engine, distDir string) {
13 indexPath := filepath.Join(distDir, "index.html")
14
15 r.Static("/assets", filepath.Join(distDir, "assets"))
16 r.StaticFile("/favicon.ico", filepath.Join(distDir, "favicon.ico"))
17 r.StaticFile("/robots.txt", filepath.Join(distDir, "robots.txt"))
18
19 r.NoRoute(func(c *gin.Context) {
20 if strings.HasPrefix(c.Request.URL.Path, "/api/") {
21 c.JSON(http.StatusNotFound, gin.H{"error": "not found"})
22 return
23 }
24
25 requested := filepath.Join(distDir, filepath.Clean(c.Request.URL.Path))
26 if !strings.HasPrefix(requested, filepath.Clean(distDir)) {
27 c.Status(http.StatusForbidden)
28 return
29 }
30
31 if info, err := os.Stat(requested); err == nil && !info.IsDir() {
32 c.File(requested)
33 return
34 }
35
36 c.Header("Cache-Control", "no-cache")
37 c.File(indexPath)
38 })
39}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1SPAs need a catch-all route that returns index.html so the client router can handle unknown paths.
- 2Always confirm a joined filesystem path still lives inside its base directory to block traversal attacks.
- 3Distinguish API 404s from asset requests so missing endpoints don't accidentally return HTML.
Related explainers
javascript
async function copyToClipboard(text) { if (navigator.clipboard && window.isSecureContext) { try { await navigator.clipboard.writeText(text);
Copying to the clipboard with a fallback
clipboard
progressive-enhancement
dom
Intermediate
8 steps
go
package handlers import ( "fmt"
Handling secure file uploads in Gin
file-upload
validation
security
Intermediate
7 steps
go
package handlers import ( "fmt"
Handling multipart profile uploads in Gin
form binding
file upload
validation
Intermediate
7 steps
go
package metrics import ( "sync/atomic"
A lock-free request counter in Go
concurrency
atomics
lock-free
Intermediate
6 steps
go
package middleware import ( "time"
Building a request logger middleware in Gin
middleware
structured-logging
closures
Intermediate
6 steps
go
package fetch import ( "context"
Concurrent API fetches with errgroup in Go
concurrency
goroutines
error-handling
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/serving-a-single-page-app-with-gin-explained-go-5abc/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.