-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
228 lines (194 loc) · 5.96 KB
/
main.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
package main
import (
"fmt"
"io"
"mime/multipart"
"net/http"
"os"
"path/filepath"
"strings"
"sync"
"time"
"net"
)
func main() {
// home, err := os.UserHomeDir()
// uploadPath := filepath.Join(home, "/.upload")
home, _ := os.UserHomeDir()
uploadPath := filepath.Join(home, "uploads")
err := os.MkdirAll(uploadPath, os.ModePerm)
if err != nil {
fmt.Println("Error creating upload directory:", err)
return
}
// fmt.Println("Home directory:", uploadPath)
// Serving static files
fs := http.FileServer(http.Dir("./static"))
http.Handle("/", fs)
// Handle file uploads
http.HandleFunc("/upload", func(w http.ResponseWriter, r *http.Request) {
fileUploadHandler(w, r, uploadPath)
})
fmt.Println("Server started on :8989")
ip, err := GetPrivateIP()
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("Possible urls:", ip)
err = http.ListenAndServe(":8989", nil)
if err != nil {
fmt.Printf("Error starting server: %s\n", err)
return
}
}
func fileUploadHandler(w http.ResponseWriter, r *http.Request, uploadPath string) {
if r.Method != "POST" {
http.Error(w, "Only POST method is accepted", http.StatusMethodNotAllowed)
return
}
// Ensure the ParseMultipartForm method is called before retrieving files
if err := r.ParseMultipartForm(10 << 20); err != nil { // 10 MB
http.Error(w, "Failed to parse multipart form: "+err.Error(), http.StatusInternalServerError)
return
}
// Retrieve files from the posted form-data
files := r.MultipartForm.File["files"]
if files == nil {
http.Error(w, "No files received", http.StatusBadRequest)
return
}
var wg sync.WaitGroup
wg.Add(len(files))
var successfulUploads []string
// Below loop ensures multi-file upload
for _, fileHeader := range files {
go func(fileHeader *multipart.FileHeader) {
defer wg.Done()
file, err := fileHeader.Open()
now := time.Now()
format := "2006-01-02 15:04:05"
// Format the timestamp and print it
if err != nil {
fmt.Println("Error retrieving the file", err)
// continue
}
defer file.Close()
newPath := filepath.Join(uploadPath, filepath.Base(fileHeader.Filename))
newFile, err := os.Create(newPath)
if err != nil {
fmt.Println("Error creating the file", err)
return
}
defer newFile.Close()
fileName := fileHeader.Header.Get("Content-Disposition")
// Extract file name from Content-Disposition header (optional parsing)
var actualFileName string
if fileName != "" {
// Basic parsing (can be improved for robustness)
parts := strings.Split(fileName, `;`)
for _, part := range parts {
if strings.Contains(part, "filename=") {
actualFileName = strings.TrimSpace(strings.SplitN(part, "=", 2)[1])
break
}
}
}
timestamp := now.Format(format)
fmt.Printf("%s: File being uploaded: %s\n\n", timestamp, actualFileName)
bytesWritten, err := io.Copy(newFile, file)
fmt.Fprintf(w, "File size is %d\n", bytesWritten)
if err != nil {
http.Error(w, "Error saving the file", http.StatusInternalServerError)
fmt.Println(err)
return
}
successfulUploads = append(successfulUploads, fileHeader.Filename)
logUploadDetails(uploadPath, filepath.Base(fileHeader.Filename), bytesWritten)
fmt.Fprintf(w, "File uploaded successfully: %+v", fileHeader.Filename)
}(fileHeader)
}
wg.Wait()
// Report back to client
if len(successfulUploads) > 0 {
fmt.Fprintf(w, "Successfully uploaded files: %v", successfulUploads)
} else {
http.Error(w, "Failed to upload any files", http.StatusInternalServerError)
}
/*
Below lines of code for single file upload
*/
// file, header, err = r.FormFile("file")
// if err != nil {
// http.Error(w, "Error retrieving the file", http.StatusInternalServerError)
// fmt.Println(err)
// return
// }
// defer file.Close()
// newPath := filepath.Join("/Users/harishkumarpillai/.uploads", filepath.Base(header.Filename))
// fmt.Printf("Uploaded File: %+v\n", header.Filename)
// fmt.Printf("File Size: %+v\n", header.Size)
// fmt.Printf("MIME Header: %+v\n", header.Header)
// newFile, err := os.Create(newPath)
// if err != nil {
// http.Error(w, "Error creating the file", http.StatusInternalServerError)
// fmt.Println(err)
// return
// }
// defer newFile.Close()
// bytesWritten, err := io.Copy(newFile, file)
// if err != nil {
// http.Error(w, "Error saving the file", http.StatusInternalServerError)
// fmt.Println(err)
// return
// }
// logUploadDetails(header.Filename, bytesWritten)
// fmt.Fprintf(w, "File uploaded successfully: %+v", header.Filename)
}
func logUploadDetails(filePath string, newPath string, fileSize int64) {
logFile, err := os.OpenFile(filepath.Join(filePath, "upload_logs.txt"), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
fmt.Println("Error opening log file:", err)
return
}
defer logFile.Close()
now := time.Now()
logEntry := fmt.Sprintf("Upload: %s, Size: %d bytes, Date: %s\n", newPath, fileSize, now.Format("2006-01-02 15:04:05"))
if _, err = logFile.WriteString(logEntry); err != nil {
fmt.Println("Error writing to log file:", err)
}
}
func GetPrivateIP() (string, error) {
interfaces, err := net.Interfaces()
if err != nil {
return "", err
}
var ipv4s string
for _, iface := range interfaces {
// Skip down interfaces, loopback interfaces, and point-to-point interfaces
if iface.Flags&net.FlagUp == 0 || iface.Flags&net.FlagLoopback != 0 || iface.Flags&net.FlagPointToPoint != 0 {
continue
}
addrs, err := iface.Addrs()
if err != nil {
return "", err
}
for _, addr := range addrs {
var ip net.IP
switch v := addr.(type) {
case *net.IPNet:
ip = v.IP
case *net.IPAddr:
ip = v.IP
}
// Check if the IP address is a private IP address
if ip.IsLoopback() || !ip.IsGlobalUnicast() {
continue
}
if ipv4 := ip.To4(); ipv4 != nil {
ipv4s = "http://" + ipv4.String() + ":8989 , " + ipv4s
}
}
}
return ipv4s,err//"", fmt.Errorf("no private IP address found")
}