NOTE: Do not out-clever yourself here! You _can_ add the CORS headers in this function, but if you're already doing it inside an external webserver like Nginx or Node.js, it will cause CORS _not_ to work.
358676
function (doc, req) {
         // This function will be used to implement "touch" for `get_avar`.
            var response;
            response = {
                headers: {
                    'Content-Type': 'application/json'
                },
                body: (doc === null) ? '{}' : doc.body
            };
            if (doc instanceof Object) {
                doc.last_touch = Date.now();
            }
            return [doc, response];
        }
896962
def options(self, *args, **kwargs):
        
        if getattr(options, 'cors', False):
            self.set_header('Access-Control-Allow-Headers',
                            'Content-Type, Authorization, '
                            'Accept, X-Requested-With')
            self.set_header('Access-Control-Allow-Methods',
                            'OPTIONS, TRACE, GET, HEAD, POST, '
                            'PUT, PATCH, DELETE')

        self.finish()
1294226
function &parseResponseHeaders(&$data, $headers_processed=false)
		{
				// Support "web-proxy-tunelling" connections for https through proxies
				if(preg_match('/^HTTP\/1\.[0-1] 200 Connection established/', $data))
				{
					// Look for CR/LF or simple LF as line separator,
					// (even though it is not valid http)
					$pos = strpos($data,"\r\n\r\n");
					if($pos || is_int($pos))
					{
						$bd = $pos+4;
					}
					else
					{
						$pos = strpos($data,"\n\n");
						if($pos || is_int($pos))
						{
							$bd = $pos+2;
						}
						else
						{
							// No separation between response headers and body: fault?
							$bd = 0;
						}
					}
					if ($bd)
					{
						// this filters out all http headers from proxy.
						// maybe we could take them into account, too?
						$data = substr($data, $bd);
					}
					else
					{
						error_log('XML-RPC: '.__METHOD__.': HTTPS via proxy error, tunnel connection possibly failed');
						$r=new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['http_error'], $GLOBALS['xmlrpcstr']['http_error']. ' (HTTPS via proxy error, tunnel connection possibly failed)');
						return $r;
					}
				}

				// Strip HTTP 1.1 100 Continue header if present
				while(preg_match('/^HTTP\/1\.1 1[0-9]{2} /', $data))
				{
					$pos = strpos($data, 'HTTP', 12);
					// server sent a Continue header without any (valid) content following...
					// give the client a chance to know it
					if(!$pos && !is_int($pos)) // works fine in php 3, 4 and 5
					{
						break;
					}
					$data = substr($data, $pos);
				}
				if(!preg_match('/^HTTP\/[0-9.]+ 200 /', $data))
				{
					$errstr= substr($data, 0, strpos($data, "\n")-1);
					error_log('XML-RPC: '.__METHOD__.': HTTP error, got response: ' .$errstr);
					$r=new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['http_error'], $GLOBALS['xmlrpcstr']['http_error']. ' (' . $errstr . ')');
					return $r;
				}

				$GLOBALS['_xh']['headers'] = array();
				$GLOBALS['_xh']['cookies'] = array();

				// be tolerant to usage of \n instead of \r\n to separate headers and data
				// (even though it is not valid http)
				$pos = strpos($data,"\r\n\r\n");
				if($pos || is_int($pos))
				{
					$bd = $pos+4;
				}
				else
				{
					$pos = strpos($data,"\n\n");
					if($pos || is_int($pos))
					{
						$bd = $pos+2;
					}
					else
					{
						// No separation between response headers and body: fault?
						// we could take some action here instead of going on...
						$bd = 0;
					}
				}
				// be tolerant to line endings, and extra empty lines
				$ar = preg_split("/\r?\n/", trim(substr($data, 0, $pos)));
				while(list(,$line) = @each($ar))
				{
					// take care of multi-line headers and cookies
					$arr = explode(':',$line,2);
					if(count($arr) > 1)
					{
						$header_name = strtolower(trim($arr[0]));
						/// @todo some other headers (the ones that allow a CSV list of values)
						/// do allow many values to be passed using multiple header lines.
						/// We should add content to $GLOBALS['_xh']['headers'][$header_name]
						/// instead of replacing it for those...
						if ($header_name == 'set-cookie' || $header_name == 'set-cookie2')
						{
							if ($header_name == 'set-cookie2')
							{
								// version 2 cookies:
								// there could be many cookies on one line, comma separated
								$cookies = explode(',', $arr[1]);
							}
							else
							{
								$cookies = array($arr[1]);
							}
							foreach ($cookies as $cookie)
							{
								// glue together all received cookies, using a comma to separate them
								// (same as php does with getallheaders())
								if (isset($GLOBALS['_xh']['headers'][$header_name]))
									$GLOBALS['_xh']['headers'][$header_name] .= ', ' . trim($cookie);
								else
									$GLOBALS['_xh']['headers'][$header_name] = trim($cookie);
								// parse cookie attributes, in case user wants to correctly honour them
								// feature creep: only allow rfc-compliant cookie attributes?
								// @todo support for server sending multiple time cookie with same name, but using different PATHs
								$cookie = explode(';', $cookie);
								foreach ($cookie as $pos => $val)
								{
									$val = explode('=', $val, 2);
									$tag = trim($val[0]);
									$val = trim(@$val[1]);
									/// @todo with version 1 cookies, we should strip leading and trailing " chars
									if ($pos == 0)
									{
										$cookiename = $tag;
										$GLOBALS['_xh']['cookies'][$tag] = array();
										$GLOBALS['_xh']['cookies'][$cookiename]['value'] = urldecode($val);
									}
									else
									{
										if ($tag != 'value')
										{
										  $GLOBALS['_xh']['cookies'][$cookiename][$tag] = $val;
										}
									}
								}
							}
						}
						else
						{
							$GLOBALS['_xh']['headers'][$header_name] = trim($arr[1]);
						}
					}
					elseif(isset($header_name))
					{
						///	@todo version1 cookies might span multiple lines, thus breaking the parsing above
						$GLOBALS['_xh']['headers'][$header_name] .= ' ' . trim($line);
					}
				}

				$data = substr($data, $bd);

				if($this->debug && count($GLOBALS['_xh']['headers']))
				{
					print '<PRE>';
					foreach($GLOBALS['_xh']['headers'] as $header => $value)
					{
						print htmlentities("HEADER: $header: $value\n");
					}
					foreach($GLOBALS['_xh']['cookies'] as $header => $value)
					{
						print htmlentities("COOKIE: $header={$value['value']}\n");
					}
					print "</PRE>\n";
				}

				// if CURL was used for the call, http headers have been processed,
				// and dechunking + reinflating have been carried out
				if(!$headers_processed)
				{
					// Decode chunked encoding sent by http 1.1 servers
					if(isset($GLOBALS['_xh']['headers']['transfer-encoding']) && $GLOBALS['_xh']['headers']['transfer-encoding'] == 'chunked')
					{
						if(!$data = decode_chunked($data))
						{
							error_log('XML-RPC: '.__METHOD__.': errors occurred when trying to rebuild the chunked data received from server');
							$r = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['dechunk_fail'], $GLOBALS['xmlrpcstr']['dechunk_fail']);
							return $r;
						}
					}

					// Decode gzip-compressed stuff
					// code shamelessly inspired from nusoap library by Dietrich Ayala
					if(isset($GLOBALS['_xh']['headers']['content-encoding']))
					{
						$GLOBALS['_xh']['headers']['content-encoding'] = str_replace('x-', '', $GLOBALS['_xh']['headers']['content-encoding']);
						if($GLOBALS['_xh']['headers']['content-encoding'] == 'deflate' || $GLOBALS['_xh']['headers']['content-encoding'] == 'gzip')
						{
							// if decoding works, use it. else assume data wasn't gzencoded
							if(function_exists('gzinflate'))
							{
								if($GLOBALS['_xh']['headers']['content-encoding'] == 'deflate' && $degzdata = @gzuncompress($data))
								{
									$data = $degzdata;
									if($this->debug)
									print "<PRE>---INFLATED RESPONSE---[".strlen($data)." chars]---\n" . htmlentities($data) . "\n---END---</PRE>";
								}
								elseif($GLOBALS['_xh']['headers']['content-encoding'] == 'gzip' && $degzdata = @gzinflate(substr($data, 10)))
								{
									$data = $degzdata;
									if($this->debug)
									print "<PRE>---INFLATED RESPONSE---[".strlen($data)." chars]---\n" . htmlentities($data) . "\n---END---</PRE>";
								}
								else
								{
									error_log('XML-RPC: '.__METHOD__.': errors occurred when trying to decode the deflated data received from server');
									$r = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['decompress_fail'], $GLOBALS['xmlrpcstr']['decompress_fail']);
									return $r;
								}
							}
							else
							{
								error_log('XML-RPC: '.__METHOD__.': the server sent deflated data. Your php install must have the Zlib extension compiled in to support this.');
								$r = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['cannot_decompress'], $GLOBALS['xmlrpcstr']['cannot_decompress']);
								return $r;
							}
						}
					}
				} // end of 'if needed, de-chunk, re-inflate response'

				// real stupid hack to avoid PHP complaining about returning NULL by ref
				$r = null;
				$r =& $r;
				return $r;
		}
