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.

GoFile Upload

Code

snippet
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

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.