package cmd import ( "embed" "fmt" "io" "io/fs" "log" "mime/multipart" "net/http" "os" ) var ( listenPort string = "1302" ) //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") log.Printf("[%v] Received file \"%v\" from %v\n", r.RemoteAddr, header.Filename, r.UserAgent()) 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) } isDone := make(chan bool) 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) if err != nil { log.Printf("Error happened writing file: %v\n", err) } isDone <- true } 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) fmt.Printf("Listening on port %v...\n", listenPort) err = http.ListenAndServe(":"+listenPort, nil) if err != nil { log.Fatal(err) } }