1167983
private function headers()
    {
        $headers = '';
        foreach (config('cors.headers') as $header) {
            $headers = $headers . $header . ', ';
        }
        header('Access-Control-Allow-Headers: ' . $headers);
    }
935829
function _cors (cookieDomain, publicUrl) {
  return ({ acceptServers, acceptAllOrigins }) => {
    // accept server 2 server requests by default
    acceptServers = acceptServers === undefined ? true : acceptServers
    // do not accept call by outside origins by default
    acceptAllOrigins = acceptAllOrigins === undefined ? false : acceptAllOrigins
    return corsBuilder({
      credentials: true,
      origin (origin, callback) {
        // Case of server to server requests
        if (!origin) {
          if (acceptServers) return callback(null, true)
          return callback(new Error('No CORS allowed for server to server requests'))
        }

        // Case where we accept any domain as origin
        if (acceptAllOrigins) return callback(null, true)

        const originDomain = new URL(origin).host

        // Case of mono-domain acceptance
        if (!cookieDomain) {
          if (originDomain === new URL(publicUrl).host) return callback(null, true)
          return callback(new Error(`No CORS allowed from origin ${origin}`))
        }

        // Case of subdomains acceptance
        if (originDomain === cookieDomain || originDomain.endsWith('.' + cookieDomain)) {
          return callback(null, true)
        }
        callback(new Error(`No CORS allowed from origin ${origin}`))
      }
    })
  }
}
437770
function getResponseHeaders(xhr) {
    let raw = xhr.getAllResponseHeaders();
    let parts = raw.replace(/\s+$/, '').split(/\n/);
    for (let i = 0; i < parts.length; i++) {
        parts[i] = parts[i].replace(/\r/g, '').replace(/^\s+/, '').replace(/\s+$/, '');
    }
    return parts;
}
603401
private function cors($request)
  {
    $origin  = $request->server->http_origin;
    $allowed = Config::get('cors.allowedOrigins');

    if (in_array('*', $allowed) || in_array($origin, $allowed) ) {
      $this->withHeaders($request);
    }
  }
