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
go
package middleware import ( "net/http"
Per-IP write rate limiting in Gin
rate-limiting
middleware
concurrency
Intermediate
8 steps
go
package middleware import ( "net/http"
A content-type guard middleware in Gin
middleware
closures
http
Intermediate
7 steps
go
package api import ( "errors"
Turning Gin validation errors into JSON
validation
error-handling
http-handlers
Intermediate
9 steps
go
package breaker import ( "errors"
How a circuit breaker works in Go
circuit-breaker
state-machine
concurrency
Intermediate
8 steps
typescript
import { Controller, All, Req,
Catch-all routes and error shaping in NestJS
exception-handling
routing
middleware
Intermediate
6 steps
typescript
import { Component } from '@angular/core'; import { RouterLink, RouterLinkActive } from '@angular/router'; import { NgFor } from '@angular/common';
Building an active-route navbar in Angular
routing
standalone-components
accessibility
Intermediate
6 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.