package main
import (
"fmt"
"io"
"net/http"
"os"
)
const (
KB int64 = 1024
MB = KB * 1024
GB = MB * 1024
)
func main() {
http.HandleFunc("/upload", func(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
maxFileSize := 200 * MB
if r.ContentLength > maxFileSize {
http.Error(w, "The uploaded file is too large. Please upload a file smaller than 200MB.", http.StatusBadRequest)
return
}
err := r.ParseMultipartForm(10 * MB)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
file, handler, err := r.FormFile("file")
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
defer file.Close()
fmt.Printf("Uploaded File: %+v\n", handler.Filename)
fmt.Printf("File Size: %+v\n", handler.Size)
fmt.Printf("MIME Header: %+v\n", handler.Header)
outFile, err := os.Create(handler.Filename)
if err != nil {
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
defer outFile.Close()
_, err = io.Copy(outFile, file)
if err != nil {
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte("File uploaded successfully"))
})
http.ListenAndServe(":8080", nil)
}