feat(server): add streaming response helpers for file download

Add ParseRange, StreamFile, StreamRange for full and partial content delivery.

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
This commit is contained in:
dailz
2026-04-15 09:22:58 +08:00
parent bf89de12f0
commit a114821615
2 changed files with 160 additions and 0 deletions

View File

@@ -114,3 +114,65 @@ func TestErrorWithStatus(t *testing.T) {
t.Fatalf("expected error 'already exists', got '%s'", resp.Error)
}
}
func TestParseRangeStandard(t *testing.T) {
tests := []struct {
rangeHeader string
fileSize int64
wantStart int64
wantEnd int64
wantErr bool
}{
{"bytes=0-1023", 10000, 0, 1023, false},
{"bytes=1024-", 10000, 1024, 9999, false},
{"bytes=-1024", 10000, 8976, 9999, false},
{"bytes=0-0", 10000, 0, 0, false},
{"bytes=9999-", 10000, 9999, 9999, false},
}
for _, tt := range tests {
start, end, err := ParseRange(tt.rangeHeader, tt.fileSize)
if (err != nil) != tt.wantErr {
t.Errorf("ParseRange(%q, %d) error = %v, wantErr %v", tt.rangeHeader, tt.fileSize, err, tt.wantErr)
continue
}
if !tt.wantErr {
if start != tt.wantStart || end != tt.wantEnd {
t.Errorf("ParseRange(%q, %d) = (%d, %d), want (%d, %d)", tt.rangeHeader, tt.fileSize, start, end, tt.wantStart, tt.wantEnd)
}
}
}
}
func TestParseRangeInvalidAndMultiPart(t *testing.T) {
tests := []struct {
rangeHeader string
fileSize int64
}{
{"", 10000},
{"bytes=9999-0", 10000},
{"bytes=20000-", 10000},
{"bytes=0-100,200-300", 10000},
{"bytes=0-100, 400-500", 10000},
{"bytes=", 10000},
{"chars=0-100", 10000},
}
for _, tt := range tests {
_, _, err := ParseRange(tt.rangeHeader, tt.fileSize)
if err == nil {
t.Errorf("ParseRange(%q, %d) expected error, got nil", tt.rangeHeader, tt.fileSize)
}
}
}
func TestParseRangeEdgeCases(t *testing.T) {
start, end, err := ParseRange("bytes=0-99999", 10000)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if end != 9999 {
t.Errorf("end = %d, want 9999 (clamped to fileSize-1)", end)
}
if start != 0 {
t.Errorf("start = %d, want 0", start)
}
}