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
39 lines
958 B
Go
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
|
|
}
|