Constructor function for the HttpServer object
which is responsible for serving static files along
with other HTTP-related features.
353433
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 :
    // -1 is a special case to turn off caching.
    // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control#Preventing_caching
    options.cache === -1 ? 'no-cache, no-store, must-revalidate' :
    options.cache // in seconds.
  );
  this.showDir = options.showDir !== 'false';
  this.autoIndex = options.autoIndex !== 'false';
  this.showDotfiles = options.showDotfiles;
  this.gzip = options.gzip === true;
  this.brotli = options.brotli === 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.username || options.password) {
    before.push(function (req, res) {
      var credentials = auth(req);

      // We perform these outside the if to avoid short-circuiting and giving
      // an attacker knowledge of whether the username is correct via a timing
      // attack.
      if (credentials) {
        var usernameEqual = secureCompare(options.username, credentials.name);
        var passwordEqual = secureCompare(options.password, credentials.pass);
        if (usernameEqual && passwordEqual) {
          return res.emit('next');
        }
      }

      res.statusCode = 401;
      res.setHeader('WWW-Authenticate', 'Basic realm=""');
      res.end('Access denied');
    });
  }

  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,
    showDotfiles: this.showDotfiles,
    autoIndex: this.autoIndex,
    defaultExt: this.ext,
    gzip: this.gzip,
    brotli: this.brotli,
    contentType: this.contentType,
    handleError: 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
      }, function (err, req, res, target) {
        if (options.logFn) {
          options.logFn(req, res, {
            message: err.message,
            status: res.statusCode });
        }
        res.emit('next');
      });
    });
  }

  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);
}
976273
function createServer(webhook)
{
  var self = this

  var onError = this.emit.bind(this, 'error')

  var port     = webhook.port     || 0
  var hostname = webhook.hostname || HOSTNAME

  var server = http.createServer(function(req, res)
  {
    if(req.method === 'GET')
    {
      res.end()

      return self.push(parse(req.url).query)
    }

    req.pipe(concat(function(body)
    {
      res.end()

      self.push(body.toString())
    }))
  })
  .listen(port, hostname, function()
  {
    var address = this.address()

    if(hostname === HOSTNAME) hostname = getHostname()

    if(!hostname)
    {
      self.emit('error', new Error("There's no public available interfaces"))

      return this.close()
    }

    self.emit('open', 'http://'+hostname+':'+address.port)
  })
  .on('error'      , onError)
  .on('clientError', onError)

  return server
}
919173
Function<TcpClient, TcpClient> build() {
		HttpResponseDecoderSpec decoder = new HttpResponseDecoderSpec();
		decoder.initialBufferSize = initialBufferSize;
		decoder.maxChunkSize = maxChunkSize;
		decoder.maxHeaderSize = maxHeaderSize;
		decoder.maxInitialLineLength = maxInitialLineLength;
		decoder.validateHeaders = validateHeaders;
		decoder.failOnMissingResponse = failOnMissingResponse;
		decoder.parseHttpAfterConnectRequest = parseHttpAfterConnectRequest;
		return tcp -> tcp.bootstrap(b -> HttpClientConfiguration.decoder(b, decoder));
	}
544906
def statichttp(container = None):
    ""
    def decorator(func):
        @functools.wraps(func)
        def handler(event):
            return _handler(container, event, func)
        if hasattr(func, '__self__'):
            handler.__self__ = func.__self__
        return handler
    return decorator
