gohttp/hander/file.go

69 lines
1.3 KiB
Go
Raw Normal View History

2023-12-09 16:34:20 +08:00
package handler
import (
"errors"
"io/fs"
"net/http"
"os"
"path/filepath"
"strings"
2023-12-13 10:59:47 +08:00
"git.pyer.club/kingecg/gologger"
2023-12-09 16:34:20 +08:00
)
type FileHandler struct {
Root string
Default string
http.FileSystem
}
func (f FileHandler) Open(name string) (http.File, error) {
2023-12-13 10:59:47 +08:00
l := gologger.GetLogger("filehandler")
2023-12-09 16:34:20 +08:00
if strings.HasPrefix(name, "../") {
return nil, errors.New("not permitted")
}
rPath := filepath.Join(f.Root, strings.TrimPrefix(name, "/"))
2023-12-13 10:59:47 +08:00
l.Debug("access:", rPath)
2023-12-10 01:08:39 +08:00
// if rPath == f.Root {
// if f.Default == "" {
// return nil, errors.New("not permit list dir")
// }
// rPath = filepath.Join(rPath, f.Default)
// }
2023-12-09 16:34:20 +08:00
fInfo, _, err := FileExists(rPath)
if err != nil {
2023-12-13 10:59:47 +08:00
l.Error("access file error:", rPath, err)
2023-12-09 16:34:20 +08:00
return nil, err
}
2023-12-10 01:08:39 +08:00
if fInfo.IsDir() && rPath != strings.TrimSuffix(f.Root, "/") {
2023-12-09 16:34:20 +08:00
return nil, errors.New("not permit list dir")
}
if fInfo.Mode() == fs.ModeSymlink {
return nil, errors.New("not permit follow symbol link")
}
2023-12-10 01:08:39 +08:00
fp, err := os.Open(rPath)
if err != nil {
2023-12-13 10:59:47 +08:00
l.Error("open file fail", err)
2023-12-10 01:08:39 +08:00
return nil, err
}
return fp, nil
2023-12-09 16:34:20 +08:00
}
func FileExists(name string) (os.FileInfo, bool, error) {
info, err := os.Stat(name)
if err != nil {
return nil, os.IsExist(err), err
}
return info, true, nil
}
func NewFileHandler(f FileHandler) http.Handler {
return http.FileServer(f)
}