Constructor function for the HttpServer object
which is responsible for serving static files along
with other HTTP-related features.
179061
function HttpServer(options) {
  options = options || {};

  if (options.root) {
    this.root = options.root;
  }
  else {
    try {
      fs.lstatSync('./public');
      this.root = './public';
    }
    catch (err) {
      this.root = './';
    }
  }

  this.headers = options.headers || {};

  this.cache = options.cache === undefined ? 3600 : options.cache; // in seconds.
  this.showDir = options.showDir !== 'false';
  this.autoIndex = options.autoIndex !== 'false';
  this.gzip = options.gzip === true;
  this.contentType = options.contentType || 'application/octet-stream';

  if (options.ext) {
    this.ext = options.ext === true
      ? 'html'
      : options.ext;
  }

  var before = options.before ? options.before.slice() : [];

  before.push(function (req, res) {
    if (options.logFn) {
      options.logFn(req, res);
    }

    res.emit('next');
  });

  if (options.cors) {
    this.headers['Access-Control-Allow-Origin'] = '*';
    this.headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Range';
    if (options.corsHeaders) {
      options.corsHeaders.split(/\s*,\s*/)
          .forEach(function (h) { this.headers['Access-Control-Allow-Headers'] += ', ' + h; }, this);
    }
    before.push(corser.create(options.corsHeaders ? {
      requestHeaders: this.headers['Access-Control-Allow-Headers'].split(/\s*,\s*/)
    } : null));
  }

  if (options.robots) {
    before.push(function (req, res) {
      if (req.url === '/robots.txt') {
        res.setHeader('Content-Type', 'text/plain');
        var robots = options.robots === true
          ? 'User-agent: *\nDisallow: /'
          : options.robots.replace(/\\n/, '\n');

        return res.end(robots);
      }

      res.emit('next');
    });
  }

  before.push(ecstatic({
    root: this.root,
    cache: this.cache,
    showDir: this.showDir,
    autoIndex: this.autoIndex,
    defaultExt: this.ext,
    gzip: this.gzip,
    contentType: this.contentType,
//    handleError: typeof options.proxy !== 'string'
    handleError: (!options.fallback || typeof options.proxy === 'string')
  }));

  if (typeof options.proxy === 'string') {
    var proxy = httpProxy.createProxyServer({});
    before.push(function (req, res) {
      proxy.web(req, res, {
        target: options.proxy,
        changeOrigin: true
      });
    });
  }

  if (options.fallback) {
    before.push(function (req, res) {
      if (res.statusCode === 404) {
        res.redirect(options.fallback.address, 301);
      }
    });
  }

  var serverOptions = {
    before: before,
    headers: this.headers,
    onError: function (err, req, res) {
      if (options.logFn) {
        options.logFn(req, res, err);
      }

      res.end();
    }
  };

  if (options.https) {
    serverOptions.https = options.https;
  }

  this.server = union.createServer(serverOptions);
}
753671
def get_handler(self, *args, **options):
        
        handler = WSGIHandler()
        try:
            from django.contrib.staticfiles.handlers import StaticFilesHandler
        except ImportError:
            return handler
        use_static_handler = options.get('use_static_handler', True)
        insecure_serving = options.get('insecure_serving', False)
        if (settings.DEBUG and use_static_handler or
                (use_static_handler and insecure_serving)):
            handler = StaticFilesHandler(handler)
        return handler
