-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmain.go
More file actions
985 lines (848 loc) · 25 KB
/
main.go
File metadata and controls
985 lines (848 loc) · 25 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
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
package main
import (
"context"
"crypto/subtle"
"embed"
"flag"
"fmt"
"html/template"
"io"
"log"
"net/http"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
)
//go:embed templates/*
var templateFS embed.FS
var templates *template.Template
var (
addr string
workingDir string
intelligentMIME bool
customMIMETypes map[string]string
customMIMEViewable map[string]bool
authRules []AuthRule
authEnabled bool
)
// AuthRule represents an authentication and authorization rule
type AuthRule struct {
Username string
Password string
Permission string // "r" (read), "w" (write), "rw" (read+write), or "" (any username with password)
Pattern *regexp.Regexp
}
// UserContext stores authenticated user information
type UserContext struct {
Username string
Rules []AuthRule
}
type FileInfo struct {
Name string
Path string
Size int64
ModTime time.Time
IsDir bool
}
type PageData struct {
CurrentPath string
ParentPath string
Files []FileInfo
Error string
}
func init() {
var err error
funcMap := template.FuncMap{
"formatSize": formatSize,
"formatDate": formatDate,
"splitPath": splitPath,
"joinPath": joinPath,
}
templates, err = template.New("").Funcs(funcMap).ParseFS(templateFS, "templates/*.html")
if err != nil {
log.Fatal("Failed to parse templates:", err)
}
}
// formatSize formats file size in human-readable format
func formatSize(size int64) string {
const unit = 1024
if size < unit {
return fmt.Sprintf("%d B", size)
}
div, exp := int64(unit), 0
for n := size / unit; n >= unit; n /= unit {
div *= unit
exp++
}
return fmt.Sprintf("%.1f %cB", float64(size)/float64(div), "KMGTPE"[exp])
}
// formatDate formats time in human-readable format
func formatDate(t time.Time) string {
return t.Format("2006-01-02 15:04:05")
}
// splitPath splits a path into components
func splitPath(path string) []string {
return strings.Split(filepath.Clean(path), string(filepath.Separator))
}
// joinPath joins path components
func joinPath(parts ...string) string {
return filepath.Join(parts...)
}
// authFlags is a custom flag type to collect multiple -auth flags
type authFlags []string
func (a *authFlags) String() string {
return strings.Join(*a, ",")
}
func (a *authFlags) Set(value string) error {
*a = append(*a, value)
return nil
}
func main() {
// Parse command-line flags
hostFlag := flag.String("host", "0.0.0.0", "Address to listen on")
portFlag := flag.String("port", "8080", "Port to listen on")
dirFlag := flag.String("dir", "", "Working directory to serve files from (default: current directory)")
intelligentMIMEFlag := flag.String("i", "", "Enable intelligent MIME recognition. Use 'true' for defaults, or specify custom mappings like 'ext1,ext2:mime/type;ext3:mime/type2,v' (,v indicates viewable)")
// Define auth flag to collect multiple -auth flags
var authFlagValues authFlags
flag.Var(&authFlagValues, "auth", "Authentication rules. Can be: password, username:password, or username:password:permission:pattern. Can be specified multiple times or comma-separated.")
flag.Parse()
// Initialize custom MIME types map
customMIMETypes = make(map[string]string)
customMIMEViewable = make(map[string]bool)
// Process the -i flag
if *intelligentMIMEFlag != "" {
intelligentMIME = true
if *intelligentMIMEFlag != "true" {
// Parse custom MIME type mappings
parseCustomMIMETypes(*intelligentMIMEFlag)
}
}
// Set address
addr = fmt.Sprintf("%s:%s", *hostFlag, strings.TrimPrefix(*portFlag, ":"))
// Set working directory
var err error
if *dirFlag != "" {
workingDir, err = filepath.Abs(*dirFlag)
if err != nil {
log.Fatal("Failed to resolve directory path:", err)
}
// Check if directory exists
if info, err := os.Stat(workingDir); err != nil {
log.Fatal("Directory does not exist:", err)
} else if !info.IsDir() {
log.Fatal("Path is not a directory:", workingDir)
}
} else {
workingDir, err = os.Getwd()
if err != nil {
log.Fatal("Failed to get working directory:", err)
}
}
// Parse authentication rules
if len(authFlagValues) > 0 {
authEnabled = true
if err := parseAuthRules(authFlagValues); err != nil {
log.Fatal("Failed to parse authentication rules:", err)
}
log.Printf("Authentication enabled with %d rule(s)", len(authRules))
}
http.HandleFunc("/", authMiddleware(logRequestMiddleware(browseHandler)))
http.HandleFunc("/download/", authMiddleware(logRequestMiddleware(downloadHandler)))
http.HandleFunc("/upload", authMiddleware(logRequestMiddleware(uploadHandler)))
log.Printf("Server starting on http://%s", addr)
log.Printf("Serving files from: %s", workingDir)
if intelligentMIME {
log.Printf("Intelligent MIME recognition enabled")
}
if err := http.ListenAndServe(addr, nil); err != nil {
log.Fatal("Server failed:", err)
}
}
// logRequestMiddleware wraps a handler to log HTTP requests
func logRequestMiddleware(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
log.Printf("[%s] %s %s", r.Method, r.URL.Path, r.RemoteAddr)
next(w, r)
log.Printf("[%s] %s completed in %v", r.Method, r.URL.Path, time.Since(start))
}
}
// parseAuthRules parses authentication rules from command-line flags
func parseAuthRules(authFlagValues []string) error {
for _, flagValue := range authFlagValues {
// Split by comma to handle multiple rules in one flag
rules := strings.Split(flagValue, ",")
for _, rule := range rules {
rule = strings.TrimSpace(rule)
if rule == "" {
continue
}
parts := strings.Split(rule, ":")
switch len(parts) {
case 1:
// Format: password (any username)
authRules = append(authRules, AuthRule{
Username: "",
Password: parts[0],
Permission: "rw",
Pattern: nil,
})
log.Printf("Added auth rule: password-only (any username)")
case 2:
// Format: username:password
authRules = append(authRules, AuthRule{
Username: parts[0],
Password: parts[1],
Permission: "rw",
Pattern: nil,
})
log.Printf("Added auth rule: %s (full access)", parts[0])
case 4:
// Format: username:password:permission:pattern
perm := strings.ToLower(parts[2])
if perm != "r" && perm != "w" && perm != "rw" {
return fmt.Errorf("invalid permission '%s' in rule '%s' (must be r, w, or rw)", parts[2], rule)
}
// Compile the glob pattern to regex
pattern := parts[3]
regex, err := globToRegex(pattern)
if err != nil {
return fmt.Errorf("invalid pattern '%s' in rule '%s': %v", parts[3], rule, err)
}
authRules = append(authRules, AuthRule{
Username: parts[0],
Password: parts[1],
Permission: perm,
Pattern: regex,
})
log.Printf("Added auth rule: %s (permission: %s, pattern: %s)", parts[0], perm, pattern)
default:
return fmt.Errorf("invalid auth rule format: '%s' (expected password, username:password, or username:password:permission:pattern)", rule)
}
}
}
if len(authRules) == 0 {
return fmt.Errorf("no valid auth rules found")
}
return nil
}
// globToRegex converts a glob pattern to a regular expression
func globToRegex(pattern string) (*regexp.Regexp, error) {
// Escape special regex characters except * and ?
regexPattern := regexp.QuoteMeta(pattern)
// Replace escaped glob wildcards with regex equivalents
regexPattern = strings.ReplaceAll(regexPattern, "\\*", ".*")
regexPattern = strings.ReplaceAll(regexPattern, "\\?", ".")
// Anchor the pattern to match the entire path
regexPattern = "^" + regexPattern + "$"
return regexp.Compile(regexPattern)
}
// authMiddleware handles HTTP Basic Authentication
func authMiddleware(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// If authentication is not enabled, proceed without checks
if !authEnabled {
next(w, r)
return
}
// Extract credentials from Basic Auth
username, password, ok := r.BasicAuth()
if !ok {
requestAuth(w, "Authorization required")
return
}
// Authenticate and get user context
userCtx, authenticated := authenticate(username, password)
if !authenticated {
requestAuth(w, "Invalid credentials")
return
}
// Store user context in request context
ctx := r.Context()
ctx = setUserContext(ctx, userCtx)
r = r.WithContext(ctx)
next(w, r)
}
}
// authenticate validates credentials and returns user context
func authenticate(username, password string) (*UserContext, bool) {
var matchedRules []AuthRule
for _, rule := range authRules {
// Check if username matches (empty username in rule means any username)
usernameMatches := rule.Username == "" || rule.Username == username
// Use constant-time comparison for password
passwordMatches := subtle.ConstantTimeCompare([]byte(rule.Password), []byte(password)) == 1
if usernameMatches && passwordMatches {
matchedRules = append(matchedRules, rule)
}
}
if len(matchedRules) == 0 {
return nil, false
}
return &UserContext{
Username: username,
Rules: matchedRules,
}, true
}
// requestAuth sends a 401 Unauthorized response with WWW-Authenticate header
func requestAuth(w http.ResponseWriter, message string) {
w.Header().Set("WWW-Authenticate", `Basic realm="File Server"`)
http.Error(w, message, http.StatusUnauthorized)
}
// Context key type for user context
type contextKey string
const userContextKey contextKey = "user"
// setUserContext stores user context in the request context
func setUserContext(ctx context.Context, user *UserContext) context.Context {
return context.WithValue(ctx, userContextKey, user)
}
// getUserContext retrieves user context from the request context
func getUserContext(r *http.Request) *UserContext {
if user, ok := r.Context().Value(userContextKey).(*UserContext); ok {
return user
}
return nil
}
// hasReadPermission checks if the user has read permission for a path
func hasReadPermission(user *UserContext, path string) bool {
if user == nil {
return !authEnabled
}
for _, rule := range user.Rules {
// Check if permission includes read
if !strings.Contains(rule.Permission, "r") {
continue
}
// If no pattern is specified, allow access
if rule.Pattern == nil {
return true
}
// Check if path matches the pattern
if rule.Pattern.MatchString(path) {
return true
}
}
return false
}
// hasWritePermission checks if the user has write permission for a path
func hasWritePermission(user *UserContext, path string) bool {
if user == nil {
return !authEnabled
}
for _, rule := range user.Rules {
// Check if permission includes write
if !strings.Contains(rule.Permission, "w") {
continue
}
// If no pattern is specified, allow access
if rule.Pattern == nil {
return true
}
// Check if path matches the pattern
if rule.Pattern.MatchString(path) {
return true
}
}
return false
}
// browseHandler handles file browsing requests
func browseHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
// Get the requested path (relative to workingDir)
requestedPath := strings.TrimPrefix(r.URL.Path, "/")
// Check read permission
user := getUserContext(r)
if !hasReadPermission(user, requestedPath) {
http.Error(w, "Access denied: insufficient permissions for this path", http.StatusForbidden)
return
}
fullPath := filepath.Join(workingDir, requestedPath)
// Security check: ensure the path is within workingDir
cleanPath, err := filepath.Abs(fullPath)
if err != nil {
http.Error(w, "Invalid path", http.StatusBadRequest)
return
}
cleanWorkingDir, _ := filepath.Abs(workingDir)
if !strings.HasPrefix(cleanPath, cleanWorkingDir) {
http.Error(w, "Access denied", http.StatusForbidden)
return
}
// Check if path exists
info, err := os.Stat(fullPath)
if err != nil {
if os.IsNotExist(err) {
http.Error(w, "Path not found", http.StatusNotFound)
return
}
http.Error(w, "Error accessing path", http.StatusInternalServerError)
return
}
// If it's a file, redirect to download
if !info.IsDir() {
http.Redirect(w, r, "/download/"+requestedPath, http.StatusFound)
return
}
// List directory contents
entries, err := os.ReadDir(fullPath)
if err != nil {
http.Error(w, "Error reading directory", http.StatusInternalServerError)
return
}
var files []FileInfo
for _, entry := range entries {
entryInfo, err := entry.Info()
if err != nil {
continue
}
files = append(files, FileInfo{
Name: entry.Name(),
Path: filepath.Join(requestedPath, entry.Name()),
Size: entryInfo.Size(),
ModTime: entryInfo.ModTime(),
IsDir: entry.IsDir(),
})
}
// Calculate parent path
parentPath := ""
if requestedPath != "" {
parentPath = filepath.Dir(requestedPath)
if parentPath == "." {
parentPath = ""
}
}
data := PageData{
CurrentPath: requestedPath,
ParentPath: parentPath,
Files: files,
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if err := templates.ExecuteTemplate(w, "browse.html", data); err != nil {
log.Printf("Template error: %v", err)
http.Error(w, "Error rendering page", http.StatusInternalServerError)
}
}
// downloadHandler handles file downloads with resume support (Range requests)
func downloadHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet && r.Method != http.MethodHead {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
// Get the requested file path
requestedPath := strings.TrimPrefix(r.URL.Path, "/download/")
// Check read permission
user := getUserContext(r)
if !hasReadPermission(user, requestedPath) {
http.Error(w, "Access denied: insufficient permissions for this path", http.StatusForbidden)
return
}
fullPath := filepath.Join(workingDir, requestedPath)
// Security check: ensure the path is within workingDir
cleanPath, err := filepath.Abs(fullPath)
if err != nil {
http.Error(w, "Invalid path", http.StatusBadRequest)
return
}
cleanWorkingDir, _ := filepath.Abs(workingDir)
if !strings.HasPrefix(cleanPath, cleanWorkingDir) {
http.Error(w, "Access denied", http.StatusForbidden)
return
}
// Open the file
file, err := os.Open(fullPath)
if err != nil {
if os.IsNotExist(err) {
http.Error(w, "File not found", http.StatusNotFound)
return
}
http.Error(w, "Error opening file", http.StatusInternalServerError)
return
}
defer file.Close()
// Get file info
fileInfo, err := file.Stat()
if err != nil {
http.Error(w, "Error getting file info", http.StatusInternalServerError)
return
}
// Don't allow downloading directories
if fileInfo.IsDir() {
http.Error(w, "Cannot download directory", http.StatusBadRequest)
return
}
fileSize := fileInfo.Size()
fileName := filepath.Base(fullPath)
// Determine content type and disposition
contentType := "application/octet-stream"
disposition := "attachment"
if intelligentMIME {
if mimeType, isViewable := getMIMEType(fullPath); isViewable {
contentType = mimeType
disposition = "inline"
}
}
// Set headers for file download
w.Header().Set("Content-Disposition", fmt.Sprintf(`%s; filename="%s"`, disposition, fileName))
w.Header().Set("Accept-Ranges", "bytes")
w.Header().Set("Content-Type", contentType)
// Handle range requests for resume support
rangeHeader := r.Header.Get("Range")
if rangeHeader == "" {
// No range requested, send entire file
w.Header().Set("Content-Length", strconv.FormatInt(fileSize, 10))
w.WriteHeader(http.StatusOK)
if r.Method != http.MethodHead {
io.Copy(w, file)
}
return
}
// Parse range header
ranges, err := parseRange(rangeHeader, fileSize)
if err != nil || len(ranges) != 1 {
w.Header().Set("Content-Range", fmt.Sprintf("bytes */%d", fileSize))
http.Error(w, "Invalid range", http.StatusRequestedRangeNotSatisfiable)
return
}
start := ranges[0].start
end := ranges[0].end
contentLength := end - start + 1
// Seek to start position
if _, err := file.Seek(start, 0); err != nil {
http.Error(w, "Error seeking file", http.StatusInternalServerError)
return
}
// Set headers for partial content
w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", start, end, fileSize))
w.Header().Set("Content-Length", strconv.FormatInt(contentLength, 10))
w.WriteHeader(http.StatusPartialContent)
// Send the requested range
if r.Method != http.MethodHead {
io.CopyN(w, file, contentLength)
}
}
// uploadHandler handles file uploads
func uploadHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
// Show upload form
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if err := templates.ExecuteTemplate(w, "upload.html", nil); err != nil {
log.Printf("Template error: %v", err)
http.Error(w, "Error rendering page", http.StatusInternalServerError)
}
return
}
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
// Get user context for permission checks
user := getUserContext(r)
// Parse multipart form (max 100MB in memory)
if err := r.ParseMultipartForm(100 << 20); err != nil {
http.Error(w, "Error parsing form: "+err.Error(), http.StatusBadRequest)
return
}
// Get the uploaded file
file, header, err := r.FormFile("file")
if err != nil {
http.Error(w, "Error retrieving file: "+err.Error(), http.StatusBadRequest)
return
}
defer file.Close()
// Get optional subdirectory
subDir := r.FormValue("directory")
targetDir := workingDir
uploadPath := ""
if subDir != "" {
// Clean and validate subdirectory path
subDir = filepath.Clean(subDir)
targetDir = filepath.Join(workingDir, subDir)
uploadPath = subDir
// Security check
cleanTargetDir, err := filepath.Abs(targetDir)
if err != nil {
http.Error(w, "Invalid directory path", http.StatusBadRequest)
return
}
cleanWorkingDir, _ := filepath.Abs(workingDir)
if !strings.HasPrefix(cleanTargetDir, cleanWorkingDir) {
http.Error(w, "Access denied", http.StatusForbidden)
return
}
// Create directory if it doesn't exist
if err := os.MkdirAll(targetDir, 0755); err != nil {
http.Error(w, "Error creating directory: "+err.Error(), http.StatusInternalServerError)
return
}
}
// Create destination file path
fileName := filepath.Base(header.Filename)
dstPath := filepath.Join(targetDir, fileName)
// Build the relative path for permission checking
filePath := filepath.Join(uploadPath, fileName)
// Check write permission
if !hasWritePermission(user, filePath) {
http.Error(w, "Access denied: insufficient write permissions for this path", http.StatusForbidden)
return
}
dst, err := os.Create(dstPath)
if err != nil {
http.Error(w, "Error creating file: "+err.Error(), http.StatusInternalServerError)
return
}
defer dst.Close()
// Copy file content
if _, err := io.Copy(dst, file); err != nil {
http.Error(w, "Error saving file: "+err.Error(), http.StatusInternalServerError)
return
}
// Redirect back to browse page
redirectPath := "/"
if subDir != "" {
redirectPath = "/" + subDir
}
http.Redirect(w, r, redirectPath+"?upload=success", http.StatusSeeOther)
}
// byteRange represents a byte range request
type byteRange struct {
start int64
end int64
}
// parseCustomMIMETypes parses custom MIME type mappings from a string
// Format: "ext1,ext2:mime/type;ext3:mime/type2,v;ext4:mime/type3"
// Multiple extensions can be mapped to the same MIME type by comma-separating them
// Optional ",v" suffix after MIME type indicates the type is viewable in browser (default: false)
func parseCustomMIMETypes(input string) {
// Split by semicolon to get each mapping group
mappings := strings.Split(input, ";")
for _, mapping := range mappings {
mapping = strings.TrimSpace(mapping)
if mapping == "" {
continue
}
// Split by colon to separate extensions from MIME type (and optional viewability flag)
parts := strings.Split(mapping, ":")
if len(parts) != 2 {
log.Printf("Invalid MIME mapping format: %s (expected 'ext:mime/type' or 'ext:mime/type,v')", mapping)
continue
}
extensions := strings.TrimSpace(parts[0])
mimeInfo := strings.TrimSpace(parts[1])
if extensions == "" || mimeInfo == "" {
log.Printf("Empty extension or MIME type in mapping: %s", mapping)
continue
}
// Check if the mime info has the ,v suffix to indicate viewable
isViewable := false
if strings.HasSuffix(mimeInfo, ",v") {
isViewable = true
mimeInfo = strings.TrimSuffix(mimeInfo, ",v")
mimeInfo = strings.TrimSpace(mimeInfo)
}
if mimeInfo == "" {
log.Printf("Empty MIME type after removing suffix: %s", mapping)
continue
}
// Split by comma to handle multiple extensions with the same MIME type
extList := strings.Split(extensions, ",")
for _, ext := range extList {
ext = strings.TrimSpace(ext)
if ext == "" {
continue
}
// Normalize extension to start with dot
if !strings.HasPrefix(ext, ".") {
ext = "." + ext
}
ext = strings.ToLower(ext)
customMIMETypes[ext] = mimeInfo
customMIMEViewable[ext] = isViewable
viewStr := "not viewable"
if isViewable {
viewStr = "viewable"
}
log.Printf("Registered custom MIME type: %s -> %s (%s)", ext, mimeInfo, viewStr)
}
}
}
// getMIMEType returns the MIME type for a file based on its extension
// Returns (mimeType, isViewable) where isViewable indicates if it's a browser-viewable multimedia type
func getMIMEType(filePath string) (string, bool) {
ext := strings.ToLower(filepath.Ext(filePath))
// Check custom MIME types first
if customMime, exists := customMIMETypes[ext]; exists {
isViewable := customMIMEViewable[ext]
return customMime, isViewable
}
// Image types
imageTypes := map[string]bool{
".jpg": true,
".jpeg": true,
".png": true,
".gif": true,
".bmp": true,
".webp": true,
".svg": true,
".ico": true,
}
// Audio types
audioTypes := map[string]bool{
".mp3": true,
".wav": true,
".flac": true,
".aac": true,
".ogg": true,
".m4a": true,
".weba": true,
}
// Video types
videoTypes := map[string]bool{
".mp4": true,
".webm": true,
".ogv": true,
".mov": true,
".mkv": true,
".avi": true,
".flv": true,
".m3u8": true,
}
// Text/document types that browsers can display
documentTypes := map[string]bool{
".html": true,
".htm": true,
".txt": true,
".pdf": true,
".xml": true,
}
// Check image types
if imageTypes[ext] {
switch ext {
case ".jpg", ".jpeg":
return "image/jpeg", true
case ".png":
return "image/png", true
case ".gif":
return "image/gif", true
case ".bmp":
return "image/bmp", true
case ".webp":
return "image/webp", true
case ".svg":
return "image/svg+xml", true
case ".ico":
return "image/x-icon", true
}
}
// Check audio types
if audioTypes[ext] {
switch ext {
case ".mp3":
return "audio/mpeg", true
case ".wav":
return "audio/wav", true
case ".flac":
return "audio/flac", true
case ".aac":
return "audio/aac", true
case ".ogg":
return "audio/ogg", true
case ".m4a":
return "audio/mp4", true
case ".weba":
return "audio/webp", true
}
}
// Check video types
if videoTypes[ext] {
switch ext {
case ".mp4":
return "video/mp4", true
case ".webm":
return "video/webm", true
case ".ogv":
return "video/ogg", true
case ".mov":
return "video/quicktime", true
case ".mkv":
return "video/x-matroska", true
case ".avi":
return "video/x-msvideo", true
case ".flv":
return "video/x-flv", true
case ".m3u8":
return "application/vnd.apple.mpegurl", true
}
}
// Check document types
if documentTypes[ext] {
switch ext {
case ".html", ".htm":
return "text/html", true
case ".txt":
return "text/plain", true
case ".pdf":
return "application/pdf", true
case ".xml":
return "application/xml", true
}
}
return "application/octet-stream", false
}
// parseRange parses a Range header value
func parseRange(s string, size int64) ([]byteRange, error) {
if !strings.HasPrefix(s, "bytes=") {
return nil, fmt.Errorf("invalid range header")
}
s = strings.TrimPrefix(s, "bytes=")
ranges := []byteRange{}
for _, rangeSpec := range strings.Split(s, ",") {
rangeSpec = strings.TrimSpace(rangeSpec)
parts := strings.Split(rangeSpec, "-")
if len(parts) != 2 {
return nil, fmt.Errorf("invalid range spec")
}
var start, end int64
var err error
if parts[0] == "" {
// Suffix range: -500 means last 500 bytes
end = size - 1
start, err = strconv.ParseInt(parts[1], 10, 64)
if err != nil {
return nil, err
}
start = size - start
if start < 0 {
start = 0
}
} else if parts[1] == "" {
// Start range: 500- means from byte 500 to end
start, err = strconv.ParseInt(parts[0], 10, 64)
if err != nil {
return nil, err
}
end = size - 1
} else {
// Full range: 500-999
start, err = strconv.ParseInt(parts[0], 10, 64)
if err != nil {
return nil, err
}
end, err = strconv.ParseInt(parts[1], 10, 64)
if err != nil {
return nil, err
}
}
if start < 0 || start >= size || end < start || end >= size {
return nil, fmt.Errorf("invalid range")
}
ranges = append(ranges, byteRange{start: start, end: end})
}
return ranges, nil
}