177445
function HttpTool(){
        this.settings = {};
        this.urlObject = {};
        this.dataToWrite = '';
        // ********** Helper Functions/Members **********
        
        var validMethods = ['GET', 'PUT', 'POST', 'DELETE', 'PATCH'];
        
        /**
        * Make sure that settings has at least property of url and method.
        * @return {boolean} whether settings is valid.
        */ 
        this.isSettingValid = function(settings){
            if (_.isEmpty(settings)) {
                return false;
            }
            if ( ! (settings.hasOwnProperty('url') && settings.hasOwnProperty('method'))) {
                return false;
            }
            if (_.isEmpty(settings.url) || _.isEmpty(settings.method)) {
                return false;
            }
            if (_.indexOf(validMethods, settings.method) === -1) {
                return false;    
            }

            return true;
        };

        /**
        * Parse and convert setting into a urlObject that suitable for 
        * http/https module in NodeJs.
        * @return {object} - the object that suitable for Node http/https module.
        */
        this.setupUrlOptions = function(settings) {
                
            var urlTool = require('url');
            var urlObject = {};

            // Parse the string into url options
            if (typeof (settings.url) === 'string') {
                urlObject = urlTool.parse(settings.url);
            }
            else {
                urlObject = settings.url;
            }
            // set the REST options
            urlObject.method = settings.method;
        
            // set up the REST headers
            if (! _.isEmpty(settings.headers)){
                urlObject.headers = settings.headers;
            }
            else {
                urlObject.headers = {};
            }
            
            urlObject.headers['Content-Length'] = 0;
            if (settings.hasOwnProperty('data')){
                switch (typeof settings.data) {
                    case 'object':
                        this.dataToWrite = JSON.stringify(settings.data);
                        urlObject.headers['Content-Type'] = 'application/json';
                        break;
                    case 'string':
                        this.dataToWrite = settings.data;
                        break;
                    default:
                        throw new TypeError("Data field can only be object or string," + 
                                            " but got " + (typeof settings.data));
                                        }
                urlObject.headers['Content-Length'] = Buffer.byteLength(this.dataToWrite);
            }
            
            if (! _.isEmpty(settings.credential)){
                if (!_.isEmpty(settings.credential.password) &&
                    _.isEmpty(settings.credential.username)) {
                    throw new Error('Please provide username and password '+
                                    'for basic authentication.');
                }
                else {
                    urlObject.auth = settings.credential.username +':'+
                    settings.credential.password;
                }
            }
            
            // set the protolcol paramter
            if (urlObject.protocol.substr(-1) !== ':') {
                urlObject.protocol = urlObject.protocol + ':';
            }

            urlObject.rejectUnauthorized = settings.verifySSL || false;
            urlObject.recvTimeoutMs = settings.recvTimeoutMs;

            return urlObject;
        };
    }
753298
function HttpConnection(options) {
    options = options ?
        ({
            protocol: (options.protocol || 'http:'),
            host: (options.host || 'localhost'),
            port: (options.port || '80'),
            path: httpPath,
            withCredentials: false
        }) :
        ({
            path: 'http://localhost:80' + httpPath
        });
    this.options = util._extend({
        localAddress: process.env.LOCAL_ADDRESS
    }, options);
    this._config = JSON.stringify(this.options);
    if (logger.isDebugEnabled()) {
        logger.debug('created with %s', this._config);
    }
}
367059
public HttpFileService build() {
        return new HttpFileService(new HttpFileServiceConfig(
                vfs, clock, maxCacheEntries, maxCacheEntrySizeBytes,
                serveCompressedFiles, autoIndex, headers()));
    }
