Created
April 3, 2025 03:12
-
-
Save nenodias/155bbe81a6dfb4824b361a368ea25e9f to your computer and use it in GitHub Desktop.
Go-uploader
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, `<!DOCTYPE html> | |
<html> | |
<head> | |
<title>File Upload</title> | |
</head> | |
<body> | |
<form action="/upload" method="POST" enctype="multipart/form-data"> | |
<input type="file" name="myFile"> | |
<input type="submit" value="Upload"> | |
</form> | |
</body> | |
</html>`) | |
} | |
func listDownload(w http.ResponseWriter, r *http.Request) { | |
fmt.Fprintf(w, `<!DOCTYPE html> | |
<html> | |
<head> | |
<title>File Upload</title> | |
</head> | |
<body>`) | |
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, "<a href=\"/download/%s\">%s</a><br>", file.Name(), file.Name()) | |
} | |
} | |
fmt.Fprintf(w, `</body></html>`) | |
} | |
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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment