Skip to content

Instantly share code, notes, and snippets.

@dakyskye
Created January 2, 2025 00:18
Show Gist options
  • Select an option

  • Save dakyskye/374ed2ff3091a973cbcfdf6a7b04a8a2 to your computer and use it in GitHub Desktop.

Select an option

Save dakyskye/374ed2ff3091a973cbcfdf6a7b04a8a2 to your computer and use it in GitHub Desktop.

Revisions

  1. dakyskye created this gist Jan 2, 2025.
    70 changes: 70 additions & 0 deletions main.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,70 @@
    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, `
    <!DOCTYPE html>
    <html>
    <body>
    <h2>Upload File</h2>
    <form enctype="multipart/form-data" method="post">
    <input type="file" name="file" required>
    <button type="submit">Upload</button>
    </form>
    </body>
    </html>
    `)
    } 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)
    }
    }