go 32 lines · 6 steps

Serving embedded static meta files in Gin

Embed a favicon and robots.txt into the binary and serve them from memory with cache headers.

Explained by highlit
1package handlers
2 
3import (
4 "net/http"
5 _ "embed"
6 
7 "github.com/gin-gonic/gin"
8)
9 
10//go:embed assets/favicon.ico
11var faviconBytes []byte
12 
13var robotsBytes = []byte(strings.Join([]string{
14 "User-agent: *",
15 "Disallow: /admin/",
16 "Disallow: /api/",
17 "Allow: /",
18 "Sitemap: https://example.com/sitemap.xml",
19 "",
20}, "\n"))
21 
22func RegisterStaticMeta(r *gin.Engine) {
23 r.GET("/favicon.ico", func(c *gin.Context) {
24 c.Header("Cache-Control", "public, max-age=604800, immutable")
25 c.Data(http.StatusOK, "image/x-icon", faviconBytes)
26 })
27 
28 r.GET("/robots.txt", func(c *gin.Context) {
29 c.Header("Cache-Control", "public, max-age=86400")
30 c.Data(http.StatusOK, "text/plain; charset=utf-8", robotsBytes)
31 })
32}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1go:embed bakes files into the binary so there is no filesystem dependency at runtime.
  2. 2Serving bytes directly with c.Data avoids per-request disk reads and lets you set exact content types.
  3. 3Cache-Control tuned per resource lets rarely-changing assets stay cached far longer than volatile ones.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Serving embedded static meta files in Gin — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code