-
Notifications
You must be signed in to change notification settings - Fork 0
/
quickgo_http.go
362 lines (311 loc) · 9.8 KB
/
quickgo_http.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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
package quickgo
import (
"archive/zip"
"bytes"
"fmt"
html_template "html/template"
"io"
"net/http"
"os"
"path"
"path/filepath"
"strings"
"github.com/Nigel2392/goldcrest"
"github.com/Nigel2392/quickgo/v2/quickgo/config"
"github.com/Nigel2392/quickgo/v2/quickgo/logger"
"github.com/Nigel2392/quickgo/v2/quickgo/quickfs"
"github.com/pkg/errors"
)
func copyToZipfile(z *zip.Writer, name string, absPath string) error {
var f, err = os.Open(absPath)
if err != nil {
return errors.Wrapf(err, "failed to open '%s'", absPath)
}
defer f.Close()
w, err := z.Create(name)
if err != nil {
return errors.Wrapf(err, "failed to create '%s'", name)
}
_, err = io.Copy(w, f)
return err
}
func (a *App) HttpHandler() http.Handler {
var mux = http.NewServeMux()
mux.Handle("/", &LogHandler{
Handler: http.HandlerFunc(a.serveIndex),
Where: "index",
Level: logger.InfoLevel,
})
mux.Handle("/projects/", &LogHandler{
Handler: http.StripPrefix(
"/projects/",
http.HandlerFunc(a.serveProjects),
),
Where: "projects",
Level: logger.InfoLevel,
})
mux.Handle("/config/", &LogHandler{
Handler: http.StripPrefix(
"/config/",
http.HandlerFunc(a.serveProjectConfig),
),
Where: "project config",
Level: logger.InfoLevel,
})
mux.Handle("/static/", &LogHandler{
Handler: http.StripPrefix("/static/", http.FileServer(http.FS(staticFS))),
Where: "static files",
Level: logger.DebugLevel,
})
mux.Handle("/favicon.ico", &LogHandler{
Handler: http.HandlerFunc(a.serveFavicon),
Where: "favicon",
Level: logger.DebugLevel,
})
return a.middleware(mux)
}
func (a *App) serveIndex(w http.ResponseWriter, r *http.Request) {
var projects, err = a.ListProjectObjects()
if err != nil {
logger.Errorf("Failed to list projects: %v", err)
http.Error(w, "Failed to list projects", http.StatusInternalServerError)
return
}
var ctx = &ProjectTemplateContext{
ObjectList: projects,
}
if err = a.executeServeTemplate(w, "index.tmpl", ctx); err != nil {
logger.Errorf("Failed to render index: %v", err)
http.Error(w, "Failed to render index", http.StatusInternalServerError)
}
}
func (a *App) serveProjects(w http.ResponseWriter, r *http.Request) {
var (
proj *config.Project
parent *quickfs.FSDirectory
fileLike quickfs.FileLike
err error
)
var pathParts = strings.Split(strings.Trim(r.URL.Path, "/"), "/")
if r.URL.Query().Get("download") != "" && len(pathParts) == 1 {
var (
projName = pathParts[0]
projPath = GetProjectDirectoryPath(projName, true)
configFile = filepath.Join(projPath, config.PROJECT_CONFIG_NAME)
projectZip = filepath.Join(projPath, config.PROJECT_ZIP_NAME)
)
w.Header().Set("Content-Type", "application/zip")
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s.zip", projName))
var zf = zip.NewWriter(w)
defer zf.Close()
logger.Debugf("Adding '%s' to zip for export", configFile)
if err = copyToZipfile(zf, config.PROJECT_CONFIG_NAME, configFile); err != nil {
logger.Errorf("Failed to copy '%s' to zip: %v", configFile, err)
http.Error(w, "Failed to copy to zip", http.StatusInternalServerError)
return
}
logger.Debugf("Adding '%s' to zip for export", projectZip)
if err = copyToZipfile(zf, config.PROJECT_ZIP_NAME, projectZip); err != nil {
logger.Errorf("Failed to copy '%s' to zip: %v", projectZip, err)
http.Error(w, "Failed to copy to zip", http.StatusInternalServerError)
return
}
logger.Infof("%s Downloaded project '%s'", r.RemoteAddr, projName)
return
}
logger.Debugf("Reading project '%s'", pathParts[0])
proj, closeFiles, err := a.ReadProjectConfig(pathParts[0])
if err != nil {
logger.Errorf("Failed to read project '%s': %v", pathParts[0], err)
http.Error(w, "Invalid project", http.StatusBadRequest)
return
}
defer func() {
logger.Debugf("Closing project '%s'", proj.Name)
closeFiles()
}()
parent, fileLike, err = proj.Root.FindWithParent(pathParts[1:])
if err != nil {
logger.Errorf("Failed to find file '%s': %v", path.Join(pathParts...), err)
http.Error(w, "Invalid path", http.StatusBadRequest)
return
}
var context = ProjectTemplateContext{
Project: proj,
Parent: parent,
}
if fileLike.IsDir() {
var dir = fileLike.(*quickfs.FSDirectory)
var FileObjects = make([]quickfs.FileLike, 0)
dir.ForEach(false, func(fl quickfs.FileLike) (cancel bool, err error) {
FileObjects = append(FileObjects, fl)
return false, nil
})
context.Dir = dir
context.ObjectList = FileObjects
logger.Debugf("Serving directory '%s' in project '%s'", dir.Name, proj.Name)
if err = a.executeServeTemplate(w, "dir.tmpl", &context); err != nil {
logger.Errorf("Failed to render directory object in project '%s': %v", proj.Name, err)
http.Error(w, "Failed to render directory in project", http.StatusInternalServerError)
}
return
}
var b = new(bytes.Buffer)
var file = fileLike.(*quickfs.FSFile)
if _, err = io.Copy(b, file); err != nil {
logger.Errorf("Failed to read file '%s': %v", file.GetPath(), err)
http.Error(w, "Failed to read file", http.StatusInternalServerError)
return
}
var content = b.String()
file.IsText = quickfs.IsText(content)
if !file.IsText {
w.Header().Set("Content-Type", "application/octet-stream")
w.Header().Set("Content-Disposition", "attachment; filename="+file.GetPath())
if _, err = io.Copy(w, b); err != nil {
http.Error(w, "Failed to read file", http.StatusInternalServerError)
}
return
}
context.File = file
context.Content = content
logger.Debugf("Serving file '%s' in project '%s'", file.Name, proj.Name)
if err = a.executeServeTemplate(w, "file.tmpl", &context); err != nil {
logger.Errorf("Failed to render file object in project '%s': %v", proj.Name, err)
http.Error(w, "Failed to render file in project", http.StatusInternalServerError)
}
}
func (a *App) serveProjectConfig(w http.ResponseWriter, r *http.Request) {
var pathParts = strings.Split(strings.Trim(r.URL.Path, "/"), "/")
if len(pathParts) != 1 {
http.Error(w, "Invalid path", http.StatusBadRequest)
return
}
var configFile, err = os.ReadFile(
GetProjectDirectoryPath(path.Join(pathParts[0], config.PROJECT_CONFIG_NAME), true),
)
if err != nil {
logger.Errorf("Failed to open project '%s': %v", pathParts[0], err)
http.Error(w, "Failed to open project", http.StatusInternalServerError)
return
}
var ctx = &ProjectTemplateContext{
// Fake for breadcrumbs
Dir: &quickfs.FSDirectory{
Name: pathParts[0],
},
// Config YAML data
Content: string(configFile),
}
if err = a.executeServeTemplate(w, "file.tmpl", ctx); err != nil {
logger.Errorf("Failed to render project config: %v", err)
http.Error(w, "Failed to render project config", http.StatusInternalServerError)
}
}
func (a *App) serveFavicon(w http.ResponseWriter, r *http.Request) {
// Write out the favicon file.
// No need to log the happy path here, quite boring.
var f, err = staticFS.Open("quickgo.png")
if err != nil {
logger.Errorf("Failed to open 'quickgo.png': %v", err)
http.Error(w, "Failed to open 'quickgo.png'", http.StatusInternalServerError)
return
}
defer f.Close()
w.Header().Set("Content-Type", "image/x-icon")
if _, err = io.Copy(w, f); err != nil {
logger.Errorf("Failed to read 'quickgo.png': %v", err)
http.Error(w, "Failed to read 'quickgo.png'", http.StatusInternalServerError)
}
}
func (a *App) middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
http.Error(w, "Internal server error", http.StatusInternalServerError)
}
}()
for _, hook := range goldcrest.Get[AppServeHook](HookQuickGoServer) {
if served, err := hook(a, w, r); err != nil {
logger.Errorf("Failed to serve: %v", err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
} else if served {
logger.Debugf("'%s' was served and hijacked by a hook", r.URL.Path)
return
}
}
next.ServeHTTP(w, r)
})
}
type LogHandler struct {
Handler http.Handler
Level logger.LogLevel
Where string
}
func (h *LogHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var s = fmt.Sprintf("Serving %s to %s on path '%s'", h.Where, r.RemoteAddr, r.URL.Path)
switch h.Level {
case logger.DebugLevel:
logger.Debug(s)
case logger.InfoLevel:
logger.Info(s)
case logger.WarnLevel:
logger.Warn(s)
case logger.ErrorLevel:
logger.Error(s)
}
h.Handler.ServeHTTP(w, r)
}
type ProjectTemplateContext struct {
Project *config.Project
File *quickfs.FSFile
Dir *quickfs.FSDirectory
Parent *quickfs.FSDirectory
ObjectList any
Content string
}
func (a *App) executeServeTemplate(w http.ResponseWriter, name string, context *ProjectTemplateContext) (err error) {
var tpl = html_template.New("base")
tpl = tpl.Funcs(html_template.FuncMap{
"ObjectURL": func(fl quickfs.FileLike) string {
return filepath.ToSlash(path.Join(
"/projects",
context.Project.Name,
fl.GetPath(),
))
},
"ProjectURL": func(project *config.Project) string {
return filepath.ToSlash(path.Join(
"/projects",
project.Name,
))
},
"ConfigURL": func(project *config.Project) string {
return filepath.ToSlash(path.Join(
"/config",
project.Name,
))
},
"FileSize": func(size int64) string {
f_size := float64(size)
if f_size < 1024 {
return fmt.Sprintf("%d b", int(f_size))
}
f_size = f_size / 1024
if f_size < 1024 {
return fmt.Sprintf("%.1f KB", f_size)
}
f_size = f_size / 1024
if f_size < 1024 {
return fmt.Sprintf("%.1f MB", f_size)
}
f_size = f_size / 1024
return fmt.Sprintf("%.1f GB", f_size)
},
})
if tpl, err = tpl.ParseFS(embedFS, append(a.Patterns, fmt.Sprintf("_templates/%s", name))...); err != nil {
return errors.Wrapf(err, "failed to parse template %s", name)
}
return tpl.ExecuteTemplate(w, name, context)
}