Go File Upload Handler
Handle multipart file uploads in Go with size limits, MIME type validation, unique filename generation, streaming to disk without buffering entire file, and.
Code
package main
import (
"fmt"
"io"
"net/http"
"os"
"time"
)
func uploadHandler(w http.ResponseWriter, r *http.Request) {
r.ParseMultipartForm(10 << 20)
file, header, err := r.FormFile("file")
if err != nil {
http.Error(w, "No file", http.StatusBadRequest)
return
}
defer file.Close()
dst, _ := os.Create(fmt.Sprintf("uploads/%d-%s", time.Now().Unix(), header.Filename))
defer dst.Close()
io.Copy(dst, file)
fmt.Fprintf(w, `{"path":"%s","size":%d}`, dst.Name(), header.Size)
}The structure at work
The function is where the work lands uploadHandler — everything else is wiring.
Nothing falls through silently — 1 checkpoint test err != nil on the way through. The function registers its cleanup up front with defer, so no exit path forgets it.
Putting it to use
The primary signature is func uploadHandler(w http.ResponseWriter, r *http.Request)
Core lines
if err != nil {
http.Error(w, "No file", http.StatusBadRequest)
return
}
dst, _ := os.Create(fmt.Sprintf("uploads/%d-%s", time.Now().Unix(), header.Filename))
defer file.Close()
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Accept Header ParserParse an Accept header into media ranges with their quality values and specificity, sorted by preference for content negotiation debugging.Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.Set-Cookie ParserParse one or more Set-Cookie header values into the cookie name, value, and attributes like Path, Domain, Expires, Max-Age, Secure, HttpOnly, and SameSite.
FAQ
- Which packages does this snippet need?
- None. Every symbol the code uses resolves inside the standard library. The file defines `uploadHandler` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.