I want to allow uploading files. Go is being used server-side to handle requests. I would like to send a response "File too large" whenever the file they're trying to upload is too large. I would like to do so, before the entire file is uploaded (bandwidth).
I am using the following snippet, but it's only sending a response after the client is done uploading. It saves a 5 kB file.
const MaxFileSize = 5 * 1024
// This feels like a bad hack...
if r.ContentLength > MaxFileSize {
if flusher, ok := w.(http.Flusher); ok {
response := []byte("Request too large")
w.Header().Set("Connection", "close")
w.Header().Set("Content-Length", fmt.Sprintf("%d", len(response)))
w.WriteHeader(http.StatusExpectationFailed)
w.Write(response)
flusher.Flush()
}
conn, _, _ := w.(http.Hijacker).Hijack()
conn.Close()
return
}
r.Body = http.MaxBytesReader(w, r.Body, MaxFileSize)
err := r.ParseMultipartForm(1024)
if err != nil {
w.Write([]byte("File too large"));
return
}
file, header, err := r.FormFile("file")
if err != nil {
panic(err)
}
dst, err := os.Create("upload/" + header.Filename)
defer dst.Close()
if err != nil {
panic(err)
}
written, err := io.Copy(dst, io.LimitReader(file, MaxFileSize))
if err != nil {
panic(err)
}
if written == MaxFileSize {
w.Write([]byte("File too large"))
return
}
w.Write([]byte("Success..."))