Files
go-socket/packages/httpRequest/helper.go
T
2026-04-28 16:38:16 +02:00

60 lines
1.2 KiB
Go

package httpRequest
import (
"io"
"net/http"
"strings"
"go-socket/packages/config"
)
type postType uint8
const (
normal postType = iota
file
avatar
profileBg
)
func validCheckWithResponseOnFail(response *http.ResponseWriter, request *http.Request, pt postType) bool {
var maxSize int64
switch pt {
case file:
maxSize = int64(config.MaxRequestWithFileBytes)
case avatar:
maxSize = int64(config.MaxRequestWithAvatarBytes)
case profileBg:
maxSize = int64(config.MaxRequestWithProfileBgBytes)
default:
maxSize = int64(config.MaxRequestBytes)
}
if request.ContentLength > maxSize {
io.Copy(io.Discard, request.Body)
http.Error(*response, "Request too large", http.StatusRequestEntityTooLarge)
return false
}
return true
}
func isImage(r io.Reader) (bool, string, error) {
buf := make([]byte, 512)
n, err := io.ReadFull(r, buf)
if err != nil && err != io.EOF && err != io.ErrUnexpectedEOF {
return false, "", err
}
contentType := http.DetectContentType(buf[:n])
isImage := strings.HasPrefix(contentType, "image/") && contentType != "image/svg+xml"
if seeker, ok := r.(io.Seeker); ok {
if _, err := seeker.Seek(0, io.SeekStart); err != nil {
return isImage, contentType, err
}
}
return isImage, contentType, nil
}