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 config import ( "fmt"
A thread-safe config singleton in Go
singleton
concurrency
environment-variables
Intermediate
7 steps
go
package scheduler import ( "container/heap"
A priority job queue with Go's container/heap
priority-queue
heap
interfaces
Intermediate
9 steps
go
func UploadChunk(c *gin.Context) { uploadID := c.Param("uploadID") if !validUploadID.MatchString(uploadID) { c.JSON(http.StatusBadRequest, gin.H{"error": "invalid upload id"})
Resumable chunked uploads in Gin
file-upload
content-range
streaming
Advanced
9 steps
go
func (h *ArticleHandler) Create(c *gin.Context) { var req struct { Title string `json:"title" binding:"required"` Body string `json:"body" binding:"required"`
Handling a POST request in Gin
request binding
validation
http status codes
Intermediate
7 steps
go
package cache import ( "sync"
A thread-safe TTL cache in Go
concurrency
mutex
caching
Intermediate
9 steps
python
from flask import Blueprint, render_template, jsonify, request, abort from .models import Article
Content negotiation in a Flask Blueprint
content-negotiation
http-headers
routing
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.