Skip to content

Instantly share code, notes, and snippets.

@nenodias
Created April 3, 2025 03:12
Show Gist options
  • Save nenodias/155bbe81a6dfb4824b361a368ea25e9f to your computer and use it in GitHub Desktop.
Save nenodias/155bbe81a6dfb4824b361a368ea25e9f to your computer and use it in GitHub Desktop.

Revisions

  1. nenodias created this gist Apr 3, 2025.
    93 changes: 93 additions & 0 deletions main.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,93 @@
    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)
    }