-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.go
More file actions
863 lines (767 loc) · 22.7 KB
/
main.go
File metadata and controls
863 lines (767 loc) · 22.7 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
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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
package main
import (
"flag"
"fmt"
"html/template"
"io"
"log"
"math"
"net/http"
"os"
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
"sync/atomic"
"time"
)
const (
filesDir = "/files"
)
var (
port string
address string
)
type FileInfo struct {
Name string
Size string
LastModified string
IsDir bool
URL string
}
// Breadcrumb segment for the current path
type Crumb struct {
Label string
URL string
}
var (
title = getEnv("TITLE", "File Server")
extraHeaders = getEnv("EXTRA_HEADERS", "")
enableUpload = getBoolEnv("ENABLE_UPLOAD", false)
enableMetrics = getBoolEnv("ENABLE_METRICS", false)
// Build information - set via ldflags during build
GitCommit = "unknown"
BuildDate = "unknown"
// Metrics
startTime = time.Now()
httpRequestsTotal atomic.Uint64
httpRequestsSuccess atomic.Uint64
httpRequestsError atomic.Uint64
uploadsTotal atomic.Uint64
uploadsSuccess atomic.Uint64
uploadsError atomic.Uint64
directoryLists atomic.Uint64
fileServes atomic.Uint64
requestDurationBuckets = map[string]map[string]*atomic.Uint64{
"GET": {
"0.1": &atomic.Uint64{},
"0.5": &atomic.Uint64{},
"1.0": &atomic.Uint64{},
"+Inf": &atomic.Uint64{},
},
"PUT": {
"0.1": &atomic.Uint64{},
"0.5": &atomic.Uint64{},
"1.0": &atomic.Uint64{},
"+Inf": &atomic.Uint64{},
},
}
requestDurationSum = map[string]*atomic.Uint64{
"GET": &atomic.Uint64{},
"PUT": &atomic.Uint64{},
}
requestDurationCount = map[string]*atomic.Uint64{
"GET": &atomic.Uint64{},
"PUT": &atomic.Uint64{},
}
)
func main() {
var enableUploadFlag bool
var enableMetricsFlag bool
var portFlag string
var addressFlag string
flag.BoolVar(&enableUploadFlag, "enable-upload", false, "Enable file uploads")
flag.BoolVar(&enableMetricsFlag, "enable-metrics", false, "Enable metrics endpoint")
flag.StringVar(&portFlag, "port", "8000", "Port to bind the server")
flag.StringVar(&addressFlag, "address", "localhost", "Address to bind the server")
flag.Parse()
// Health check command
if len(os.Args) > 1 && os.Args[1] == "health" {
resp, err := http.Get("http://" + addressFlag + ":" + portFlag)
if err != nil {
os.Exit(1)
}
defer resp.Body.Close()
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
os.Exit(0)
}
os.Exit(1)
}
port = ":" + portFlag
address = addressFlag
if enableUploadFlag {
enableUpload = true
}
if enableMetricsFlag {
enableMetrics = true
}
os.MkdirAll(filesDir, os.ModePerm)
http.HandleFunc("/", pathHandler)
http.HandleFunc("/metrics", metricsHandler)
log.Printf("Server running at http://%s%s", address, port)
if enableUpload {
log.Printf("File uploads are enabled")
} else {
log.Printf("File uploads are disabled")
}
if enableMetrics {
log.Printf("Metrics endpoint available at /metrics")
} else {
log.Printf("Metrics endpoint is disabled")
}
log.Fatal(http.ListenAndServe(port, nil))
}
func pathHandler(w http.ResponseWriter, r *http.Request) {
start := time.Now()
defer func() {
if r.URL.Path != "/metrics" {
duration := time.Since(start).Seconds()
recordRequestDuration(r.Method, duration)
}
}()
if r.URL.Path != "/metrics" {
httpRequestsTotal.Add(1)
}
if r.Method == "PUT" {
handlePutUpload(w, r)
return
}
urlPath := r.URL.Path
fullPath := filepath.Join(filesDir, urlPath)
absFilesDir, _ := filepath.Abs(filesDir)
absPath, _ := filepath.Abs(fullPath)
if !strings.HasPrefix(absPath, absFilesDir) {
if r.URL.Path != "/metrics" {
httpRequestsError.Add(1)
}
http.NotFound(w, r)
return
}
if _, err := os.Stat(filesDir); os.IsNotExist(err) {
if r.URL.Path != "/metrics" {
httpRequestsError.Add(1)
}
http.Error(w, fmt.Sprintf("files dir %s: no such directory", filesDir), http.StatusInternalServerError)
return
}
info, err := os.Stat(fullPath)
if err != nil {
if r.URL.Path != "/metrics" {
httpRequestsError.Add(1)
}
if urlPath == "/" {
http.Error(w, fmt.Sprintf("files dir %s: inaccessible or bad perms", filesDir), http.StatusInternalServerError)
} else {
http.Error(w, fmt.Sprintf("%s: no such file or directory", fullPath), http.StatusNotFound)
}
return
}
if info.IsDir() {
if !strings.HasSuffix(urlPath, "/") {
http.Redirect(w, r, urlPath+"/", http.StatusFound)
return
}
directoryLists.Add(1)
listDirectory(w, fullPath, urlPath)
} else {
fileServes.Add(1)
http.ServeFile(w, r, fullPath)
}
if r.URL.Path != "/metrics" {
httpRequestsSuccess.Add(1)
}
}
func listDirectory(w http.ResponseWriter, dirPath string, urlPath string) {
entries, err := os.ReadDir(dirPath)
if err != nil {
http.Error(w, "Error reading directory", http.StatusInternalServerError)
return
}
parentURL := "/"
if urlPath != "/" {
parts := strings.Split(strings.Trim(urlPath, "/"), "/")
if len(parts) > 1 {
parentURL = "/" + strings.Join(parts[:len(parts)-1], "/") + "/"
} else if len(parts) == 1 {
parentURL = "/"
}
}
fileInfos := make([]FileInfo, 0, len(entries))
for _, entry := range entries {
info, err := entry.Info()
if err != nil {
continue
}
entryURL := entry.Name()
var size string
if entry.IsDir() {
entryURL += "/"
subDirPath := filepath.Join(dirPath, entry.Name())
if subEntries, err := os.ReadDir(subDirPath); err == nil {
itemCount := len(subEntries)
if itemCount == 1 {
size = "1 item"
} else {
size = fmt.Sprintf("%d items", itemCount)
}
} else {
size = "-"
}
} else {
size = formatSize(info.Size())
}
fileInfos = append(fileInfos, FileInfo{
Name: entry.Name(),
Size: size,
LastModified: info.ModTime().Format("2006-01-02 15:04-07:00"),
IsDir: entry.IsDir(),
URL: entryURL,
})
}
sort.Slice(fileInfos, func(i, j int) bool {
if fileInfos[i].IsDir && !fileInfos[j].IsDir {
return true
}
if !fileInfos[i].IsDir && fileInfos[j].IsDir {
return false
}
return fileInfos[i].Name < fileInfos[j].Name
})
tmpl := template.New("index").Funcs(template.FuncMap{
"safeHTML": func(s string) template.HTML {
return template.HTML(s)
},
})
tmpl, err = tmpl.Parse(htmlTemplate)
if err != nil {
http.Error(w, "Error rendering page", http.StatusInternalServerError)
return
}
breadcrumbs := buildBreadcrumbs(urlPath)
data := struct {
CurrentPath string
ParentURL string
Files []FileInfo
Title string
ExtraHeaders string
GitCommit string
BuildDate string
DisableUpload bool
Breadcrumbs []Crumb
}{
CurrentPath: urlPath,
ParentURL: parentURL,
Files: fileInfos,
Title: title,
ExtraHeaders: extraHeaders,
GitCommit: GitCommit,
BuildDate: BuildDate,
DisableUpload: !enableUpload,
Breadcrumbs: breadcrumbs,
}
tmpl.Execute(w, data)
}
func handlePutUpload(w http.ResponseWriter, r *http.Request) {
uploadsTotal.Add(1)
if !enableUpload {
uploadsError.Add(1)
httpRequestsError.Add(1)
http.Error(w, "File uploads are disabled", http.StatusForbidden)
return
}
urlPath := r.URL.Path
fullPath := filepath.Join(filesDir, urlPath)
absFilesDir, _ := filepath.Abs(filesDir)
absPath, _ := filepath.Abs(fullPath)
if !strings.HasPrefix(absPath, absFilesDir) {
uploadsError.Add(1)
httpRequestsError.Add(1)
http.Error(w, "Invalid file path", http.StatusForbidden)
return
}
if strings.HasSuffix(urlPath, "/") {
uploadsError.Add(1)
httpRequestsError.Add(1)
http.Error(w, "Cannot upload to a directory path", http.StatusBadRequest)
return
}
// Create parent directory if it doesn't exist
parentDir := filepath.Dir(fullPath)
if err := os.MkdirAll(parentDir, os.ModePerm); err != nil {
uploadsError.Add(1)
httpRequestsError.Add(1)
http.Error(w, "Unable to create directory", http.StatusInternalServerError)
return
}
// Create or overwrite the file
dst, err := os.Create(fullPath)
if err != nil {
uploadsError.Add(1)
httpRequestsError.Add(1)
http.Error(w, "Unable to create file", http.StatusInternalServerError)
return
}
defer dst.Close()
// Copy the request body to the file
_, err = io.Copy(dst, r.Body)
if err != nil {
uploadsError.Add(1)
httpRequestsError.Add(1)
http.Error(w, "Error saving file", http.StatusInternalServerError)
return
}
uploadsSuccess.Add(1)
httpRequestsSuccess.Add(1)
w.WriteHeader(http.StatusCreated)
fmt.Fprintf(w, "File uploaded successfully to %s\n", urlPath)
}
func recordRequestDuration(method string, duration float64) {
buckets, exists := requestDurationBuckets[method]
if !exists {
return
}
requestDurationCount[method].Add(1)
durationMicros := uint64(duration * 1_000_000)
requestDurationSum[method].Add(durationMicros)
bucketThresholds := []string{"0.1", "0.5", "1.0", "+Inf"}
thresholds := []float64{0.1, 0.5, 1.0, math.Inf(1)}
for i, threshold := range thresholds {
if duration <= threshold {
buckets[bucketThresholds[i]].Add(1)
}
}
}
func metricsHandler(w http.ResponseWriter, r *http.Request) {
if !enableMetrics {
http.Error(w, "Metrics are disabled", http.StatusForbidden)
return
}
w.Header().Set("Content-Type", "text/plain; version=0.0.4; charset=utf-8")
var m runtime.MemStats
runtime.ReadMemStats(&m)
uptime := time.Since(startTime).Seconds()
fmt.Fprintf(w, "# HELP filebrowser_info Information about the file browser\n")
fmt.Fprintf(w, "# TYPE filebrowser_info gauge\n")
fmt.Fprintf(w, "filebrowser_info{version=\"%s\",build_date=\"%s\"} 1\n", GitCommit, BuildDate)
fmt.Fprintf(w, "\n")
fmt.Fprintf(w, "# HELP filebrowser_uptime_seconds Total uptime in seconds\n")
fmt.Fprintf(w, "# TYPE filebrowser_uptime_seconds gauge\n")
fmt.Fprintf(w, "filebrowser_uptime_seconds %.2f\n", uptime)
fmt.Fprintf(w, "\n")
fmt.Fprintf(w, "# HELP filebrowser_http_requests_total Total number of HTTP requests\n")
fmt.Fprintf(w, "# TYPE filebrowser_http_requests_total counter\n")
fmt.Fprintf(w, "filebrowser_http_requests_total{status=\"total\"} %d\n", httpRequestsTotal.Load())
fmt.Fprintf(w, "filebrowser_http_requests_total{status=\"success\"} %d\n", httpRequestsSuccess.Load())
fmt.Fprintf(w, "filebrowser_http_requests_total{status=\"error\"} %d\n", httpRequestsError.Load())
fmt.Fprintf(w, "\n")
fmt.Fprintf(w, "# HELP filebrowser_uploads_total Total number of file uploads\n")
fmt.Fprintf(w, "# TYPE filebrowser_uploads_total counter\n")
fmt.Fprintf(w, "filebrowser_uploads_total{status=\"total\"} %d\n", uploadsTotal.Load())
fmt.Fprintf(w, "filebrowser_uploads_total{status=\"success\"} %d\n", uploadsSuccess.Load())
fmt.Fprintf(w, "filebrowser_uploads_total{status=\"error\"} %d\n", uploadsError.Load())
fmt.Fprintf(w, "\n")
fmt.Fprintf(w, "# HELP filebrowser_operations_total Total number of file operations\n")
fmt.Fprintf(w, "# TYPE filebrowser_operations_total counter\n")
fmt.Fprintf(w, "filebrowser_operations_total{type=\"directory_list\"} %d\n", directoryLists.Load())
fmt.Fprintf(w, "filebrowser_operations_total{type=\"file_serve\"} %d\n", fileServes.Load())
fmt.Fprintf(w, "\n")
fmt.Fprintf(w, "# HELP filebrowser_http_request_duration_seconds HTTP request duration in seconds\n")
fmt.Fprintf(w, "# TYPE filebrowser_http_request_duration_seconds histogram\n")
for method, buckets := range requestDurationBuckets {
for bucket, count := range buckets {
fmt.Fprintf(w, "filebrowser_http_request_duration_seconds_bucket{le=\"%s\",method=\"%s\"} %d\n", bucket, method, count.Load())
}
sumMicros := requestDurationSum[method].Load()
sumSeconds := float64(sumMicros) / 1_000_000
fmt.Fprintf(w, "filebrowser_http_request_duration_seconds_sum{method=\"%s\"} %.6f\n", method, sumSeconds)
fmt.Fprintf(w, "filebrowser_http_request_duration_seconds_count{method=\"%s\"} %d\n", method, requestDurationCount[method].Load())
}
fmt.Fprintf(w, "\n")
fmt.Fprintf(w, "# HELP filebrowser_memory_bytes Memory usage in bytes\n")
fmt.Fprintf(w, "# TYPE filebrowser_memory_bytes gauge\n")
fmt.Fprintf(w, "filebrowser_memory_bytes{type=\"alloc\"} %d\n", m.Alloc)
fmt.Fprintf(w, "filebrowser_memory_bytes{type=\"sys\"} %d\n", m.Sys)
fmt.Fprintf(w, "filebrowser_memory_bytes{type=\"heap_alloc\"} %d\n", m.HeapAlloc)
fmt.Fprintf(w, "filebrowser_memory_bytes{type=\"heap_sys\"} %d\n", m.HeapSys)
fmt.Fprintf(w, "\n")
fmt.Fprintf(w, "# HELP filebrowser_goroutines Current number of goroutines\n")
fmt.Fprintf(w, "# TYPE filebrowser_goroutines gauge\n")
fmt.Fprintf(w, "filebrowser_goroutines %d\n", runtime.NumGoroutine())
fmt.Fprintf(w, "\n")
fmt.Fprintf(w, "# HELP filebrowser_gc_total Total number of garbage collections\n")
fmt.Fprintf(w, "# TYPE filebrowser_gc_total counter\n")
fmt.Fprintf(w, "filebrowser_gc_total %d\n", m.NumGC)
fmt.Fprintf(w, "\n")
fmt.Fprintf(w, "# HELP filebrowser_config Configuration settings\n")
fmt.Fprintf(w, "# TYPE filebrowser_config gauge\n")
if enableUpload {
fmt.Fprintf(w, "filebrowser_config{setting=\"uploads_enabled\"} 1\n")
} else {
fmt.Fprintf(w, "filebrowser_config{setting=\"uploads_disabled\"} 1\n")
}
}
func formatSize(bytes int64) string {
const unit = 1024
if bytes < unit {
return fmt.Sprintf("%d B", bytes)
}
div, exp := int64(unit), 0
for n := bytes / unit; n >= unit; n /= unit {
div *= unit
exp++
}
return fmt.Sprintf("%.1f %cB", float64(bytes)/float64(div), "KMGTPE"[exp])
}
func getEnv(key, defaultValue string) string {
if value, exists := os.LookupEnv(key); exists {
return value
}
return defaultValue
}
func getBoolEnv(key string, defaultValue bool) bool {
if value, exists := os.LookupEnv(key); exists {
if parsed, err := strconv.ParseBool(value); err == nil {
return parsed
}
}
return defaultValue
}
func buildBreadcrumbs(urlPath string) []Crumb {
crumbs := []Crumb{{Label: "/", URL: "/"}}
clean := strings.Trim(urlPath, "/")
if clean == "" {
return crumbs
}
parts := strings.Split(clean, "/")
current := "/"
for _, p := range parts {
current += p + "/"
crumbs = append(crumbs, Crumb{Label: p + "/", URL: current})
}
return crumbs
}
const htmlTemplate = `<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{.Title}}</title>
<link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'><text y='14' font-size='14'>📁</text></svg>">
{{.ExtraHeaders | safeHTML}}
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
:root {
--bg-color: #fff;
--text-color: #000;
--header-bg: #f0f0f0;
--border-color: #ddd;
--border-light: #eee;
--row-even: #f8f8f8;
--footer-bg: #f0f0f0;
--footer-text: #666;
--footer-height: 30px;
--table-margin: 10px;
}
@media (prefers-color-scheme: dark) {
:root {
--bg-color: #1a1a1a;
--text-color: #e0e0e0;
--header-bg: #2a2a2a;
--border-color: #444;
--border-light: #333;
--row-even: #252525;
--footer-bg: #2a2a2a;
--footer-text: #888;
}
}
[data-theme="dark"] {
--bg-color: #1a1a1a;
--text-color: #e0e0e0;
--header-bg: #2a2a2a;
--border-color: #444;
--border-light: #333;
--row-even: #252525;
--footer-bg: #2a2a2a;
--footer-text: #888;
}
[data-theme="light"] {
--bg-color: #fff;
--text-color: #000;
--header-bg: #f0f0f0;
--border-color: #ddd;
--border-light: #eee;
--row-even: #f8f8f8;
--footer-bg: #f0f0f0;
--footer-text: #666;
}
body {
font-family: monospace;
font-size: 14px;
background: var(--bg-color);
color: var(--text-color);
height: 100vh;
display: flex;
flex-direction: column;
}
header {
background: var(--header-bg);
padding: 10px;
border-bottom: 1px solid var(--border-color);
display: flex;
flex-direction: column;
gap: 10px;
flex-shrink: 0;
}
main {
flex: 1;
overflow: auto;
padding-bottom: var(--footer-height);
}
table {
width: calc(100% - calc(2 * var(--table-margin)));
border-collapse: collapse;
margin: var(--table-margin);
}
th {
text-align: left;
padding: 8px 4px;
border-bottom: 1px solid var(--border-color);
position: sticky;
top: 0;
background: var(--bg-color);
z-index: 10;
}
td {
padding: 8px 4px;
border-bottom: 1px solid var(--border-light);
white-space: nowrap;
}
tr:nth-child(even) { background: var(--row-even); }
.name { width: 60%; overflow: hidden; text-overflow: ellipsis; }
.size { width: 15%; }
.date { width: 25%; }
.upload-form { display: flex; align-items: center; gap: 5px; }
.search-box {
padding: 4px;
width: 100%;
font-family: monospace;
background: var(--bg-color);
color: var(--text-color);
border: 1px solid var(--border-color);
}
input[type="file"] {
display: none;
}
.file-input-label {
flex-grow: 1;
padding: 4px 8px;
background: var(--header-bg);
color: var(--text-color);
border: 1px solid var(--border-color);
cursor: pointer;
font-family: monospace;
font-size: 14px;
text-align: left;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
.file-input-label:hover { opacity: 0.8; }
.file-input-label:disabled,
.file-input-label.disabled {
opacity: 0.5;
cursor: not-allowed;
}
.file-input-label.disabled::after {
content: " 🚫";
color: #999;
}
.drag-disabled {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: var(--header-bg);
border: 2px solid var(--border-color);
padding: 10px 20px;
border-radius: 4px;
font-size: 16px;
z-index: 1000;
display: none;
}
button {
padding: 4px 8px;
background: var(--header-bg);
color: var(--text-color);
border: 1px solid var(--border-color);
cursor: pointer;
}
button:hover { opacity: 0.8; }
button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
a { color: var(--text-color); }
header h1 a { text-decoration: none; }
header h1 a:hover { text-decoration: underline; }
footer {
position: fixed;
bottom: 0;
left: 0;
right: 0;
background: var(--footer-bg);
padding: 5px 40px 5px 10px;
border-top: 1px solid var(--border-color);
font-size: 11px;
color: var(--footer-text);
}
.theme-toggle {
position: absolute;
right: 5px;
top: 50%;
transform: translateY(-50%);
padding: 4px 8px;
background: var(--header-bg);
border: 1px solid var(--border-color);
color: var(--text-color);
cursor: pointer;
font-size: 11px;
margin: 0;
}
.theme-toggle:hover { opacity: 0.8; }
</style>
</head>
<body>
<header>
<h1>{{range .Breadcrumbs}}<a href="{{.URL}}">{{.Label}}</a>{{end}}</h1>
<input type="text" id="search" class="search-box" placeholder="Filter by filename..." autocomplete="off">
<div class="upload-form">
<input type="file" id="file-input" {{if .DisableUpload}}disabled{{end}}>
<label for="file-input" class="file-input-label{{if .DisableUpload}} disabled{{end}}" id="file-label">
{{if .DisableUpload}}Uploads disabled{{else}}Choose file...{{end}}
</label>
<button id="upload-btn" {{if .DisableUpload}}disabled{{end}}>Upload</button>
</div>
</header>
<main>
<table id="file-table">
<thead>
<tr>
<th class="name">Name</th>
<th class="size">Size</th>
<th class="date">Last Modified</th>
</tr>
</thead>
<tbody>
{{if ne .CurrentPath "/"}}
<tr class="filerow">
<td class="name">📁 <a href="{{.ParentURL}}">..</a></td>
<td class="size">-</td>
<td class="date">-</td>
</tr>
{{end}}
{{range .Files}}
<tr class="filerow">
<td class="name">
{{if .IsDir}}📁{{else}}📄{{end}}
<a href="{{.URL}}">{{.Name}}{{if .IsDir}}/{{end}}</a>
</td>
<td class="size">{{.Size}}</td>
<td class="date">{{.LastModified}}</td>
</tr>
{{end}}
</tbody>
</table>
</main>
<footer>
Build: {{.GitCommit}} | {{.BuildDate}}
<button class="theme-toggle" onclick="toggleTheme()" title="Toggle theme">🌓</button>
</footer>
<div id="drag-message" class="drag-disabled"></div>
<script>
function toggleTheme() {
const html = document.documentElement;
const current = html.getAttribute('data-theme');
const next = current === 'dark' ? 'light' : 'dark';
html.setAttribute('data-theme', next);
}
const fileInput = document.getElementById('file-input');
const uploadBtn = document.getElementById('upload-btn');
const dragMessage = document.getElementById('drag-message');
const currentPath = '{{.CurrentPath}}';
async function uploadFile(file) {
const uploadPath = currentPath + file.name;
try {
const response = await fetch(uploadPath, {
method: 'PUT',
body: file
});
if (response.ok) {
window.location.reload();
} else {
const error = await response.text();
alert('Upload failed: ' + error);
}
} catch (error) {
alert('Upload failed: ' + error.message);
}
}
fileInput.addEventListener('change', function(e) {
const label = document.getElementById('file-label');
if (e.target.disabled) return;
const fileName = e.target.files[0]?.name || 'Choose file...';
label.textContent = fileName;
});
uploadBtn.addEventListener('click', function() {
if (fileInput.disabled || !fileInput.files[0]) return;
uploadFile(fileInput.files[0]);
});
document.getElementById('search').addEventListener('input', function(e) {
const term = e.target.value.toLowerCase();
const rows = document.querySelectorAll('.filerow');
rows.forEach(row => {
const link = row.querySelector('.name a');
if (!link) return;
const name = link.textContent.toLowerCase();
if (link.textContent === '..') return;
row.style.display = name.includes(term) ? '' : 'none';
});
});
// Drag and drop functionality
function showDragMessage(text) {
dragMessage.className = 'drag-disabled';
dragMessage.textContent = text;
dragMessage.style.display = 'block';
}
function hideDragMessage() {
dragMessage.style.display = 'none';
}
document.addEventListener('dragover', function(e) {
e.preventDefault();
const text = fileInput.disabled ? '🚫 Uploads disabled' : '📁 Drop to upload';
showDragMessage(text);
});
document.addEventListener('dragleave', function(e) {
if (!e.relatedTarget) hideDragMessage();
});
document.addEventListener('drop', function(e) {
e.preventDefault();
hideDragMessage();
if (!fileInput.disabled && e.dataTransfer.files.length > 0) {
const file = e.dataTransfer.files[0];
uploadFile(file);
}
});
</script>
</body>
</html>`