Skip to content

Commit

Permalink
Implement content server for filestore
Browse files Browse the repository at this point in the history
  • Loading branch information
Acconut committed Dec 20, 2024
1 parent ff0631a commit b531952
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
12 changes: 12 additions & 0 deletions pkg/filestore/filestore.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (
"errors"
"fmt"
"io"
"net/http"
"os"
"path/filepath"

Expand Down Expand Up @@ -50,6 +51,7 @@ func (store FileStore) UseIn(composer *handler.StoreComposer) {
composer.UseTerminater(store)
composer.UseConcater(store)
composer.UseLengthDeferrer(store)
composer.UseContentServer(store)
}

func (store FileStore) NewUpload(ctx context.Context, info handler.FileInfo) (handler.Upload, error) {
Expand Down Expand Up @@ -156,6 +158,10 @@ func (store FileStore) AsConcatableUpload(upload handler.Upload) handler.Concata
return upload.(*fileUpload)
}

func (store FileStore) AsServableUpload(upload handler.Upload) handler.ServableUpload {
return upload.(*fileUpload)
}

// defaultBinPath returns the path to the file storing the binary data, if it is
// not customized using the pre-create hook.
func (store FileStore) defaultBinPath(id string) string {
Expand Down Expand Up @@ -268,6 +274,12 @@ func (upload *fileUpload) FinishUpload(ctx context.Context) error {
return nil
}

func (upload *fileUpload) ServeContent(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
http.ServeFile(w, r, upload.binPath)

return nil
}

// createFile creates the file with the content. If the corresponding directory does not exist,
// it is created. If the file already exists, its content is removed.
func createFile(path string, content []byte) error {
Expand Down
17 changes: 17 additions & 0 deletions pkg/filestore/filestore_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package filestore
import (
"context"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
Expand Down Expand Up @@ -68,6 +70,21 @@ func TestFilestore(t *testing.T) {
a.Equal("hello world", string(content))
reader.(io.Closer).Close()

// Serve content
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/", nil)
r.Header.Set("Range", "bytes=0-4")

err = store.AsServableUpload(upload).ServeContent(context.Background(), w, r)
a.Nil(err)

a.Equal(http.StatusPartialContent, w.Code)
a.Equal("5", w.Header().Get("Content-Length"))
a.Equal("text/plain; charset=utf-8", w.Header().Get("Content-Type"))
a.Equal("bytes 0-4/11", w.Header().Get("Content-Range"))
a.NotEqual("", w.Header().Get("Last-Modified"))
a.Equal("hello", w.Body.String())

// Terminate upload
a.NoError(store.AsTerminatableUpload(upload).Terminate(ctx))

Expand Down

0 comments on commit b531952

Please sign in to comment.