1263354
function HttpsProxyAgent (opts) {
  if (!(this instanceof HttpsProxyAgent)) return new HttpsProxyAgent(opts);
  if ('string' == typeof opts) opts = url.parse(opts);
  if (!opts) throw new Error('an HTTP(S) proxy server `host` and `port` must be specified!');
  debug('creating new HttpsProxyAgent instance: %o', opts);
  Agent.call(this, connect);

  var proxy = extend({}, opts);

  // if `true`, then connect to the proxy server over TLS. defaults to `false`.
  this.secureProxy = proxy.protocol ? /^https:?$/i.test(proxy.protocol) : false;

  // prefer `hostname` over `host`, and set the `port` if needed
  proxy.host = proxy.hostname || proxy.host;
  proxy.port = +proxy.port || (this.secureProxy ? 443 : 80);

  if (proxy.host && proxy.path) {
    // if both a `host` and `path` are specified then it's most likely the
    // result of a `url.parse()` call... we need to remove the `path` portion so
    // that `net.connect()` doesn't attempt to open that as a unix socket file.
    delete proxy.path;
    delete proxy.pathname;
  }

  this.proxy = proxy;
}
387881
function create(server, fn) {
  var type = is(server)
    , options;

  if ('object' === type) options = server;
  else if ('number' === type) options = { port: server };
  else options = {};

  fn = create.fns(fn || options);

  var certs = options.key && options.cert       // Check HTTPS certs.
    , hostname = options.hostname               // Bind address.
    , port = options.port || 443                // Force HTTPS by default.
    , secure = certs || 443 === port            // Check for true HTTPS.
    , spdy = 'spdy' in options;                 // Or are we spdy.

  //
  // Determine which type of server we need to create.
  //
  if (spdy) type = 'spdy';
  else if (secure) type = 'https';
  else type = 'http';

  //
  // We need to have SSL certs for SPDY and secure servers.
  //
  if ((secure || spdy) && !certs) {
    throw new Error('Missing the SSL key or certificate files in the options.');
  }

  //
  // When given a `options.root` assume that our SSL certs and keys are path
  // references that still needs to be read. This allows a much more human
  // readable interface for SSL.
  //
  if (secure && options.root) {
    ['cert', 'key', 'ca', 'pfx', 'crl'].filter(function filter(key) {
      return key in options;
    }).forEach(function parse(key) {
      var data = options[key];

      if (Array.isArray(data)) {
        options[key] = data.map(function read(file) {
          return fs.readFileSync(path.join(options.root, file));
        });
      } else {
        options[key] = fs.readFileSync(path.join(options.root, data));
      }
    });
  }

  //
  // Provide additional protection for HTTPS server by supplying a safer cypher
  // set and prevent POODLE attacks on the servers.
  //
  if (secure) {
    //
    // Protection against POODLE attacks.
    //
    options.secureProtocol = options.secureProtocol || 'SSLv23_method';
    options.secureOptions = options.secureOptions || require('constants').SSL_OP_NO_SSLv3;

    //
    // Optimized cipher list.
    //
    options.ciphers = options.ciphers || [
      'ECDHE-RSA-AES256-SHA384',
      'DHE-RSA-AES256-SHA384',
      'ECDHE-RSA-AES256-SHA256',
      'DHE-RSA-AES256-SHA256',
      'ECDHE-RSA-AES128-SHA256',
      'DHE-RSA-AES128-SHA256',
      'HIGH',
      '!aNULL',
      '!eNULL',
      '!EXPORT',
      '!DES',
      '!RC4',
      '!MD5',
      '!PSK',
      '!SRP',
      '!CAMELLIA'
    ].join(':');
  }

  //
  // Create the correct server instance and pass in the options object for those
  // who require it (spoiler: all non http servers).
  //
  server = require(type).createServer('http' !== type ? options : undefined);

  //
  // Setup an addition redirect server which redirects people to the correct
  // HTTP or HTTPS server.
  //
  if (+options.redirect) {
    var redirect = require('http').createServer(function handle(req, res) {
      res.statusCode = 404;

      if (req.headers.host) {
        var url = parse('http://'+ req.headers.host);

        res.statusCode = 301;
        res.setHeader(
          'Location',
          'http'+ (secure ? 's' : '') +'://'+ url.hostname +':'+ port + req.url
        );
      }

      if (secure) res.setHeader(
        'Strict-Transport-Security',
        'max-age=8640000; includeSubDomains'
      );

      res.end('');
    }).listen(+options.redirect, hostname);

    //
    // Close the redirect server when the main server is closed.
    //
    server.once('close', function close() {
      try { redirect.close(); }
      catch (e) {}
    });
  }

  //
  // Assign the last callbacks.
  //
  if (fn.close) server.once('close', fn.close);
  ['request', 'upgrade', 'error'].forEach(function each(event) {
    if (fn[event]) server.on(event, fn[event]);
  });

  //
  // Things are completed, call callback.
  //
  if (fn[type]) fn[type]();

  if (options.listen !== false) {
    listen(server, port, hostname, fn.listening);
  } else if (fn.listening) {
    server.once('listening', fn.listening);
  }

  return server;
}
1308911
function(httpServer) {
      this.stop();

      var port = isNaN(options.port) ? 3000 : +options.port;
      _httpServer = httpServer || http.createServer(function(req, res) {
        res.setHeader('Access-Control-Allow-Origin', '*');
        res.setHeader('Access-Control-Request-Method', '*');
        res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET');
        res.setHeader('Access-Control-Allow-Headers', '*');
        if ( req.method === 'OPTIONS' ) {
          res.writeHead(200);
          res.end();
          return;
        }
      });
      _httpServer.on('request', _handle);
      _httpServer.listen(port, function() {
        debug.log('Listening on '+port);
      });

      return _server;
    }