869217
function httpClient(baseUrl, globalTrackingId) {
  var self = object.create(httpClient.prototype);

  self.baseUrl = baseUrl;
  self.globalTrackingId = globalTrackingId;

  return self;
}
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
993452
function init(domainManager) {
    _domainManager = domainManager;

    if (!domainManager.hasDomain("staticServer")) {
        domainManager.registerDomain("staticServer", {major: 0, minor: 1});
    }
    _domainManager.registerCommand(
        "staticServer",
        "_setRequestFilterTimeout",
        _cmdSetRequestFilterTimeout,
        false,
        "Unit tests only. Set timeout value for filtered requests.",
        [{
            name: "timeout",
            type: "number",
            description: "Duration to wait before passing a filtered request to the static file server."
        }],
        []
    );
    _domainManager.registerCommand(
        "staticServer",
        "getServer",
        _cmdGetServer,
        true,
        "Starts or returns an existing server for the given path.",
        [
            {
                name: "path",
                type: "string",
                description: "Absolute filesystem path for root of server."
            },
            {
                name: "port",
                type: "number",
                description: "Port number to use for HTTP server.  Pass zero to assign a random port."
            }
        ],
        [{
            name: "address",
            type: "{address: string, family: string, port: number}",
            description: "hostname (stored in 'address' parameter), port, and socket type (stored in 'family' parameter) for the server. Currently, 'family' will always be 'IPv4'."
        }]
    );
    _domainManager.registerCommand(
        "staticServer",
        "closeServer",
        _cmdCloseServer,
        false,
        "Closes the server for the given path.",
        [{
            name: "path",
            type: "string",
            description: "absolute filesystem path for root of server"
        }],
        [{
            name: "result",
            type: "boolean",
            description: "indicates whether a server was found for the specific path then closed"
        }]
    );
    _domainManager.registerCommand(
        "staticServer",
        "setRequestFilterPaths",
        _cmdSetRequestFilterPaths,
        false,
        "Defines a set of paths from a server's root path to watch and fire 'requestFilter' events for.",
        [
            {
                name: "root",
                type: "string",
                description: "absolute filesystem path for root of server"
            },
            {
                name: "paths",
                type: "Array",
                description: "path to notify"
            }
        ],
        []
    );
    _domainManager.registerCommand(
        "staticServer",
        "writeFilteredResponse",
        _cmdWriteFilteredResponse,
        false,
        "Overrides the server response from static middleware with the provided response data. This should be called only in response to a filtered request.",
        [
            {
                name: "root",
                type: "string",
                description: "absolute filesystem path for root of server"
            },
            {
                name: "path",
                type: "string",
                description: "path to rewrite"
            },
            {
                name: "resData",
                type: "{body: string, headers: Array}",
                description: "TODO"
            }
        ],
        []
    );
    _domainManager.registerEvent(
        "staticServer",
        "requestFilter",
        [{
            name: "location",
            type: "{hostname: string, pathname: string, port: number, root: string: id: number}",
            description: "request path"
        }]
    );
}
1304437
def StaticServe(base_path='/views/static/'):
    
    def get_file(path=RAW_INVOCATION_ARGS):
        fullpath = get_config('project_path') + os.path.join(base_path, path)
        try:
            mime, encoding = mimetypes.guess_type(fullpath)
            return open(fullpath, 'rb'), mime or 'application/octet-stream'
        except IOError:
            raise DataNotFound("File does not exist")

    class StaticServe(Program):
        controllers = ['http-get']
        model = [get_file]
        view = FileView()

    return StaticServe()
1132416
def get_handler(self, *args, **options):
        '''
        
        '''
        handler = super().get_handler(*args, **options)
        use_static_handler = options['use_static_handler']
        insecure_serving = options['insecure_serving']
        if use_static_handler and (settings.DEBUG or insecure_serving):
            return CRAStaticFilesHandler(handler)
        return handler
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;
}
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;
    }
1208684
function createHttpsServer(options, requestHandler, keys) {
  net
    .createServer(function(socket){
      socket.once('data', function(buffer){
        // Pause the socket
        socket.pause();

        // Determine if this is an HTTP(s) request
        var byte = buffer[0];
        var proxy;

        if (byte === 22)
          proxy = server.https;
        else if (32 < byte && byte < 127)
          proxy = server.http;

        if (proxy)
        {
          // Push the buffer back onto the front of the data stream
          socket.unshift(buffer);

          // Emit the socket to the HTTP(s) server
          proxy.emit('connection', socket);
        }

        // Resume the socket data stream
        socket.resume();
      });
    })
    .on('error', function(error){
      onError(error, options);
    })
    .listen(options.port, function(){
      onListen(this, options);
    });

  var server = {
    http: http.createServer(requestHandler),
    https: https.createServer(keys, requestHandler)
  };

  return server;
}
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
  }
409443
function () {
    // Determine https vs. http
    this.server = this.ssl ?
        https.createServer(this.ssl) :
        http.createServer();

    // Bind to the request
    this.server.on('request', this.handle.bind(this));
  }