package main import ( "fmt" "net/http" "os" "path/filepath" ) func main() { // Directory to save uploaded files uploadDir := "./uploads" err := os.MkdirAll(uploadDir, os.ModePerm) if err != nil { fmt.Printf("Error creating upload directory: %v\n", err) return } http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { // Serve the file upload form if r.Method == http.MethodGet { w.Header().Set("Content-Type", "text/html") fmt.Fprint(w, `

Upload File

`) } else if r.Method == http.MethodPost { // Handle file upload file, header, err := r.FormFile("file") if err != nil { http.Error(w, fmt.Sprintf("Error reading file: %v", err), http.StatusInternalServerError) return } defer file.Close() outPath := filepath.Join(uploadDir, header.Filename) outFile, err := os.Create(outPath) if err != nil { http.Error(w, fmt.Sprintf("Error saving file: %v", err), http.StatusInternalServerError) return } defer outFile.Close() _, err = outFile.ReadFrom(file) if err != nil { http.Error(w, fmt.Sprintf("Error writing file: %v", err), http.StatusInternalServerError) return } fmt.Fprintf(w, "File uploaded successfully: %s", header.Filename) fmt.Printf("File saved to: %s\n", outPath) } }) // Start the server port := "8080" fmt.Printf("Server started at http://localhost:%s\n", port) err = http.ListenAndServe("0.0.0.0:"+port, nil) if err != nil { fmt.Printf("Error starting server: %v\n", err) } }