Skip to content

Commit e9eeddf

Browse files
author
Alexander Menzhinsky
committed
Add FileSystem support
1 parent 7a858a7 commit e9eeddf

File tree

3 files changed

+25
-8
lines changed

3 files changed

+25
-8
lines changed

context.go

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@ import (
1010
"net"
1111
"net/http"
1212
"net/url"
13-
"os"
1413
"path/filepath"
1514
"strings"
1615
)
@@ -472,7 +471,7 @@ func (c *context) Stream(code int, contentType string, r io.Reader) (err error)
472471
}
473472

474473
func (c *context) File(file string) error {
475-
f, err := os.Open(file)
474+
f, err := c.echo.FS.Open(file)
476475
if err != nil {
477476
return ErrNotFound
478477
}
@@ -481,7 +480,7 @@ func (c *context) File(file string) error {
481480
fi, _ := f.Stat()
482481
if fi.IsDir() {
483482
file = filepath.Join(file, indexPage)
484-
f, err = os.Open(file)
483+
f, err = c.echo.FS.Open(file)
485484
if err != nil {
486485
return ErrNotFound
487486
}

echo.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ import (
4545
stdLog "log"
4646
"net"
4747
"net/http"
48+
"os"
4849
"path"
4950
"reflect"
5051
"runtime"
@@ -80,6 +81,7 @@ type (
8081
AutoTLSManager autocert.Manager
8182
Mutex sync.RWMutex
8283
Logger Logger
84+
FS http.FileSystem
8385
}
8486

8587
// Route contains a handler and information for matching against requests.
@@ -238,6 +240,14 @@ var (
238240
}
239241
)
240242

243+
// FS implements http.FileSystem
244+
type FS struct {}
245+
246+
// Open opens the named file for serving
247+
func (fs *FS) Open(name string) (http.File, error) {
248+
return os.Open(name)
249+
}
250+
241251
// New creates an instance of Echo.
242252
func New() (e *Echo) {
243253
e = &Echo{
@@ -260,6 +270,7 @@ func New() (e *Echo) {
260270
return e.NewContext(nil, nil)
261271
}
262272
e.router = NewRouter(e)
273+
e.FS = &FS{}
263274
return
264275
}
265276

echo_test.go

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,12 @@ package echo
22

33
import (
44
"bytes"
5+
"errors"
56
"net/http"
67
"net/http/httptest"
7-
"testing"
8-
98
"reflect"
109
"strings"
11-
12-
"errors"
13-
10+
"testing"
1411
"time"
1512

1613
"github.com/stretchr/testify/assert"
@@ -85,6 +82,16 @@ func TestEchoStatic(t *testing.T) {
8582
assert.Equal(t, true, strings.HasPrefix(r, "<!doctype html>"))
8683
}
8784

85+
func TestStaticCustomFS(t *testing.T) {
86+
e := New()
87+
e.FS = http.Dir("_fixture")
88+
89+
e.Static("/images", "images")
90+
c, b := request(GET, "/images/walle.png", e)
91+
assert.Equal(t, http.StatusOK, c)
92+
assert.NotEmpty(t, b)
93+
}
94+
8895
func TestEchoFile(t *testing.T) {
8996
e := New()
9097
e.File("/walle", "_fixture/images/walle.png")

0 commit comments

Comments
 (0)