blob: 71428edec95101f1155e1cc991267cce65772e59 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
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)
}
}
func mediaType(filePath string) string {
if strings.HasSuffix(filePath, ".gmi") {
// This may not be present in the listings searched by mime.TypeByExtension,
// so provide a dedicated fast path for it here.
return "text/gemini"
}
slashIdx := strings.LastIndex(filePath, "/")
dotIdx := strings.LastIndex(filePath[slashIdx+1:], ".")
if dotIdx == -1 {
return "application/octet-stream"
}
ext := filePath[slashIdx+1+dotIdx:]
mtype := mime.TypeByExtension(ext)
if mtype == "" {
return "application/octet-stream"
}
return mtype
}
|