367059
public HttpFileService build() {
        return new HttpFileService(new HttpFileServiceConfig(
                vfs, clock, maxCacheEntries, maxCacheEntrySizeBytes,
                serveCompressedFiles, autoIndex, headers()));
    }
357278
function Server(/* [options], [connectionListener] */) {
    events.EventEmitter.call(this);
    var self = this;

    var options;
    if (typeof arguments[0] === 'function') {
        options = {};
        this.on('connection', arguments[0]);
    } else {
        options = arguments[0] || {};
        if (typeof arguments[1] === 'function') {
            this.on('connection', arguments[1]);
        }
    }

    this._server = net.createServer(options, this._handler.bind(this));
    this._server.on('listening', function () {
        self.emit('listening');
    })
    this._server.on('close', function () {
        self.emit('close');
    })
    this._server.on('error', function (e) {
        self.emit('error', e);
    });
}
158629
function initServer (args) {
    // get server args
    var server = requireValidOptionalObject(args.server)
    // create module methods
    moduleMethods.forEach(methodName => {
        var method = server[methodName]
        // skip if no method in args
        if (!defined(method)) {
            return
        }
        // require function
        this.assert(typeof method === 'function', 110, `${methodName} method must be function`)
        // create module method
        this.module.method(methodName, method)
    })
}
543478
function NetworkServer(server) {
  this.server = server;
  function connection(socket) {
    server.connection(socket, this);
  }
  this.on('connection', connection);
}
51528
def get_handler(self, *args, **options):
        
        handler = super(Command, self).get_handler(*args, **options)
        insecure_serving = options.get('insecure_serving', False)
        if self.should_use_static_handler(options):
            return StaticFilesHandler(handler)
        return handler
998656
function serveRoutes(server) {
    self.server = server;
    server.app.use(serve);
    server.app.get('/admin/statics', function(req, res) { res.send(Object.keys(self.file$)); });
    watchAll();
    return self; // chainable
  }
