package main import ( "fmt" "io" "net/http" "os" "github.com/gorilla/mux" ) const maxUploadSize = 10 << 20 // 10 MB func uploadFile(w http.ResponseWriter, r *http.Request) { if err := r.ParseMultipartForm(maxUploadSize); err != nil { http.Error(w, "Unable to parse form", http.StatusInternalServerError) return } file, handler, err := r.FormFile("myFile") if err != nil { http.Error(w, "Unable to retrieve file", http.StatusInternalServerError) return } defer file.Close() if err := saveFile(file, handler.Filename); err != nil { http.Error(w, "Unable to save file", http.StatusInternalServerError) return } fmt.Fprintf(w, "Successfully uploaded file %s!\n", handler.Filename) } func saveFile(file io.Reader, filename string) error { tempFile, err := os.Create(fmt.Sprintf("/tmp/%s", filename)) if err != nil { return fmt.Errorf("error creating file: %w", err) } defer tempFile.Close() if _, err := io.Copy(tempFile, file); err != nil { return fmt.Errorf("error saving file: %w", err) } return nil } func uploadForm(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, ` File Upload
`) } func listDownload(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, ` File Upload `) files, err := os.ReadDir("./") if err != nil { http.Error(w, "Unable to list files", http.StatusInternalServerError) return } for _, file := range files { if !file.IsDir() { fmt.Fprintf(w, "%s
", file.Name(), file.Name()) } } fmt.Fprintf(w, ``) } func main() { r := mux.NewRouter() r.HandleFunc("/upload", uploadFile).Methods("POST") r.HandleFunc("/", uploadForm).Methods("GET") r.HandleFunc("/list", listDownload).Methods("GET") r.PathPrefix("/download/").Handler(http.StripPrefix("/download/", http.FileServer(http.Dir("./")))) http.ListenAndServe(":8080", r) }