go
28 lines · 6 steps
Streaming video files with Gin
A Gin handler that looks up a video, opens its file, and streams it with range support via http.ServeContent.
Explained by
highlit
1func ServeVideo(c *gin.Context) {
2 id := c.Param("id")
3 video, err := videoRepo.FindByID(c.Request.Context(), id)
4 if err != nil {
5 c.JSON(http.StatusNotFound, gin.H{"error": "video not found"})
6 return
7 }
8
9 path := filepath.Join(mediaRoot, video.StoredName)
10 info, err := os.Stat(path)
11 if err != nil || info.IsDir() {
12 c.JSON(http.StatusNotFound, gin.H{"error": "file unavailable"})
13 return
14 }
15
16 f, err := os.Open(path)
17 if err != nil {
18 c.JSON(http.StatusInternalServerError, gin.H{"error": "could not open file"})
19 return
20 }
21 defer f.Close()
22
23 c.Header("Accept-Ranges", "bytes")
24 c.Header("Content-Type", video.ContentType)
25 c.Header("Cache-Control", "public, max-age=86400")
26
27 http.ServeContent(c.Writer, c.Request, video.StoredName, info.ModTime(), f)
28}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Delegating to http.ServeContent gets you range requests, conditional GETs, and content-type handling for free.
- 2Validate the database record and the file on disk separately, since either can be missing independently.
- 3Defer closing the file right after opening so the handle is released on every return path.
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
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
go
package logging import ( "context"
Deduplicating log attributes in Go's slog
decorator-pattern
structured-logging
immutability
Intermediate
8 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/streaming-video-files-with-gin-explained-go-9f2b/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.