ServeContent Range Requests
Answer byte-range requests with http.ServeContent on an httptest server and inspect the 206 status and Content-Range header.
Code
package main
import (
"bytes"
"fmt"
"io"
"net/http"
"net/http/httptest"
"time"
)
func main() {
payload := []byte("0123456789abcdefghij")
modTime := time.Date(2026, time.January, 2, 3, 4, 5, 0, time.UTC)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// ServeContent answers Range requests, HEAD, and content type probes
http.ServeContent(w, r, "digits.txt", modTime, bytes.NewReader(payload))
}))
defer server.Close()
req, err := http.NewRequest(http.MethodGet, server.URL, nil)
if err != nil {
fmt.Println("request failed:", err)
return
}
// ask for ten bytes starting at offset six
req.Header.Set("Range", "bytes=6-15")
resp, err := http.DefaultClient.Do(req)
if err != nil {
fmt.Println("get failed:", err)
return
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Println("status:", resp.StatusCode)
fmt.Println("content-range:", resp.Header.Get("Content-Range"))
fmt.Println("body:", string(body))
fmt.Println("accept-ranges:", resp.Header.Get("Accept-Ranges"))
}The path of execution
The moving parts are the function main.
err is inspected at 2 call sites before any result is trusted. defer schedules the cleanup, and the scheduled call fires no matter how the function exits.
Points of care
- No install step: all APIs used ship with the platform.
Applying it
The main signature reads func main()
Each run prints the 3 labeled blocks request failed:, get failed:, status: in source order.
Statements that matter
if err != nil {
fmt.Println("request failed:", err)
return
}
if err != nil {
fmt.Println("get failed:", err)
return
}
defer resp.Body.Close()
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Accept Header ParserParse an Accept header into media ranges with their quality values and specificity, sorted by preference for content negotiation debugging.Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.Set-Cookie ParserParse one or more Set-Cookie header values into the cookie name, value, and attributes like Path, Domain, Expires, Max-Age, Secure, HttpOnly, and SameSite.
FAQ
- What does ServeContent Range Requests print when run?
- Running the file directly is enough — expect labeled output lines such as `request failed:`, `get failed:`, `status:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.