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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1go:embed bakes files into the binary so there is no filesystem dependency at runtime.
- 2Serving bytes directly with c.Data avoids per-request disk reads and lets you set exact content types.
- 3Cache-Control tuned per resource lets rarely-changing assets stay cached far longer than volatile ones.
Related explainers
go
package streaming import ( "bufio"
Streaming NDJSON logs over HTTP in Go
http-streaming
channels
select
Advanced
10 steps
go
package api import ( "crypto/sha256"
ETag conditional requests in Gin
http-caching
etag
conditional-requests
Intermediate
6 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
go
package logging import ( "context"
Deduplicating log attributes in Go's slog
decorator-pattern
structured-logging
immutability
Intermediate
8 steps
go
package middleware import ( "net/http"
Per-plan export limits in Gin middleware
middleware
rate-limiting
authorization
Intermediate
7 steps
go
package httputil import ( "net"
Safely extracting the real client IP in Go
security
http
ip-spoofing
Intermediate
7 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-embedded-static-meta-files-in-gin-explained-go-370a/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.