2024-05-03 08:23:58 +02:00
|
|
|
package cmd
|
|
|
|
|
|
|
|
import (
|
|
|
|
"embed"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"io/fs"
|
|
|
|
"log"
|
2024-05-21 08:52:26 +02:00
|
|
|
"mime/multipart"
|
2024-05-03 08:23:58 +02:00
|
|
|
"net/http"
|
|
|
|
"os"
|
|
|
|
)
|
|
|
|
|
2024-05-03 08:31:04 +02:00
|
|
|
var (
|
|
|
|
listenPort string = "1302"
|
|
|
|
)
|
|
|
|
|
2024-05-03 08:23:58 +02:00
|
|
|
//go:embed assets
|
|
|
|
var assetsFolder embed.FS
|
|
|
|
|
|
|
|
func uploadFile(w http.ResponseWriter, r *http.Request) {
|
|
|
|
fmt.Fprintln(w, "Successful upload!")
|
|
|
|
|
|
|
|
file, header, err := r.FormFile("file")
|
2024-05-03 08:31:04 +02:00
|
|
|
log.Printf("[%v] Received file \"%v\" from %v\n", r.RemoteAddr, header.Filename, r.UserAgent())
|
2024-05-03 08:23:58 +02:00
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
log.Printf("Error happened receiving file: %v\n", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
defer file.Close()
|
|
|
|
|
|
|
|
_, err = os.Stat("./temp/")
|
|
|
|
if os.IsNotExist(err) {
|
|
|
|
os.Mkdir("./temp/", 0700)
|
|
|
|
}
|
|
|
|
|
|
|
|
f, err := os.OpenFile("./temp/"+header.Filename, os.O_WRONLY|os.O_CREATE, 0660)
|
|
|
|
if err != nil {
|
|
|
|
log.Printf("Error happened opening file: %v\n", err)
|
|
|
|
}
|
2024-05-21 08:52:26 +02:00
|
|
|
isDone := make(chan bool)
|
2024-05-03 08:23:58 +02:00
|
|
|
|
2024-05-21 08:52:26 +02:00
|
|
|
go copyTo(isDone, f, file)
|
|
|
|
|
|
|
|
<-isDone
|
|
|
|
log.Printf("Successfully copied file!\n")
|
|
|
|
}
|
|
|
|
|
|
|
|
func copyTo(isDone chan bool, f *os.File, file multipart.File) {
|
|
|
|
_, err := io.Copy(f, file)
|
2024-05-03 09:18:23 +02:00
|
|
|
if err != nil {
|
|
|
|
log.Printf("Error happened writing file: %v\n", err)
|
|
|
|
}
|
2024-05-21 08:52:26 +02:00
|
|
|
isDone <- true
|
2024-05-03 08:23:58 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func server() {
|
|
|
|
serverRoot, err := fs.Sub(assetsFolder, "assets")
|
|
|
|
if err != nil {
|
|
|
|
log.Fatalf("Error occurred setting HTML root: %v\n", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
http.Handle("/", http.FileServer(http.FS(serverRoot)))
|
|
|
|
http.HandleFunc("/api/upload", uploadFile)
|
|
|
|
|
2024-05-03 08:31:04 +02:00
|
|
|
fmt.Printf("Listening on port %v...\n", listenPort)
|
2024-05-03 08:23:58 +02:00
|
|
|
|
2024-05-03 08:31:04 +02:00
|
|
|
err = http.ListenAndServe(":"+listenPort, nil)
|
2024-05-03 08:23:58 +02:00
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
|
|
|
}
|