Documentation
¶
Index ¶
- Variables
- func BuildAllowedMimeMap(imageMimes, videoMimes []string) map[string]bool
- func CalculateMaxRequestSize(maxAttachmentSize int64, bufferSize int64) int64
- func DetectMimeType(fileHeader *multipart.FileHeader) (string, error)
- func ExtractImageDimensions(file multipart.File, mimeType string) (*int, *int)
- func FormatSizeMB(bytes int64) float64
- func ValidateAndParseMultipart(r *http.Request, w http.ResponseWriter, maxSize int64) error
- func ValidateAttachments(fileHeaders []*multipart.FileHeader, ...) ([]*domain.PendingFile, error)
Constants ¶
This section is empty.
Variables ¶
var ErrInvalidMimeType = errors.New("invalid MIME type")
ErrInvalidMimeType is returned when an uploaded file has a disallowed MIME type
var ErrPayloadTooLarge = errors.New("payload too large")
ErrPayloadTooLarge is returned when the request body exceeds size limits
var ErrTooManyAttachments = errors.New("too many attachments")
ErrTooManyAttachments is returned when too many files are uploaded
Functions ¶
func BuildAllowedMimeMap ¶
func CalculateMaxRequestSize ¶
CalculateMaxRequestSize returns the maximum request size including overhead buffer. It adds a buffer (typically 1 MiB) for form fields and multipart overhead.
func DetectMimeType ¶
func DetectMimeType(fileHeader *multipart.FileHeader) (string, error)
func ExtractImageDimensions ¶
func FormatSizeMB ¶
FormatSizeMB converts bytes to megabytes for user-friendly error messages.
func ValidateAndParseMultipart ¶
ValidateAndParseMultipart validates request size and parses the multipart form. It sets up MaxBytesReader to enforce the size limit and attempts to parse the form. Returns an error if the size limit is exceeded or parsing fails.
Connection Reset Behavior (By Design): When MaxBytesReader's limit is exceeded, the server stops reading and closes the connection, which triggers ERR_CONNECTION_RESET in browsers. This is EXPECTED and ACCEPTABLE because:
- MaxBytesReader only reads UP TO the limit (e.g., 21MB), then stops - preventing resource exhaustion even if a user tries to upload 200TB.
- Client-side JavaScript validation catches 99.9% of legitimate users before upload starts.
- Connection reset only affects: - Malicious users trying to bypass client-side checks (acceptable) - Users with JavaScript disabled (rare, acceptable trade-off) - API clients that don't check Content-Length (they handle resets gracefully)
This multi-layer defense (JS validation → MaxBytesReader) is the industry standard approach. For browser form submissions, we cannot reject early by checking Content-Length because the browser has already started uploading when we receive the request.
func ValidateAttachments ¶
func ValidateAttachments(fileHeaders []*multipart.FileHeader, allowedImageMimes, allowedVideoMimes []string) ([]*domain.PendingFile, error)
Types ¶
This section is empty.