Range Request File Server
Serve a single file from a confined root and rely on ServeContent for partial content, conditional requests, and range headers.
Code
package main
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"path"
"path/filepath"
"strings"
)
func fileHandler(root string) http.HandlerFunc {
absoluteRoot, err := filepath.Abs(root)
if err != nil {
panic(err)
}
return func(w http.ResponseWriter, r *http.Request) {
cleaned := path.Clean("/" + r.URL.Path)
full := filepath.Join(absoluteRoot, filepath.FromSlash(strings.TrimPrefix(cleaned, "/")))
if !strings.HasPrefix(full, absoluteRoot+string(os.PathSeparator)) {
http.Error(w, "invalid path", http.StatusBadRequest)
return
}
file, err := os.Open(full)
if err != nil {
http.Error(w, "not found", http.StatusNotFound)
return
}
defer file.Close()
info, err := file.Stat()
if err != nil || info.IsDir() {
http.Error(w, "not found", http.StatusNotFound)
return
}
http.ServeContent(w, r, info.Name(), info.ModTime(), file)
}
}
func main() {
root, err := os.MkdirTemp("", "range-server-*")
if err != nil {
panic(err)
}
defer os.RemoveAll(root)
if err := os.WriteFile(filepath.Join(root, "report.txt"), []byte("hello range world"), 0o644); err != nil {
panic(err)
}
server := httptest.NewServer(fileHandler(root))
defer server.Close()
request, err := http.NewRequest(http.MethodGet, server.URL+"/report.txt", nil)
if err != nil {
panic(err)
}
request.Header.Set("Range", "bytes=6-10")
response, err := http.DefaultClient.Do(request)
if err != nil {
panic(err)
}
defer response.Body.Close()
body, err := io.ReadAll(response.Body)
if err != nil {
panic(err)
}
fmt.Println("status:", response.StatusCode)
fmt.Println("content-range:", response.Header.Get("Content-Range"))
fmt.Println("body:", string(body))
}Inside the snippet
The whole behavior is carried by the functions fileHandler and main.
Every err != nil branch (8 sites) calls panic(err) — the run stops at the first failure instead of continuing in a broken state. A defer statement pins the cleanup to the function boundary rather than scattering it through the body.
Points of care
- Failures abort via
panic(err)— nothing is returned for the caller to check, and nothing in the snippet recovers.
Putting it to use
The primary signature is func fileHandler(root string) http.HandlerFunc
The demo output is labeled (status:, content-range:, body:), so each line traces straight back to the statement that printed it.
There are 1 call inside main — fileHandler — executed top to bottom.
Core lines
if err := os.WriteFile(filepath.Join(root, "report.txt"), []byte("hello range world"), 0o644); err != nil {
panic(err)
}
if err != nil || info.IsDir() {
http.Error(w, "not found", http.StatusNotFound)
return
}
if err != nil {
panic(err)
}
Interactive Tools for This Topic
FAQ
- What happens when a call fails?
- There are no error returns here: a non-nil `err` reaches `panic(err)` immediately.
- What does Range Request File Server print when run?
- Execute the whole file; each printed line is prefixed with a label like `status:`, `content-range:`, `body:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.