-
Notifications
You must be signed in to change notification settings - Fork 0
/
fileserver.go
98 lines (80 loc) · 2.37 KB
/
fileserver.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
package fileserver
import (
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strings"
)
// UploadHandler handles file uploads
func UploadHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
return
}
file, handler, err := r.FormFile("file")
if err != nil {
http.Error(w, "Failed to get file", http.StatusBadRequest)
return
}
defer file.Close()
savePath := filepath.Join("uploads", handler.Filename)
out, err := os.Create(savePath)
if err != nil {
http.Error(w, "Failed to save file", http.StatusInternalServerError)
return
}
defer out.Close()
_, err = io.Copy(out, file)
if err != nil {
http.Error(w, "Failed to save file", http.StatusInternalServerError)
return
}
fmt.Fprintf(w, "File uploaded successfully: %s\n", handler.Filename)
}
// DownloadHandler handles file downloads
func DownloadHandler(w http.ResponseWriter, r *http.Request) {
fileName := strings.TrimPrefix(r.URL.Path, "/download/")
filePath := filepath.Join("uploads", fileName)
if _, err := os.Stat(filePath); os.IsNotExist(err) {
http.Error(w, "File not found", http.StatusNotFound)
return
}
http.ServeFile(w, r, filePath)
}
// ListHandler lists all files in the upload directory
func ListHandler(w http.ResponseWriter, r *http.Request) {
files, err := os.ReadDir("uploads")
if err != nil {
http.Error(w, "Failed to list files", http.StatusInternalServerError)
return
}
for _, file := range files {
fmt.Fprintln(w, file.Name())
}
}
// DeleteHandler deletes a specified file
func DeleteHandler(w http.ResponseWriter, r *http.Request) {
fileName := strings.TrimPrefix(r.URL.Path, "/delete/")
filePath := filepath.Join("uploads", fileName)
if err := os.Remove(filePath); err != nil {
if os.IsNotExist(err) {
http.Error(w, "File not found", http.StatusNotFound)
} else {
http.Error(w, "Failed to delete file", http.StatusInternalServerError)
}
return
}
fmt.Fprintf(w, "File deleted successfully: %s\n", fileName)
}
func StartServer(addr string) {
// Ensure the uploads directory exists
os.MkdirAll("uploads", os.ModePerm)
http.HandleFunc("/upload", UploadHandler)
http.HandleFunc("/download/", DownloadHandler)
http.HandleFunc("/list", ListHandler)
http.HandleFunc("/delete/", DeleteHandler)
fmt.Println("Starting server on :8080")
http.ListenAndServe(":8080", nil)
}