go
60 lines · 7 steps
Serving cached static assets in Gin
Wrapping an http.FileSystem and a Gin middleware to attach long-lived Cache-Control headers to static assets.
Explained by
highlit
1package server
2
3import (
4 "net/http"
5 "path/filepath"
6 "strings"
7
8 "github.com/gin-gonic/gin"
9)
10
11type cachedFileSystem struct {
12 fs http.FileSystem
13 maxAge string
14 immutable bool
15}
16
17type cachedFile struct {
18 http.File
19}
20
21func (c cachedFileSystem) Open(name string) (http.File, error) {
22 f, err := c.fs.Open(name)
23 if err != nil {
24 return nil, err
25 }
26 return cachedFile{f}, nil
27}
28
29func newCachedFS(root string, maxAge string, immutable bool) cachedFileSystem {
30 return cachedFileSystem{
31 fs: http.Dir(root),
32 maxAge: maxAge,
33 immutable: immutable,
34 }
35}
36
37func (c cachedFileSystem) cacheControl() string {
38 value := "public, max-age=" + c.maxAge
39 if c.immutable {
40 value += ", immutable"
41 }
42 return value
43}
44
45func RegisterStatic(r *gin.Engine) {
46 assets := newCachedFS("./public/assets", "31536000", true)
47
48 r.Use(func(ctx *gin.Context) {
49 if strings.HasPrefix(ctx.Request.URL.Path, "/assets/") {
50 ext := filepath.Ext(ctx.Request.URL.Path)
51 if ext != "" {
52 ctx.Header("Cache-Control", assets.cacheControl())
53 ctx.Header("Vary", "Accept-Encoding")
54 }
55 }
56 ctx.Next()
57 })
58
59 r.StaticFS("/assets", assets)
60}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Wrapping http.FileSystem lets you customize file serving without reimplementing the whole handler.
- 2Immutable, year-long Cache-Control values are safe when asset URLs are content-fingerprinted.
- 3Gin middleware can inspect the request path and set response headers before the static handler runs.
Related explainers
go
package streaming import ( "bufio"
Streaming NDJSON logs over HTTP in Go
http-streaming
channels
select
Advanced
10 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
go
package api import ( "crypto/sha256"
ETag conditional requests in Gin
http-caching
etag
conditional-requests
Intermediate
6 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
go
func (w *Watcher) resetDebounce(d time.Duration) { if !w.timer.Stop() { select { case <-w.timer.C:
Debouncing a stream of events in Go
debounce
timers
channels
Advanced
7 steps
php
<?php namespace App\Services;
Building a cached daily leaderboard in Laravel
caching
aggregation
eager-loading
Intermediate
9 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-cached-static-assets-in-gin-explained-go-4e42/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.