Skip to content

Commit

Permalink
handler: support range requests for GET /upload
Browse files Browse the repository at this point in the history
  • Loading branch information
markspolakovs committed Dec 14, 2023
1 parent c856f72 commit e13b648
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
57 changes: 57 additions & 0 deletions pkg/handler/get_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"testing"

"github.com/golang/mock/gomock"

. "github.com/tus/tusd/v2/pkg/handler"
)

Expand Down Expand Up @@ -164,4 +165,60 @@ func TestGet(t *testing.T) {
ResBody: "",
}).Run(handler, t)
})

SubTest(t, "RangeRequest", func(t *testing.T, store *MockFullDataStore, _ *StoreComposer) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
upload := NewMockFullUpload(ctrl)
locker := NewMockFullLocker(ctrl)
lock := NewMockFullLock(ctrl)

reader := &closingStringReader{
Reader: strings.NewReader("hello"),
}

gomock.InOrder(
locker.EXPECT().NewLock("yes").Return(lock, nil),
lock.EXPECT().Lock(gomock.Any(), gomock.Any()).Return(nil),
store.EXPECT().GetUpload(gomock.Any(), "yes").Return(upload, nil),
upload.EXPECT().GetInfo(gomock.Any()).Return(FileInfo{
Offset: 5,
Size: 20,
MetaData: map[string]string{
"filename": "file.jpg\"evil",
"filetype": "image/jpeg",
},
IsFinal: true,
}, nil),
upload.EXPECT().GetReader(gomock.Any()).Return(reader, nil),
lock.EXPECT().Unlock().Return(nil),
)

composer := NewStoreComposer()
composer.UseCore(store)
composer.UseLocker(locker)

handler, _ := NewHandler(Config{
StoreComposer: composer,
})

(&httpTest{
Method: "GET",
URL: "yes",
ReqHeader: map[string]string{
"Range": "bytes=0-3",
},
ResHeader: map[string]string{
"Content-Length": "4",
"Content-Type": "image/jpeg",
"Content-Disposition": `inline;filename="file.jpg\"evil"`,
},
Code: http.StatusOK,
ResBody: "hell",
}).Run(handler, t)

if !reader.closed {
t.Error("expected reader to be closed")
}
})
}
8 changes: 8 additions & 0 deletions pkg/handler/unrouted_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -646,6 +646,7 @@ func (handler *UnroutedHandler) HeadFile(w http.ResponseWriter, r *http.Request)
} else {
resp.Header["Upload-Length"] = strconv.FormatInt(info.Size, 10)
resp.Header["Content-Length"] = strconv.FormatInt(info.Size, 10)
resp.Header["Accept-Ranges"] = "bytes"
}

resp.StatusCode = http.StatusOK
Expand Down Expand Up @@ -1002,6 +1003,13 @@ func (handler *UnroutedHandler) GetFile(w http.ResponseWriter, r *http.Request)
return
}

if seeker, ok := src.(io.ReadSeeker); ok {
handler.sendResp(c, resp)
http.ServeContent(w, r, info.ID, time.Time{}, seeker)
_ = src.Close()
return
}

handler.sendResp(c, resp)
io.Copy(w, src)

Expand Down

0 comments on commit e13b648

Please sign in to comment.