Перенесите реализацию ЛР 4 на стенд ЛР 5
This commit is contained in:
@@ -0,0 +1,56 @@
|
||||
package attachment
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"image"
|
||||
_ "image/jpeg"
|
||||
_ "image/png"
|
||||
"io"
|
||||
"strings"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"messenger/internal/platform/apperr"
|
||||
)
|
||||
|
||||
const MaxUploadBytes int64 = 10 * 1024 * 1024
|
||||
const MaxImagePixels int64 = 40_000_000
|
||||
|
||||
var imageFormats = map[string]string{
|
||||
"image/png": "png",
|
||||
"image/jpeg": "jpeg",
|
||||
}
|
||||
|
||||
func ValidateFilename(name string) error {
|
||||
if !utf8.ValidString(name) || strings.TrimSpace(name) == "" || utf8.RuneCountInString(name) > 255 {
|
||||
return apperr.Invalid("filename must contain 1-255 characters")
|
||||
}
|
||||
for _, r := range name {
|
||||
if r == '/' || r == '\\' || unicode.IsControl(r) {
|
||||
return apperr.Invalid("filename contains a forbidden character")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// The small header is replayed into the decoder; pixels are allocated only
|
||||
// after checking dimensions. The caller serializes decoding per replica.
|
||||
func ValidateImage(r io.Reader, mime string, maxPixels int64) error {
|
||||
limited := io.LimitReader(r, MaxUploadBytes+1)
|
||||
var header bytes.Buffer
|
||||
cfg, format, err := image.DecodeConfig(io.TeeReader(limited, &header))
|
||||
if err != nil {
|
||||
return apperr.Wrap(apperr.KindUnsupportedMedia, "invalid image", err)
|
||||
}
|
||||
if expectedFormat, accepted := imageFormats[mime]; !accepted || format != expectedFormat {
|
||||
return apperr.UnsupportedMedia("image does not match Content-Type")
|
||||
}
|
||||
if cfg.Width <= 0 || cfg.Height <= 0 || int64(cfg.Width) > maxPixels/int64(cfg.Height) {
|
||||
return apperr.PayloadTooLarge("image exceeds pixel limit")
|
||||
}
|
||||
_, _, err = image.Decode(io.MultiReader(bytes.NewReader(header.Bytes()), limited))
|
||||
if err != nil {
|
||||
return apperr.Wrap(apperr.KindUnsupportedMedia, "invalid image", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user