net/http: reduce allocs in CrossOriginProtection.Check

Rather than repeatedly creating error values on
CrossOriginProtection.Check's unhappy paths, return non-exported and
effectively constant error variables.
This commit is contained in:
Julien Cretel 2025-06-16 12:49:25 +02:00
parent 96a6e147b2
commit e704d63cd6
No known key found for this signature in database
GPG Key ID: 1449149EC303618F
1 changed files with 8 additions and 3 deletions

View File

@ -136,7 +136,7 @@ func (c *CrossOriginProtection) Check(req *Request) error {
if c.isRequestExempt(req) {
return nil
}
return errors.New("cross-origin request detected from Sec-Fetch-Site header")
return errCrossOriginRequest
}
origin := req.Header.Get("Origin")
@ -159,10 +159,15 @@ func (c *CrossOriginProtection) Check(req *Request) error {
if c.isRequestExempt(req) {
return nil
}
return errors.New("cross-origin request detected, and/or browser is out of date: " +
"Sec-Fetch-Site is missing, and Origin does not match Host")
return errCrossOriginRequestFromOldBrowser
}
var (
errCrossOriginRequest = errors.New("cross-origin request detected from Sec-Fetch-Site header")
errCrossOriginRequestFromOldBrowser = errors.New("cross-origin request detected, and/or browser is out of date: " +
"Sec-Fetch-Site is missing, and Origin does not match Host")
)
// isRequestExempt checks the bypasses which require taking a lock, and should
// be deferred until the last moment.
func (c *CrossOriginProtection) isRequestExempt(req *Request) bool {