summaryrefslogtreecommitdiff
path: root/contrib/fs/file.go
diff options
context:
space:
mode:
Diffstat (limited to 'contrib/fs/file.go')
-rw-r--r--contrib/fs/file.go49
1 files changed, 26 insertions, 23 deletions
diff --git a/contrib/fs/file.go b/contrib/fs/file.go
index 71428ed..a1293af 100644
--- a/contrib/fs/file.go
+++ b/contrib/fs/file.go
@@ -1,37 +1,40 @@
package fs
import (
- "context"
"io/fs"
"mime"
"strings"
"tildegit.org/tjp/gus"
- "tildegit.org/tjp/gus/gemini"
)
-// FileHandler builds a handler function which serves up a file system.
-func FileHandler(fileSystem fs.FS) gus.Handler {
- return func(ctx context.Context, req *gus.Request) *gus.Response {
- file, err := fileSystem.Open(strings.TrimPrefix(req.Path, "/"))
- if isNotFound(err) {
- return nil
- }
- if err != nil {
- return gemini.Failure(err)
- }
-
- isDir, err := fileIsDir(file)
- if err != nil {
- return gemini.Failure(err)
- }
-
- if isDir {
- return nil
- }
-
- return gemini.Success(mediaType(req.Path), file)
+// ResolveFile finds a file from a filesystem based on a request path.
+//
+// It only returns a non-nil file if a file is found - not a directory.
+// If there is any other sort of filesystem access error, it will be
+// returned.
+func ResolveFile(request *gus.Request, fileSystem fs.FS) (string, fs.File, error) {
+ filepath := strings.TrimPrefix(request.Path, "/")
+ file, err := fileSystem.Open(filepath)
+ if isNotFound(err) {
+ return "", nil, nil
}
+ if err != nil {
+ return "", nil, err
+ }
+
+ isDir, err := fileIsDir(file)
+ if err != nil {
+ _ = file.Close()
+ return "", nil, err
+ }
+
+ if isDir {
+ _ = file.Close()
+ return "", nil, nil
+ }
+
+ return filepath, file, nil
}
func mediaType(filePath string) string {