437847
function createServer(port, f) {
  f = f || noop;
  http.createServer(handler).listen(port, f);
  return statusHelper.changeStatus;
}
328503
function HttpProvider(host, timeout) {
  if (!(this instanceof HttpProvider)) { throw new Error('[ethjs-provider-http] the HttpProvider instance requires the "new" flag in order to function normally (e.g. `const eth = new Eth(new HttpProvider());`).'); }
  if (typeof host !== 'string') { throw new Error('[ethjs-provider-http] the HttpProvider instance requires that the host be specified (e.g. `new HttpProvider("http://localhost:8545")` or via service like infura `new HttpProvider("http://ropsten.infura.io")`)'); }

  const self = this;
  self.host = host;
  self.timeout = timeout || 0;
}
741977
function serveStatic(options) {
    var opts = options || {};

    if (typeof opts.appendRequestPath === 'undefined') {
        opts.appendRequestPath = true;
    }

    assert.object(opts, 'options');
    assert.string(opts.directory, 'options.directory');
    assert.optionalNumber(opts.maxAge, 'options.maxAge');
    assert.optionalObject(opts.match, 'options.match');
    assert.optionalString(opts.charSet, 'options.charSet');
    assert.optionalString(opts.file, 'options.file');
    assert.bool(opts.appendRequestPath, 'options.appendRequestPath');

    var p = path.normalize(opts.directory).replace(/\\/g, '/');
    var re = new RegExp('^' + escapeRE(p) + '/?.*');

    function serveFileFromStats(file, err, stats, isGzip, req, res, next) {

        if (typeof req.connectionState === 'function' &&
            (req.connectionState() === 'close' ||
            req.connectionState() === 'aborted')) {
            next(false);
            return;
        }

        if (err) {
            next(new ResourceNotFoundError(err, '%s', req.path()));
            return;
        } else if (!stats.isFile()) {
            next(new ResourceNotFoundError('%s does not exist', req.path()));
            return;
        }

        if (res.handledGzip && isGzip) {
            res.handledGzip();
        }

        var fstream = fs.createReadStream(file + (isGzip ? '.gz' : ''));
        var maxAge = opts.maxAge === undefined ? 3600 : opts.maxAge;
        fstream.once('open', function (fd) {
            res.cache({maxAge: maxAge});
            res.set('Content-Length', stats.size);
            res.set('Content-Type', mime.lookup(file));
            res.set('Last-Modified', stats.mtime);

            if (opts.charSet) {
                var type = res.getHeader('Content-Type') +
                    '; charset=' + opts.charSet;
                res.setHeader('Content-Type', type);
            }

            if (opts.etag) {
                res.set('ETag', opts.etag(stats, opts));
            }
            res.writeHead(200);
            fstream.pipe(res);
            fstream.once('close', function () {
                next(false);
            });
        });

        res.once('close', function () {
            fstream.close();
        });
    }

    function serveNormal(file, req, res, next) {
        fs.stat(file, function (err, stats) {
            if (!err && stats.isDirectory() && opts.default) {
                // Serve an index.html page or similar
                var filePath = path.join(file, opts.default);
                fs.stat(filePath, function (dirErr, dirStats) {
                    serveFileFromStats(filePath,
                        dirErr,
                        dirStats,
                        false,
                        req,
                        res,
                        next);
                });
            } else {
                serveFileFromStats(file,
                    err,
                    stats,
                    false,
                    req,
                    res,
                    next);
            }
        });
    }

    function serve(req, res, next) {
        var file;

        if (opts.file) {
            //serves a direct file
            file = path.join(opts.directory,
                decodeURIComponent(opts.file));
        } else {
            if (opts.appendRequestPath) {
                file = path.join(opts.directory,
                    decodeURIComponent(req.path()));
            }
            else {
                var dirBasename = path.basename(opts.directory);
                var reqpathBasename = path.basename(req.path());

                if (path.extname(req.path()) === '' &&
                    dirBasename === reqpathBasename) {

                    file = opts.directory;
                }
                else {
                    file = path.join(opts.directory,
                        decodeURIComponent(path.basename(req.path())));
                }
            }
        }

        if (req.method !== 'GET' && req.method !== 'HEAD') {
            next(new MethodNotAllowedError(req.method));
            return;
        }

        if (!re.test(file.replace(/\\/g, '/'))) {
            next(new NotAuthorizedError('%s', req.path()));
            return;
        }

        if (opts.match && !opts.match.test(file)) {
            next(new NotAuthorizedError('%s', req.path()));
            return;
        }

        if (opts.gzip && req.acceptsEncoding('gzip')) {
            fs.stat(file + '.gz', function (err, stats) {
                if (!err) {
                    res.setHeader('Content-Encoding', 'gzip');
                    serveFileFromStats(file,
                        err,
                        stats,
                        true,
                        req,
                        res,
                        next);
                } else {
                    serveNormal(file, req, res, next);
                }
            });
        } else {
            serveNormal(file, req, res, next);
        }

    }

    return (serve);
}
1091991
function toServer (router) {
  assert.equal(typeof router, 'function')

  const syms = getOwnSymbols(router)
  const sym = syms.length ? syms[0] : router._sym
  assert.ok(sym, 'router should be an instance of wayfarer')

  emit._subrouters = router._subrouters
  emit._routes = router._routes
  emit[sym] = true
  emit.emit = emit
  emit.on = on

  return emit

  // match a route and execute the corresponding callback
  // (obj, obj) -> null
  // original: {path, params parentDefault}
  function emit (route, req, res) {
    assert.equal(typeof route, 'string')
    assert.ok(req, 'no req specified')

    if (!req._ssa) {
      assert.ok(res, 'no res specified')
    }

    // handle server init
    if (isReq(req) && isRes(res)) {
      const ssa = createSsa({}, req, res)
      const dft = { node: { cb: [ router._default ] } }
      return router(route, ssa, dft)
    }

    // handle subrouter
    const params = req
    const parentDefault = res
    router(route, params, parentDefault)
  }

  // register a new route on a method
  // (str, obj) -> obj
  function on (route, methods) {
    assert.equal(typeof route, 'string')
    methods = methods || {}

    // mount subrouter
    if (methods[sym]) return router.on(route, methods)

    assert.equal(typeof methods, 'object')

    // mount http methods
    router.on(route, function (args) {
      demuxSsa(args, function (req, res, params) {
        const meth = methodist(req, defaultFn, methods)
        meth(req, res, params)

        // default function to call if methods don't match
        // null -> null
        function defaultFn () {
          router._default(args)
        }
      })
    })
    return emit
  }
}
206947
def serve(path, livereload, port, verbose):
    
    setup_logging(verbose)
    run_app(*serve_static(static_path=path, livereload=livereload, port=port))
1097079
public function createServerRequestFromServer(): ServerRequestInterface
        {
            $method  = $_SERVER['REQUEST_METHOD'];
            $uri     = (new UriFactory)->createUriFromServer($_SERVER);
            $files   = (new UploadedFileFactory)->createUploadedFileFromServer($_FILES);
            
            $request = $this->createServerRequest($method, $uri, $_SERVER);
            $request = $request->withQueryParams($_GET);
            $request = $request->withParsedBody($_POST);
            $request = $request->withCookieParams($_COOKIE);
            $request = $request->withUploadedFiles($files);
            return $request;
        }