1243811
protected function addCorsHeaders()
    {
        // set CORS headers if specified in config
        if (!isset($this->config['docs']['cors'])) {
            return false;
        }

        if (!count($this->config['docs']['cors'])) {
            return false;
        }

        foreach ($this->config['docs']['cors'] as $header => $value) {
            $this->response = $this->response->withHeader($header, $value);
        }
    }
697546
func CORS(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// Set allow origin to match origin of our request or fall back to *
		if o := r.Header.Get(origin); o != "" {
			w.Header().Set(allow_origin, o)
		} else {
			w.Header().Set(allow_origin, "*")
		}

		// Set other headers
		w.Header().Set(allow_headers, headers)
		w.Header().Set(allow_methods, methods)
		w.Header().Set(allow_credentials, credentials)
		w.Header().Set(expose_headers, headers)

		// If this was preflight options request let's write empty ok response and return
		if r.Method == options {
			w.WriteHeader(http.StatusOK)
			w.Write(nil)
			return
		}

		next.ServeHTTP(w, r)
	})
}
460101
def _handle_headers(self):
        
        origin = self.request.headers.get('Origin')
        if not settings.DEBUG:
            if origin in settings.ALLOWED_ORIGINS or not origin:
                self.set_header('Access-Control-Allow-Origin', origin)
            else:
                log.debug("CORS ERROR: %s not allowed, allowed hosts: %s" % (origin,
                                                                             settings.ALLOWED_ORIGINS))
                raise HTTPError(403, "Origin not in ALLOWED_ORIGINS: %s" % origin)
        else:
            self.set_header('Access-Control-Allow-Origin', origin or '*')
        self.set_header('Access-Control-Allow-Credentials', "true")
        self.set_header('Access-Control-Allow-Headers', 'Content-Type')
        self.set_header('Access-Control-Allow-Methods', 'OPTIONS')
        self.set_header('Content-Type', 'application/json')
