ServeContent Range Requests

Answer byte-range requests with http.ServeContent on an httptest server and inspect the 206 status and Content-Range header.

GoData Fetching

Code

gosnippet
42 lines
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

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:`.