-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandlers.go
More file actions
211 lines (171 loc) · 5.66 KB
/
Copy pathhandlers.go
File metadata and controls
211 lines (171 loc) · 5.66 KB
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
package api
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/gorilla/mux"
)
// Entry describes a file or directory returned by the list endpoint.
type Entry struct {
Path string `json:"path"`
Size int64 `json:"size"`
IsDir bool `json:"isDir"`
ModTime time.Time `json:"modTime"`
}
// DeleteResult describes the outcome of a delete request.
type DeleteResult struct {
Deleted int `json:"deleted"`
Paths []string `json:"paths"`
}
// listHandler handles GET /api/list/{path}.
// It returns the contents of all directories matching the (possibly glob) path.
// A final /* is always appended so the response contains entries rather than
// the matched directories themselves — clients should omit the trailing wildcard.
func (a *API) listHandler(resp http.ResponseWriter, r *http.Request) {
rawPath := mux.Vars(r)["path"]
pattern, err := a.safePath(rawPath)
if err != nil {
writeError(resp, http.StatusBadRequest, err.Error())
return
}
// Append /* to list contents of each matched directory.
pattern = filepath.Join(pattern, "*")
matches, err := a.globSafe(pattern)
if err != nil {
writeError(resp, http.StatusInternalServerError, err.Error())
return
}
entries := make([]Entry, 0, len(matches))
for _, match := range matches {
info, statErr := os.Lstat(match)
if statErr != nil {
continue
}
relPath := strings.TrimPrefix(match, a.outputPath+string(filepath.Separator))
entries = append(entries, Entry{
Path: relPath,
Size: info.Size(),
IsDir: info.IsDir(),
ModTime: info.ModTime().UTC(),
})
}
writeJSON(resp, http.StatusOK, entries, strconv.Itoa(len(entries))+" entries")
}
// fileHandler handles GET /api/file/{path} and streams the file contents.
// Wildcards are not permitted; use /api/list/ first to find file paths.
func (a *API) fileHandler(resp http.ResponseWriter, req *http.Request) {
rawPath := mux.Vars(req)["path"]
filePath, err := a.safePath(rawPath)
if err != nil {
writeError(resp, http.StatusBadRequest, err.Error())
return
}
if strings.ContainsRune(filePath, '*') {
writeError(resp, http.StatusBadRequest, "wildcards not allowed for file fetch; use /api/list/ first")
return
}
info, err := os.Stat(filePath)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
writeError(resp, http.StatusNotFound, "not found: "+filePath)
} else {
writeError(resp, http.StatusInternalServerError, "stat: "+err.Error())
}
return
}
if info.IsDir() {
writeError(resp, http.StatusBadRequest, "path is a directory; use /api/list/")
return
}
fileHandle, err := os.Open(filePath) //nolint:gosec // path validated against outputPath
if err != nil {
writeError(resp, http.StatusInternalServerError, "opening file: "+err.Error())
return
}
defer fileHandle.Close()
http.ServeContent(resp, req, info.Name(), info.ModTime(), fileHandle)
}
// deleteHandler handles DELETE /api/glob/{path} and removes all files or directories
// matching the path. The path may contain * wildcards in any segment.
func (a *API) deleteHandler(resp http.ResponseWriter, r *http.Request) {
rawPath := mux.Vars(r)["path"]
pattern, err := a.safePath(rawPath)
if err != nil {
writeError(resp, http.StatusBadRequest, err.Error())
return
}
matches, err := a.resolveForDelete(pattern)
if err != nil {
writeError(resp, http.StatusInternalServerError, err.Error())
return
}
deleted := make([]string, 0, len(matches))
for _, match := range matches {
err = os.RemoveAll(match)
if err == nil {
deleted = append(deleted, strings.TrimPrefix(match, a.outputPath+string(filepath.Separator)))
}
}
writeJSON(resp, http.StatusOK, DeleteResult{Deleted: len(deleted), Paths: deleted}, strconv.Itoa(len(deleted))+" deleted")
}
// resolveForDelete returns the filesystem paths to act on for the given pattern.
// When the pattern contains no wildcard it returns the pattern if it exists.
func (a *API) resolveForDelete(pattern string) ([]string, error) {
if !strings.ContainsRune(pattern, '*') {
_, err := os.Stat(pattern)
if errors.Is(err, os.ErrNotExist) {
return nil, nil
}
if err != nil {
return nil, fmt.Errorf("stat: %w", err)
}
return []string{pattern}, nil
}
return a.globSafe(pattern)
}
// deleteAllHandler handles DELETE /api/all and removes every entry directly
// inside outputPath, including directories.
func (a *API) deleteAllHandler(resp http.ResponseWriter, _ *http.Request) {
entries, err := os.ReadDir(a.outputPath)
if err != nil && !errors.Is(err, os.ErrNotExist) {
writeError(resp, http.StatusInternalServerError, "reading output path: "+err.Error())
return
}
var count int
for _, entry := range entries {
removeErr := os.RemoveAll(filepath.Join(a.outputPath, entry.Name()))
if removeErr == nil {
count++
}
}
writeJSON(resp, http.StatusOK, DeleteResult{Deleted: count, Paths: []string{a.outputPath}}, strconv.Itoa(count)+" deleted")
}
// writeJSON writes data as a JSON response body with the given status code.
func writeJSON(resp http.ResponseWriter, status int, data any, info string) {
body, err := json.Marshal(data)
if err != nil {
http.Error(resp, `{"error":"internal server error"}`, http.StatusInternalServerError)
return
}
if info != "" {
resp.Header().Set("X-Info", info)
}
resp.Header().Set("Content-Type", "application/json")
resp.WriteHeader(status)
_, _ = resp.Write(body)
}
// writeError writes a JSON error response.
func writeError(resp http.ResponseWriter, status int, msg string) {
const maxInfoLength = 100
info := strings.TrimSpace(msg)
if len(info) > maxInfoLength {
info = info[:maxInfoLength] + "..."
}
writeJSON(resp, status, map[string]string{"error": msg}, info)
}