Files
tokens-reef/backend/internal/service/upstream_response_limit.go
Developer da36506b89 fix: resolve P0/P1 code quality issues
P0 fixes:
- ModelError.Is(): use exact matching instead of substring contains()
- shouldClearStickySession: add context param for cancellation/tracing

P1 fixes:
- TODO stubs: return 501 Not Implemented errors
- validateInstanceSignature: deduplicate to shared validateCodeSignature()
- Error messages: standardize to English only
- http.go: remove pseudo if-else with duplicate branches
2026-03-31 11:39:18 +08:00

39 lines
958 B
Go

package service
import (
"errors"
"fmt"
"io"
"github.com/Wei-Shaw/sub2api/internal/config"
)
var ErrUpstreamResponseBodyTooLarge = errors.New("upstream response body too large")
const defaultUpstreamResponseReadMaxBytes int64 = 8 * 1024 * 1024
func resolveUpstreamResponseReadLimit(cfg *config.Config) int64 {
if cfg != nil && cfg.Gateway.UpstreamResponseReadMaxBytes > 0 {
return cfg.Gateway.UpstreamResponseReadMaxBytes
}
return defaultUpstreamResponseReadMaxBytes
}
func readUpstreamResponseBodyLimited(reader io.Reader, maxBytes int64) ([]byte, error) {
if reader == nil {
return nil, errors.New("response body is nil")
}
if maxBytes <= 0 {
maxBytes = defaultUpstreamResponseReadMaxBytes
}
body, err := io.ReadAll(io.LimitReader(reader, maxBytes+1))
if err != nil {
return nil, err
}
if int64(len(body)) > maxBytes {
return nil, fmt.Errorf("%w: limit=%d", ErrUpstreamResponseBodyTooLarge, maxBytes)
}
return body, nil
}