cluade code review changes

This commit is contained in:
2026-02-20 16:38:24 +05:30
parent a048cb0d73
commit f1601020b1
16 changed files with 150 additions and 70 deletions

View File

@@ -15,10 +15,10 @@ import (
"code.patial.tech/go/appcore/validate"
)
// MaxRequestBodySize is the maximum allowed size for request bodies (1MB default).
// MaxRequestBodySize is the maximum allowed size for request bodies (5MB default).
// This prevents resource exhaustion attacks from large payloads.
// Override this value if you need to accept larger requests.
var MaxRequestBodySize int64 = 1 << 20 // 1MB
var MaxRequestBodySize int64 = 5 << 20 // 5MB
func FormField(r *http.Request, key string) (string, error) {
f, err := Payload[map[string]any](r)
@@ -49,22 +49,24 @@ func PayloadWithValidate[T any](r *http.Request) (T, error) {
func Payload[T any](r *http.Request) (T, error) {
var p T
if r.ContentLength > MaxRequestBodySize {
return p, errors.New("request body too large")
}
// Limit request body size to prevent resource exhaustion
limited := io.LimitReader(r.Body, MaxRequestBodySize)
limited := io.LimitReader(r.Body, MaxRequestBodySize+1)
decoder := json.NewDecoder(limited)
if err := decoder.Decode(&p); err != nil {
// Check if we hit the size limit
if err == io.EOF || err == io.ErrUnexpectedEOF {
// Try to read one more byte to see if there's more data
var buf [1]byte
if n, _ := limited.Read(buf[:]); n == 0 {
// We hit the limit
return p, errors.New("request body too large")
}
}
return p, err
}
// Check if there's more data beyond the limit
var buf [1]byte
if n, _ := limited.Read(buf[:]); n > 0 {
return p, errors.New("request body too large")
}
return p, nil
}
@@ -72,21 +74,23 @@ func Payload[T any](r *http.Request) (T, error) {
// This is useful when you want to decode into an existing variable.
// The request body size is limited by MaxRequestBodySize to prevent DoS attacks.
func DecodeJSON(r *http.Request, v any) error {
if r.ContentLength > MaxRequestBodySize {
return errors.New("request body too large")
}
// Limit request body size to prevent resource exhaustion
limited := io.LimitReader(r.Body, MaxRequestBodySize)
limited := io.LimitReader(r.Body, MaxRequestBodySize+1)
decoder := json.NewDecoder(limited)
if err := decoder.Decode(v); err != nil {
// Check if we hit the size limit
if err == io.EOF || err == io.ErrUnexpectedEOF {
// Try to read one more byte to see if there's more data
var buf [1]byte
if n, _ := limited.Read(buf[:]); n == 0 {
// We hit the limit
return errors.New("request body too large")
}
}
return err
}
// Check if there's more data beyond the limit
var buf [1]byte
if n, _ := limited.Read(buf[:]); n > 0 {
return errors.New("request body too large")
}
return nil
}