64 lines
1.3 KiB
Go
64 lines
1.3 KiB
Go
package httpRequest
|
|
|
|
import (
|
|
"io"
|
|
"net/http"
|
|
"strings"
|
|
|
|
"go-socket/packages/globals"
|
|
)
|
|
|
|
type postType uint8
|
|
|
|
const (
|
|
postNormal postType = iota
|
|
postFile
|
|
postAvatar
|
|
postProfileBg
|
|
)
|
|
|
|
func postValidCheckWithResponseOnFail(response *http.ResponseWriter, request *http.Request, pt postType) bool {
|
|
if request.Method != http.MethodPost {
|
|
http.Error(*response, "POST only", http.StatusMethodNotAllowed)
|
|
return false
|
|
}
|
|
|
|
var maxSize int64
|
|
switch pt {
|
|
case postFile:
|
|
maxSize = int64(globals.MaxPostWithFileBytes)
|
|
case postAvatar:
|
|
maxSize = int64(globals.MaxPostWithAvatar)
|
|
case postProfileBg:
|
|
maxSize = int64(globals.MaxPostWithProfileBg)
|
|
default:
|
|
maxSize = int64(globals.MaxPostBytes)
|
|
}
|
|
|
|
if request.ContentLength > maxSize {
|
|
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
|
|
}
|