-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
filesystem.go
221 lines (192 loc) · 4.93 KB
/
filesystem.go
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
package middleware
import (
"fmt"
"html"
"log"
"net/http"
"os"
"path"
"sort"
"strings"
fiber "github.com/gofiber/fiber"
)
// Middleware types
type (
// FileSystemConfig defines the config for FileSystem middleware.
FileSystemConfig struct {
// Next defines a function to skip this middleware if returned true.
Next func(ctx *fiber.Ctx) bool
// Root is a FileSystem that provides access
// to a collection of files and directories.
// Required. Default: nil
Root http.FileSystem
// Index file for serving a directory.
// Optional. Default: "index.html"
Index string
// Enable directory browsing.
// Optional. Default: false
Browse bool
}
)
// FileSystemConfigDefault is the default config
var FileSystemConfigDefault = FileSystemConfig{
Next: nil,
Root: nil,
Index: "/index.html",
Browse: false,
}
/*
FileSystem allows the following config arguments in any order:
- FileSystem(root http.FileSystem)
- FileSystem(index string)
- FileSystem(browse bool)
- FileSystem(config FileSystem)
- FileSystem(next func(*fiber.Ctx) bool)
*/
func FileSystem(options ...interface{}) fiber.Handler {
// Create default config
var config = FileSystemConfigDefault
// Assert options if provided to adjust the config
for i := range options {
switch opt := options[i].(type) {
case func(*fiber.Ctx) bool:
config.Next = opt
case http.FileSystem:
config.Root = opt
case string:
config.Index = opt
case bool:
config.Browse = opt
case FileSystemConfig:
config = opt
default:
log.Fatal("FileSystem: the following option types are allowed: string, bool, http.FileSystem, FileSystemConfig")
}
}
// Return fileSystem
return fileSystem(config)
}
func fileSystem(config FileSystemConfig) fiber.Handler {
// Set config default values
if config.Index == "" {
config.Index = FileSystemConfigDefault.Index
}
if !strings.HasPrefix(config.Index, "/") {
config.Index = "/" + config.Index
}
if config.Root == nil {
log.Fatal("FileSystem: Root value is missing!")
}
// Middleware settings
var prefix string
// Return handler
return func(c *fiber.Ctx) {
// Set prefix
if len(prefix) == 0 {
prefix = c.Route().Path
}
// Strip prefix
path := strings.TrimPrefix(c.Path(), prefix)
if !strings.HasPrefix(path, "/") {
path = "/" + path
}
file, err := config.Root.Open(path)
if err != nil {
c.Next(err)
return
}
stat, err := file.Stat()
if err != nil {
c.Next(err)
return
}
// Serve index if path is directory
if stat.IsDir() {
indexPath := strings.TrimSuffix(path, "/") + config.Index
index, err := config.Root.Open(indexPath)
if err == nil {
indexStat, err := index.Stat()
if err == nil {
file = index
stat = indexStat
}
}
}
// Browse directory if no index found and browsing is enabled
if stat.IsDir() {
if config.Browse {
if err := dirList(c, file); err != nil {
c.Next(err)
}
return
}
c.SendStatus(fiber.StatusForbidden)
return
}
modTime := stat.ModTime()
contentLength := int(stat.Size())
// Set Content Type header
c.Type(getFileExtension(stat.Name()))
// Set Last Modified header
if !modTime.IsZero() {
c.Set(fiber.HeaderLastModified, modTime.UTC().Format(http.TimeFormat))
}
if c.Method() == fiber.MethodGet {
c.Fasthttp.SetBodyStream(file, contentLength)
return
} else if c.Method() == fiber.MethodHead {
c.Fasthttp.ResetBody()
c.Fasthttp.Response.SkipBody = true
c.Fasthttp.Response.Header.SetContentLength(contentLength)
if err := file.Close(); err != nil {
c.Next(err)
}
return
}
c.Next()
}
}
func getFileExtension(path string) string {
n := strings.LastIndexByte(path, '.')
if n < 0 {
return ""
}
return path[n:]
}
func dirList(c *fiber.Ctx, f http.File) error {
fileinfos, err := f.Readdir(-1)
if err != nil {
return err
}
fm := make(map[string]os.FileInfo, len(fileinfos))
filenames := make([]string, 0, len(fileinfos))
for _, fi := range fileinfos {
name := fi.Name()
fm[name] = fi
filenames = append(filenames, name)
}
basePathEscaped := html.EscapeString(c.Path())
c.Write(fmt.Sprintf("<html><head><title>%s</title><style>.dir { font-weight: bold }</style></head><body>", basePathEscaped))
c.Write(fmt.Sprintf("<h1>%s</h1>", basePathEscaped))
c.Write("<ul>")
if len(basePathEscaped) > 1 {
parentPathEscaped := html.EscapeString(c.Path() + "/..")
c.Write(fmt.Sprintf(`<li><a href="%s" class="dir">..</a></li>`, parentPathEscaped))
}
sort.Strings(filenames)
for _, name := range filenames {
pathEscaped := html.EscapeString(path.Join(c.Path() + "/" + name))
fi := fm[name]
auxStr := "dir"
className := "dir"
if !fi.IsDir() {
auxStr = fmt.Sprintf("file, %d bytes", fi.Size())
className = "file"
}
c.Write(fmt.Sprintf(`<li><a href="%s" class="%s">%s</a>, %s, last modified %s</li>`,
pathEscaped, className, html.EscapeString(name), auxStr, fi.ModTime()))
}
c.Write("</ul></body></html>")
c.Type("html")
return nil
}