forked from h2oai/wave
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile_server.go
80 lines (69 loc) · 2.25 KB
/
file_server.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
// Copyright 2020 H2O.ai, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package wave
import (
"errors"
"net/http"
"os"
"path"
"path/filepath"
"strings"
)
// FileServer represents a file server.
type FileServer struct {
dir string
handler http.Handler
}
func newFileServer(dir string) http.Handler {
return &FileServer{
dir,
http.FileServer(http.Dir(dir)),
}
}
var (
errInvalidUnloadPath = errors.New("invalid file path")
)
func (fs *FileServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
if path.Ext(r.URL.Path) == "" { // ignore requests for directories and ext-less files
echo(Log{"t": "file_download", "path": r.URL.Path, "error": "not found"})
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
return
}
echo(Log{"t": "file_download", "path": r.URL.Path})
r.URL.Path = strings.TrimPrefix(r.URL.Path, "/_f") // public
fs.handler.ServeHTTP(w, r)
case http.MethodDelete: // TODO garbage collection
if err := fs.unloadFile(r.URL.Path); err != nil {
echo(Log{"t": "file_unload", "path": r.URL.Path, "error": err.Error()})
return
}
echo(Log{"t": "file_unload", "path": r.URL.Path})
default:
echo(Log{"t": "file_download", "method": r.Method, "path": r.URL.Path, "error": "method not allowed"})
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
}
}
func (fs *FileServer) unloadFile(url string) error {
tokens := strings.Split(path.Clean(url), "/")
if len(tokens) != 4 { // /_f/uuid/file.ext
return errInvalidUnloadPath
}
if tokens[0] != "" || tokens[1] != "_f" || path.Ext(tokens[3]) == "" {
return errInvalidUnloadPath
}
dirpath := filepath.Join(fs.dir, tokens[2])
return os.RemoveAll(dirpath)
}