Gevent-based WSGI-HTTP server.
548206
def serve(application, host='127.0.0.1', port=8080):
	""""""
	
	# Instantiate the server with a host/port configuration and our application.
	WSGIServer((host, int(port)), application).serve_forever()
4106
def create_wsgi_request(event, server_name='apigw'):
    
    path = urllib.url2pathname(event['path'])
    script_name = (
        event['headers']['Host'].endswith('.amazonaws.com') and
        event['requestContext']['stage'] or '').encode('utf8')
    query = event['queryStringParameters']
    query_string = query and urllib.urlencode(query) or ""
    body = event['body'] and event['body'].encode('utf8') or ''

    environ = {
        'HTTPS': 'on',
        'PATH_INFO': path.encode('utf8'),
        'QUERY_STRING': query_string.encode('utf8'),
        'REMOTE_ADDR': event[
            'requestContext']['identity']['sourceIp'].encode('utf8'),
        'REQUEST_METHOD': event['httpMethod'].encode('utf8'),
        'SCRIPT_NAME': script_name,
        'SERVER_NAME': server_name.encode('utf8'),
        'SERVER_PORT': '80'.encode('utf8'),
        'SERVER_PROTOCOL': u'HTTP/1.1'.encode('utf8'),

        'wsgi.errors': sys.stderr,
        'wsgi.input': StringIO(body),
        'wsgi.multiprocess': False,
        'wsgi.multithread': False,
        'wsgi.run_once': False,
        'wsgi.url_scheme': u'https'.encode('utf8'),
        'wsgi.version': (1, 0),
    }

    headers = event['headers']
    # Input processing
    if event['httpMethod'] in ("POST", "PUT", "PATCH"):
        if 'Content-Type' in headers:
            environ['CONTENT_TYPE'] = headers['Content-Type']
        environ['CONTENT_LENGTH'] = str(len(body))

    for header in list(event['headers'].keys()):
        wsgi_name = "HTTP_" + header.upper().replace('-', '_')
        environ[wsgi_name] = headers[header].encode('utf8')

    if script_name:
        path_info = environ['PATH_INFO']
        if script_name in path_info:
            environ['PATH_INFO'].replace(script_name, '')

    # Extract remote user from event
    remote_user = None
    if event['requestContext'].get('authorizer'):
        remote_user = event[
            'requestContext']['authorizer'].get('principalId')
    elif event['requestContext'].get('identity'):
        remote_user = event['requestContext']['identity'].get('userArn')
    if remote_user:
        environ['REMOTE_USER'] = remote_user

    # apigw aware integrations
    environ['apigw.request'] = event['requestContext']
    environ['apigw.stagevars'] = event['stageVariables']

    return environ
1329261
def run_gevent(self):
        """"""
        from pywb.utils.geventserver import GeventServer, RequestURIWSGIHandler
        logging.info('Starting Gevent Server on ' + str(self.r.port))
        ge = GeventServer(self.application,
                          port=self.r.port,
                          hostname=self.r.bind,
                          handler_class=RequestURIWSGIHandler,
                          direct=True)
1027781
def wsgi(self, environ, start_response):
        
        try:
            out = self._cast(self._handle(environ))
            # rfc2616 section 4.3
            if response._status_code in (100, 101, 204, 304)\
            or environ['REQUEST_METHOD'] == 'HEAD':
                if hasattr(out, 'close'): out.close()
                out = []
            start_response(response._status_line, response.headerlist)
            return out
        except (KeyboardInterrupt, SystemExit, MemoryError):
            raise
        except Exception:
            if not self.catchall: raise
            err = '<h1>Critical error while processing request: %s</h1>' \
                  % html_escape(environ.get('PATH_INFO', '/'))
            if DEBUG:
                err += '<h2>Error:</h2>\n<pre>\n%s\n</pre>\n' \
                       '<h2>Traceback:</h2>\n<pre>\n%s\n</pre>\n' \
                       % (html_escape(repr(_e())), html_escape(format_exc()))
            environ['wsgi.errors'].write(err)
            headers = [('Content-Type', 'text/html; charset=UTF-8')]
            start_response('500 INTERNAL SERVER ERROR', headers, sys.exc_info())
            return [tob(err)]
