summaryrefslogtreecommitdiff
path: root/contrib/fs/file.go
diff options
context:
space:
mode:
authortjpcc <tjp@ctrl-c.club>2023-01-28 14:52:35 -0700
committertjpcc <tjp@ctrl-c.club>2023-01-28 15:01:41 -0700
commit66a1b1f39a1e1d5499b548b36d18c8daa872d7da (patch)
tree96471dbd5486ede1a908790ac23e0c55b226dfad /contrib/fs/file.go
parenta27b879accb191b6a6c6e76a6251ed751967f73a (diff)
gopher support.
Some of the contrib packages were originally built gemini-specific and had to be refactored into generic core functionality and thin protocol-specific wrappers for each of gemini and gopher.
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 {