2024-04-28 13:08:41 +02:00
|
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
// SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors
|
|
|
|
|
2022-08-18 01:16:43 +02:00
|
|
|
package echo
|
|
|
|
|
|
|
|
import (
|
2022-11-02 17:50:56 +01:00
|
|
|
"errors"
|
|
|
|
"io"
|
|
|
|
"io/fs"
|
2022-08-18 01:16:43 +02:00
|
|
|
"net/http"
|
|
|
|
"path/filepath"
|
|
|
|
)
|
|
|
|
|
2022-11-02 17:50:56 +01:00
|
|
|
func (c *context) File(file string) error {
|
|
|
|
return fsFile(c, file, c.echo.Filesystem)
|
|
|
|
}
|
|
|
|
|
|
|
|
// FileFS serves file from given file system.
|
|
|
|
//
|
|
|
|
// When dealing with `embed.FS` use `fs := echo.MustSubFS(fs, "rootDirectory") to create sub fs which uses necessary
|
|
|
|
// prefix for directory path. This is necessary as `//go:embed assets/images` embeds files with paths
|
|
|
|
// including `assets/images` as their prefix.
|
|
|
|
func (c *context) FileFS(file string, filesystem fs.FS) error {
|
|
|
|
return fsFile(c, file, filesystem)
|
|
|
|
}
|
|
|
|
|
|
|
|
func fsFile(c Context, file string, filesystem fs.FS) error {
|
|
|
|
f, err := filesystem.Open(file)
|
2022-08-18 01:16:43 +02:00
|
|
|
if err != nil {
|
2022-11-02 17:50:56 +01:00
|
|
|
return ErrNotFound
|
2022-08-18 01:16:43 +02:00
|
|
|
}
|
|
|
|
defer f.Close()
|
|
|
|
|
|
|
|
fi, _ := f.Stat()
|
|
|
|
if fi.IsDir() {
|
2022-11-02 17:50:56 +01:00
|
|
|
file = filepath.ToSlash(filepath.Join(file, indexPage)) // ToSlash is necessary for Windows. fs.Open and os.Open are different in that aspect.
|
|
|
|
f, err = filesystem.Open(file)
|
2022-08-18 01:16:43 +02:00
|
|
|
if err != nil {
|
2022-11-02 17:50:56 +01:00
|
|
|
return ErrNotFound
|
2022-08-18 01:16:43 +02:00
|
|
|
}
|
|
|
|
defer f.Close()
|
|
|
|
if fi, err = f.Stat(); err != nil {
|
2022-11-02 17:50:56 +01:00
|
|
|
return err
|
2022-08-18 01:16:43 +02:00
|
|
|
}
|
|
|
|
}
|
2022-11-02 17:50:56 +01:00
|
|
|
ff, ok := f.(io.ReadSeeker)
|
|
|
|
if !ok {
|
|
|
|
return errors.New("file does not implement io.ReadSeeker")
|
|
|
|
}
|
|
|
|
http.ServeContent(c.Response(), c.Request(), fi.Name(), fi.ModTime(), ff)
|
|
|
|
return nil
|
2022-08-18 01:16:43 +02:00
|
|
|
}
|