53 lines
1.1 KiB
Go
53 lines
1.1 KiB
Go
package hws
|
|
|
|
import (
|
|
"net/http"
|
|
"os"
|
|
|
|
"github.com/pkg/errors"
|
|
)
|
|
|
|
// Wrapper for default FileSystem
|
|
type justFilesFilesystem struct {
|
|
fs http.FileSystem
|
|
}
|
|
|
|
// Wrapper for default File
|
|
type neuteredReaddirFile struct {
|
|
http.File
|
|
}
|
|
|
|
// Modifies the behavior of FileSystem.Open to return the neutered version of File
|
|
func (fs justFilesFilesystem) Open(name string) (http.File, error) {
|
|
f, err := fs.fs.Open(name)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// Check if the requested path is a directory
|
|
// and explicitly return an error to trigger a 404
|
|
fileInfo, err := f.Stat()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if fileInfo.IsDir() {
|
|
return nil, os.ErrNotExist
|
|
}
|
|
|
|
return neuteredReaddirFile{f}, nil
|
|
}
|
|
|
|
// Overrides the Readdir method of File to always return nil
|
|
func (f neuteredReaddirFile) Readdir(count int) ([]os.FileInfo, error) {
|
|
return nil, nil
|
|
}
|
|
|
|
func SafeFileServer(fileSystem *http.FileSystem) (http.Handler, error) {
|
|
if fileSystem == nil {
|
|
return nil, errors.New("No file system provided")
|
|
}
|
|
nfs := justFilesFilesystem{*fileSystem}
|
|
fs := http.FileServer(nfs)
|
|
return fs, nil
|
|
}
|