561966
def setup_server(config_path):
    """"""
    # configure the SharQ server
    server = SharQServer(config_path)
    # start the requeue loop
    gevent.spawn(server.requeue)

    return server
341731
function createNodeServer(http, nodePort, webSocketPort, watchFiles, tsWarning, tsError, target) {
    return http.createServer(async (req, res) => {
        try {
            const fileExtension = req.url.slice(req.url.lastIndexOf('.') + 1);
            switch (fileExtension) {
                case '/': {
                    const indexFileContents = (await fs.readFile(`./index.html`)).toString();
                    const modifiedIndexFileContents = modifyHTML(indexFileContents, 'index.html', watchFiles, webSocketPort);
                    watchFile(`./index.html`, watchFiles);
                    res.end(modifiedIndexFileContents);
                    return;
                }
                case 'js': {
                    await handleScriptExtension(req, res, fileExtension);
                    return;
                }
                case 'mjs': {
                    await handleScriptExtension(req, res, fileExtension);
                    return;
                }
                case 'ts': {
                    await handleScriptExtension(req, res, fileExtension);
                    return;
                }
                case 'tsx': {
                    await handleScriptExtension(req, res, fileExtension);
                    return;
                }
                case 'jsx': {
                    await handleScriptExtension(req, res, fileExtension);
                    return;
                }
                case 'wast': {
                    await handleWASTExtension(req, res, fileExtension);
                    return;
                }
                case 'wasm': {
                    await handleWASMExtension(req, res, fileExtension);
                    return;
                }
                default: {
                    await handleGenericFile(req, res, fileExtension);
                    return;
                }
            }
        }
        catch(error) {
            console.log(error);
        }
    });
}
767062
def WSGIMimeRender(*args, **kwargs):
    '''
    
    '''
    def wrapper(*args2, **kwargs2):
        # take the function
        def wrapped(f):
            return _WSGIMimeRender(*args, **kwargs)(*args2, **kwargs2)(wsgi_wrap(f))
        return wrapped
    return wrapper
1158936
def serve_http(self):
        
        start_http_server(port=self.options.port,
                          addr=str(self.options.address))
1161664
def connect(self, (host, port)):
        '''
        
        '''
        super(GeventTransport, self).connect((host, port), klass=socket.socket)
316437
def serve(application, host='127.0.0.1', port=8080):
	""""""
	
	# Instantiate the server with our configuration and application.
	server = CherryPyWSGIServer((host, int(port)), application, server_name=host)
	
	# Try to be handy as many terminals allow clicking links.
	print("serving on http://{0}:{1}".format(host, port))
	
	# Bind and launch the server; this is a blocking operation.
	try:
		server.start()
	except KeyboardInterrupt:
		server.stop()
1107809
function WebServer(data) {
  // Use a closure to preserve `this`
  var self = this;
  self.data = data;

  this.RequestHandler = bind(this.RequestHandler, this);
  this.callbackExecutor = bind(this.callbackExecutor, this);

  self.server = http.createServer(self.RequestHandler);

  // Use random port if port settings is not provided.
  if (!self.data.port) {
    self.data.port = 0;
  }

  // Use address if provided.
  if (self.data.hostname) {
    self.server.listen(self.data.port, self.data.hostname);
  } else {
    self.server.listen(self.data.port);
  }

  self.server.on('listening', function() {
    self.debug.log('Listen on :%s', self.server.address().port);
  });
}
461047
def serve(ip, port, application, ssl=None, processes=1, **kwargs):
    

    try:
        # use werkzeug if its there
        from werkzeug.serving import run_simple
        print("Using Werkzeug run_simple")
        run_simple(ip, port, application, ssl_context=ssl, processes=processes, **kwargs)
        return
    except ImportError:
        pass

    # otherwise just use python's built in wsgi webserver
    from wsgiref.simple_server import make_server
    server = make_server(ip, port, application)
    print("Serving on %s:%s, using built in Python server" % (ip, port))
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        pass
892633
public function http()
    {
        $this->writeln('Starting swoole http server...');

        $server = new HttpServer(
            $this->swooleConfig['http']['host'] ?? self::DEFAULT_SWOOLE_HOST,
            $this->swooleConfig['http']['port'] ?? self::DEFAULT_SWOOLE_PORT
        );

        $server->on(
            'Request', function ($request, $response) {

                $swooleRequest = (new SwooleRequest())->setSwooleRequest($request);
                $swooleResponse = (new SwooleResponse())->setSwooleResponse($response);
                $sessionId = $swooleRequest->getCookie('swoole_session_id');
                if (!$sessionId) {
                    $sessionId = IdGenerator::component()->generate();
                    $swooleResponse->setCookie('swoole_session_id', $sessionId);
                }
                $swooleRequest->setSessionId($sessionId);
                $swooleResponse->setSessionId($sessionId);

                (new App($swooleRequest, $swooleResponse))->run();

            }
        );

        $server->start();
    }
