go
42 lines · 8 steps
Streaming a proxied download in Gin
A Gin handler fetches a file from upstream storage and streams it straight back to the client, preserving range requests and key headers.
Explained by
highlit
1func ProxyDownload(c *gin.Context) {
2 objectKey := c.Param("key")
3 upstream := fmt.Sprintf("%s/files/%s", storageBaseURL, objectKey)
4
5 req, err := http.NewRequestWithContext(c.Request.Context(), http.MethodGet, upstream, nil)
6 if err != nil {
7 c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "failed to build upstream request"})
8 return
9 }
10
11 if rng := c.GetHeader("Range"); rng != "" {
12 req.Header.Set("Range", rng)
13 }
14 req.Header.Set("Authorization", "Bearer "+storageToken)
15
16 resp, err := httpClient.Do(req)
17 if err != nil {
18 c.AbortWithStatusJSON(http.StatusBadGateway, gin.H{"error": "upstream unreachable"})
19 return
20 }
21 defer resp.Body.Close()
22
23 if resp.StatusCode >= http.StatusBadRequest {
24 c.AbortWithStatusJSON(resp.StatusCode, gin.H{"error": "upstream returned an error"})
25 return
26 }
27
28 extraHeaders := map[string]string{}
29 if cd := resp.Header.Get("Content-Disposition"); cd != "" {
30 extraHeaders["Content-Disposition"] = cd
31 }
32 if ar := resp.Header.Get("Accept-Ranges"); ar != "" {
33 extraHeaders["Accept-Ranges"] = ar
34 }
35
36 contentType := resp.Header.Get("Content-Type")
37 if contentType == "" {
38 contentType = "application/octet-stream"
39 }
40
41 c.DataFromReader(resp.StatusCode, resp.ContentLength, contentType, resp.Body, extraHeaders)
42}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Tying the outbound request to the incoming request's context lets client disconnects cancel upstream work automatically.
- 2Streaming from the response body with DataFromReader avoids buffering the whole file in memory.
- 3A proxy should forward meaningful headers like Range and Content-Disposition so downstream behavior stays intact.
Related explainers
ruby
class Order class InvalidTransition < StandardError; end TRANSITIONS = {
A state machine for order transitions in Ruby
state-machine
data-driven
error-handling
Intermediate
8 steps
go
package theme import ( "fmt"
Per-tenant HTML templates with Gin's renderer
multi-tenancy
concurrency
html-templates
Advanced
8 steps
php
<?php namespace App\Http\Controllers;
Streaming a filtered CSV export in Laravel
streaming
csv-export
query-builder
Intermediate
9 steps
go
package auth import ( "net/http"
Setting and reading secure session cookies in Go
cookies
session-management
security
Intermediate
6 steps
rust
use std::cmp::Ordering; use std::str::FromStr; #[derive(Debug, Clone, PartialEq, Eq)]
Parsing and ordering semantic versions in Rust
parsing
trait-implementation
ordering
Intermediate
8 steps
javascript
'use client'; import { useEffect } from 'react'; import * as Sentry from '@sentry/nextjs';
How a Next.js error boundary recovers
error-boundary
error-handling
observability
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-a-proxied-download-in-gin-explained-go-dfc4/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.