Skip to content

Commit

Permalink
add staticserve.NewFS
Browse files Browse the repository at this point in the history
  • Loading branch information
linkdata committed Nov 11, 2024
1 parent 5ddc78e commit 84a2f62
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 0 deletions.
21 changes: 21 additions & 0 deletions staticserve/newfs.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package staticserve

import (
"io"
"io/fs"
"path/filepath"
)

// NewFS reads the file at fpath from fsys and then calls New with
// the filename part of fpath.
func NewFS(fsys fs.FS, fpath string) (ss *StaticServe, err error) {
var f fs.File
if f, err = fsys.Open(fpath); err == nil {
defer f.Close()
var b []byte
if b, err = io.ReadAll(f); err == nil {
ss, err = New(filepath.Base(fpath), b)
}
}
return
}
22 changes: 22 additions & 0 deletions staticserve/newfs_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package staticserve

import (
"embed"
"testing"
)

//go:embed assets
var assetsFS embed.FS

func TestNewFS(t *testing.T) {
ss, err := NewFS(assetsFS, "assets/subdir/test.txt")
if err != nil {
t.Error(err)
}
if ss.ContentType != "text/plain; charset=utf-8" {
t.Error(ss.ContentType)
}
if ss.Name != "test.u9cvw0b8o4xe.txt" {
t.Error(ss.Name)
}
}
3 changes: 3 additions & 0 deletions staticserve/staticserve.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ type StaticServe struct {
Gz []byte
}

// New returns a StaticServe that serves the given data with a filename like 'filename.12345678.ext'.
// The filename must have the suffix ".gz" if the data is GZip compressed. The ".gz" suffix will
// not be part of the filename presented in this case.
func New(filename string, data []byte) (ss *StaticServe, err error) {
var gz []byte
if strings.HasSuffix(filename, ".gz") {
Expand Down

0 comments on commit 84a2f62

Please sign in to comment.