306708
public static function allowCors()
    {
        $origin = filter_input(INPUT_SERVER, 'HTTP_ORIGIN');
        $protocol = filter_input(INPUT_SERVER, 'REQUEST_SCHEME') ?? 'http';
        $host = preg_replace("/^http(s)?:\/{2}/", "", $origin);
        $allowedHosts = cfg::ALLOW_CORS;
        $allowedHosts[] = cfg::HOST_DEV;

        if (in_array($host, $allowedHosts)) {
            header("Access-Control-Allow-Origin: " . $protocol . "://" . $host);
        }
    }
1080701
def set_cors_common_headers(self):
        
        if not self.cors: return

        req = self.request
        origin = req.get_header('origin')
        if origin:
            self.response.set_header('Access-Control-Allow-Origin', origin)
1260979
function(base_url, callback, cors) {
    var recv = new XhrReceiver(base_url + '/chunking_test', {cors: cors});
    var result = 0;
    recv.onmessage = function(e) {
        // Now a cool hack: we can stop receiving after we got at least
        // one chunk, contains some data, but not everyting.
        var l = e.responsetext.split('h\n').length;
        if(e.readystate === 3 && l > 0 && l < 6 ) {
            result = l;
            recv.abort();
        }
    };
    recv.onclose = function(e) {
        recv = recv.onmessage = recv.onclose = null;
        utils.log('Chunking test: ' + (result ? 'passed' : 'failed')
                  + ' (' + result + ' chunk received)');
        callback(!!result);
    };
}
149597
function getCORSRequest() {
  var xhr = new root.XMLHttpRequest();
  if ('withCredentials' in xhr) {
    return xhr;
  } else if (!!root.XDomainRequest) {
    return new XDomainRequest();
  } else {
    throw new Error('CORS is not supported by your browser');
  }
}
229003
def set_cors_config(app):
    
    if "CORS" in app.config:
        for k, v in app.config["CORS"].items():
            _ = "CORS_" + k.upper()
            if _ not in app.config:
                app.config[_] = v
254124
func Cors(allowedOrigins ...string) http.HandlerFunc {
	if len(allowedOrigins) == 0 {
		allowedOrigins = append(allowedOrigins, "*")
	}
	return func(rw http.ResponseWriter, req *http.Request) {
		allowed := false
		// Set appropriate response headers required for CORS
		reqOrigin := req.Header.Get(headerGetOrigin)
		for _, o := range allowedOrigins {
			// Set appropriate response headers required for CORS
			if o == "*" || o == reqOrigin {
				rw.Header().Set(headerOrigin, reqOrigin)
				allowed = true
				break
			}
		}

		if !allowed {
			webgo.SendHeader(rw, http.StatusForbidden)
			return
		}

		rw.Header().Set(headerMethods, allowMethods)
		rw.Header().Set(headerCreds, "true")

		// Adding allowed headers
		rw.Header().Set(headerAllowHeaders, allowHeaders+req.Header.Get(headerReqHeaders))
	}
}
1197840
async function externalRequest(transport, options, callback) {
    // perform the DNS lookup manually so that the HTTP host header generated by
    // http.get will contain the IP address, this is needed because since Chrome
    // 66 the host header cannot contain an host name different than localhost
    // (see https://github.com/cyrus-and/chrome-remote-interface/issues/340)
    if (!options.useHostName) {
        try {
            const {address} = await util.promisify(dns.lookup)(options.host);
            options = Object.assign({}, options);
            options.host = address;
        } catch (err) {
            callback(err);
            return;
        }
    }
    // perform the actual request
    const request = transport.get(options, (response) => {
        let data = '';
        response.on('data', (chunk) => {
            data += chunk;
        });
        response.on('end', () => {
            if (response.statusCode === 200) {
                callback(null, data);
            } else {
                callback(new Error(data));
            }
        });
    });
    request.setTimeout(REQUEST_TIMEOUT, () => {
        request.abort();
    });
    request.on('error', callback);
}