@@ -13,6 +13,8 @@ import (
13
13
"strings"
14
14
"sync"
15
15
16
+ "path/filepath"
17
+
16
18
"github.com/bradfitz/http2"
17
19
"github.com/mattn/go-colorable"
18
20
"golang.org/x/net/websocket"
@@ -157,7 +159,7 @@ func New() (e *Echo) {
157
159
code = he .code
158
160
msg = he .message
159
161
}
160
- if e .Debug () {
162
+ if e .debug {
161
163
msg = err .Error ()
162
164
}
163
165
http .Error (c .response , msg , code )
@@ -299,23 +301,45 @@ func (e *Echo) Favicon(file string) {
299
301
e .ServeFile ("/favicon.ico" , file )
300
302
}
301
303
302
- // Static serves static files.
303
- func (e * Echo ) Static (path , root string ) {
304
- fs := http .StripPrefix (path , http .FileServer (http .Dir (root )))
304
+ // Static serves static files from a directory. It's an alias for `Echo.ServeDir`
305
+ func (e * Echo ) Static (path , dir string ) {
306
+ e .ServeDir (path , dir )
307
+ }
308
+
309
+ // ServeDir serves files from a directory.
310
+ func (e * Echo ) ServeDir (path , dir string ) {
305
311
e .Get (path + "*" , func (c * Context ) error {
306
- fs .ServeHTTP (c .response , c .request )
307
- return nil
312
+ return serveFile (dir , c .P (0 ), c ) // Param `_name`
308
313
})
309
314
}
310
315
311
316
// ServeFile serves a file.
312
317
func (e * Echo ) ServeFile (path , file string ) {
313
318
e .Get (path , func (c * Context ) error {
314
- http . ServeFile ( c . response , c . request , file )
315
- return nil
319
+ dir , file := filepath . Split ( file )
320
+ return serveFile ( dir , file , c )
316
321
})
317
322
}
318
323
324
+ func serveFile (dir , file string , c * Context ) error {
325
+ fs := http .Dir (dir )
326
+ f , err := fs .Open (file )
327
+ if err != nil {
328
+ return NewHTTPError (http .StatusNotFound )
329
+ }
330
+
331
+ fi , err := f .Stat ()
332
+ if err != nil {
333
+ return NewHTTPError (http .StatusNotFound )
334
+ }
335
+ if fi .IsDir () {
336
+ return NewHTTPError (http .StatusForbidden )
337
+ }
338
+
339
+ http .ServeContent (c .response , c .request , fi .Name (), fi .ModTime (), f )
340
+ return nil
341
+ }
342
+
319
343
// URI generates a URI from handler.
320
344
func (e * Echo ) URI (h Handler , params ... interface {}) string {
321
345
uri := new (bytes.Buffer )
0 commit comments