From a7b103e92852907114ef7f72efbd89e23bf2a858 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=96=E7=95=8C?= Date: Fri, 23 Aug 2024 12:41:53 +0800 Subject: [PATCH] Add PNA support (cherry picked from commit 41a1de4d02ba902fcc0a8717f9aee0f70d6ed849) --- cors.go | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/cors.go b/cors.go index f3e2b00..d9a5516 100644 --- a/cors.go +++ b/cors.go @@ -59,6 +59,9 @@ type Options struct { // cookies, HTTP authentication or client side SSL certificates. AllowCredentials bool + // AllowPrivateNetwork allows requests from private networks + AllowPrivateNetwork bool + // MaxAge indicates how long (in seconds) the results of a preflight request // can be cached MaxAge int @@ -106,18 +109,20 @@ type Cors struct { // Set to true when allowed headers contains a "*" allowedHeadersAll bool - allowCredentials bool - optionPassthrough bool + allowCredentials bool + allowPrivateNetwork bool + optionPassthrough bool } // New creates a new Cors handler with the provided options. func New(options Options) *Cors { c := &Cors{ - exposedHeaders: convert(options.ExposedHeaders, http.CanonicalHeaderKey), - allowOriginFunc: options.AllowOriginFunc, - allowCredentials: options.AllowCredentials, - maxAge: options.MaxAge, - optionPassthrough: options.OptionsPassthrough, + exposedHeaders: convert(options.ExposedHeaders, http.CanonicalHeaderKey), + allowOriginFunc: options.AllowOriginFunc, + allowCredentials: options.AllowCredentials, + allowPrivateNetwork: options.AllowPrivateNetwork, + maxAge: options.MaxAge, + optionPassthrough: options.OptionsPassthrough, } if options.Debug && c.Log == nil { c.Log = log.New(os.Stdout, "[cors] ", log.LstdFlags) @@ -278,6 +283,10 @@ func (c *Cors) handlePreflight(w http.ResponseWriter, r *http.Request) { // from Access-Control-Request-Headers can be enough headers.Set("Access-Control-Allow-Headers", strings.Join(reqHeaders, ", ")) } + reqPrivateNetwork := r.Header.Get("Access-Control-Request-Private-Network") == "true" + if reqPrivateNetwork && c.allowPrivateNetwork { + headers.Set("Access-Control-Allow-Private-Network", "true") + } if c.allowCredentials { headers.Set("Access-Control-Allow-Credentials", "true") }