1349144
function createServer() {
  function app(req, res, next) {
    app.handle(req, res, next);
  }
  app.method = '*';
  merge(app, proto);
  merge(app, EventEmitter.prototype);
  app.stack = [];
  app.params = [];
  app._cachedEvents = [] ;
  app.routedMethods = {} ;
  app.locals = Object.create(null);
  for (var i = 0; i < arguments.length; ++i) {
    app.use(arguments[i]);
  }

  //create methods app.invite, app.register, etc..
  methods.forEach((method) => {
    app[method.toLowerCase()] = app.use.bind(app, method.toLowerCase()) ;
  }) ;

  //special handling for cdr events
  app.on = function(event, listener) {
    if (0 === event.indexOf('cdr:')) {
      if (app.client) {
        app.client.on(event, function() {
          var args = Array.prototype.slice.call(arguments) ;
          EventEmitter.prototype.emit.apply(app, [event].concat(args)) ;
        }) ;
      }
      else {
        this._cachedEvents.push(event) ;
      }
    }
    //delegate all others to standard EventEmitter prototype
    return EventEmitter.prototype.addListener.call(app, event, listener) ;
  } ;

  return app;
}
17591
def main(global_config, **settings):
    
    config = Configurator(settings=settings)

    includeme(config)
    return config.make_wsgi_app()
847626
def build_environ(scope, message, body):
    
    environ = {
        "REQUEST_METHOD": scope["method"],
        "SCRIPT_NAME": "",
        "PATH_INFO": scope["path"],
        "QUERY_STRING": scope["query_string"].decode("ascii"),
        "SERVER_PROTOCOL": "HTTP/%s" % scope["http_version"],
        "wsgi.version": (1, 0),
        "wsgi.url_scheme": scope.get("scheme", "http"),
        "wsgi.input": io.BytesIO(body),
        "wsgi.errors": sys.stdout,
        "wsgi.multithread": True,
        "wsgi.multiprocess": True,
        "wsgi.run_once": False,
    }

    # Get server name and port - required in WSGI, not in ASGI
    server = scope.get("server", ("localhost", 80))
    environ["SERVER_NAME"] = server[0]
    environ["SERVER_PORT"] = server[1]

    # Get client IP address
    if "client" in scope:
        environ["REMOTE_ADDR"] = scope["client"][0]

    # Go through headers and make them into environ entries
    for name, value in scope.get("headers", []):
        name = name.decode("latin1")
        if name == "content-length":
            corrected_name = "CONTENT_LENGTH"
        elif name == "content-type":
            corrected_name = "CONTENT_TYPE"
        else:
            corrected_name = "HTTP_%s" % name.upper().replace("-", "_")
        # HTTPbis say only ASCII chars are allowed in headers, but we latin1 just in case
        value = value.decode("latin1")
        if corrected_name in environ:
            value = environ[corrected_name] + "," + value
        environ[corrected_name] = value
    return environ
187256
def setup(self, environ):
        '''
        '''
        request = wsgi_request(environ)
        cfg = request.cache.cfg
        loop = request.cache._loop
        self.store = create_store(cfg.data_store, loop=loop)
        pubsub = self.store.pubsub(protocol=Protocol())
        channel = '%s_webchat' % self.name
        ensure_future(pubsub.subscribe(channel), loop=loop)
        return WsgiHandler([Router('/', get=self.home_page),
                            WebSocket('/message', Chat(pubsub, channel)),
                            Router('/rpc', post=Rpc(pubsub, channel),
                                   response_content_types=JSON_CONTENT_TYPES)],
                           [AsyncResponseMiddleware,
                            GZipMiddleware(min_length=20)])