Create an ad-hoc web server where to receive the webhook notifications

@param {Object} webhook
@param {string} [webhook.hostname='0.0.0.0']
@param {Number} [webhook.port=0]

@return {http.Server}
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
}
477422
function onlineMessage() {
			_this.showLogo();

			var httpPort = _this.config.http.port;
			Logger.info('Listening HTTP on port ' + httpPort);

			if(_this.config.https.enabled) {
				var httpsPort = _this.config.https.port;
				Logger.info('Listening HTTPS on port ' + httpsPort);
			}
		}
319275
def webhooks
      webhooks = JSON.parse(API::Server.webhooks(@bot.token, @id))
      webhooks.map { |webhook| Webhook.new(webhook, @bot) }
    end
840235
function Webhook(flint) {

  return function(req, res) {

    // emit webhook event (mostly here for debugging...)
    flint.emit('webhook', req[flint.options.webhookRequestJSONLocation]);

    // if "res" is passed to function...
    if(typeof res !== 'undefined') {
      res.status(200);
      res.send('OK');
    }

    // get webhook header to determine if security is enabled
    var sig = req.headers['x-spark-signature'] || false;
    var body = req[flint.options.webhookRequestJSONLocation] || false;

    if(!body){
      return when(true);
    }

    if(flint.spark.webhookSecret && !(sig && flint.spark.webhookAuth(sig, body))) {
      // invalid signature, ignore processing webhook
      flint.debug('invalid signature in webhook callback, ignoring...');
      return when(true);
    }

    if(!flint.active) {
      return when(true);
    }

    // get webhook content
    var id = body.id;
    var name = body.name;
    var resource = body.resource;
    var event = body.event;
    var data = body.data;
    var roomId = body.filter ? body.filter.split('=')[1] : null;

    // validate webbhook is bound for this instance of flint
    if(name !== flint.webhook.name || (typeof flint.webhook.roomId !== 'undefined' && flint.webhook.roomId !== roomId)) {
      return when(true);
    }

    if(typeof resource !== 'string' || typeof event !== 'string') {
      flint.debug('Can not determine webhook type');
      return when(true);
    }

    // rooms
    if(resource === 'rooms') {
      return flint.getRoom(data.id)
        .then(room => {

          // set room title for rooms with none set (api bug?)
          if(room.title == '') {
            room.title = 'Default title';
          }

          // room created
          if(event === 'created') {
            flint.emit('roomCreated', room, flint.id);

            return flint.onRoomCreated(room)
              .catch(err => {
                flint.debug(err.stack);
                return when(true);
              });
          }

          // room updated
          if(event === 'updated') {
            flint.emit('roomUpdated', room, flint.id);

            return flint.onRoomUpdated(room)
              .catch(err => {
                flint.debug(err.stack);
                return when(true);
              });
          }

        })
        .catch(() => {
          return when(true);
        });
    }

    // memberships
    if(resource === 'memberships') {

      // membership created
      if(event === 'created') {
        return flint.getMembership(data.id)
          .then(membership => {
            flint.emit('membershipCreated', membership, flint.id);

            return flint.onMembershipCreated(membership)
              .catch(err => {
                flint.debug(err.stack);
                return when(true);
              });
          })
          .catch(() => {
            return when(true);
          });
      }

      // membership updated
      if(event === 'updated') {
        return flint.getMembership(data.id)
          .then(membership => {
            flint.emit('membershipUpdated', membership, flint.id);

            return flint.onMembershipUpdated(membership)
              .catch(err => {
                flint.debug(err.stack);
                return when(true);
              });
          })
          .catch(() => {
            return when(true);
          });
      }

      // membership deleted
      if(event === 'deleted') {
        flint.emit('membershipDeleted', data, flint.id);

        return flint.onMembershipDeleted(data)
          .catch(err => {
            flint.debug(err.stack);
            return when(true);
          });
      }

    }

    // messages
    if(resource === 'messages') {
      // membership created
      if(event === 'created') {
        return flint.getMessage(data.id)
          .then(message => {
            flint.emit('messageCreated', message, flint.id);

            return flint.onMessageCreated(message)
              .catch(err => {
                flint.debug(err.stack);
                return when(true);
              });
          })
          .catch(() => {
            return when(true);
          });
      }

      // message deleted
      if(event === 'deleted') {
        flint.emit('messageDeleted', data, flint.id);
        return when(true);
      }
    }
  }; // end of return function...
}
166377
def perform_webhook
      http_request.body  = {'text'  => params[:text]}.to_json.to_s
      http_request.query = {'token' => params[:token]}
      HTTPI.post(http_request)
    end
150151
function WebKitInspector(port, host, href, callback) {
    if (!(this instanceof WebKitInspector)) {
        return new WebKitInspector(port, host, href, callback);
    }

    this.closed = false;
    this._callbacks = {};
    this._id = 0;

    this.debug = false;

    // Add library domains
    var domains = Object.keys(library);
    for (var i = 0, l = domains.length; i < l; i++) {
        this[ domains[i] ] = new library[ domains[i] ](this);
    }

    // Setup host and port parameters
    if (typeof port !== 'number') {
        throw new Error('A port number must be speficed');
    }
    if (typeof host !== 'string') {
        throw new Error('A host name must be speficed');
    }
    if (typeof href !== 'string') {
        throw new Error('A page url must be speficed');
    }

    // Add callback to connect event
    if (callback) this.once('connect', callback);

    // Try to connect to WebKit Server
    this._tryConnect(port, host, href, 0, 2000);
}
260427
function XMLHttpRequest() {
    var scope = ctorEvent();
    goog.base(this, descriptor);

    /**
     * Real XHR.
     * @type {!XMLHttpRequest}
     * @private
     */
    this.handle_ = new originalXhr();

    /**
     * Event type trackers, by name.
     * @type {!Object.<Function>}
     * @private
     */
    this.trackers_ = {};

    /**
     * Properties, accumulated during setup before send().
     * @type {!Object}
     * @private
     */
    this.props_ = {
      'method': null,
      'url': null,
      'async': true,
      'user': null,
      'headers': {},
      'timeout': 0,
      'withCredentials': false,
      'overrideMimeType': null,
      'responseType': ''
    };

    /**
     * Active flow, if any.
     * @type {wtf.trace.Flow}
     * @private
     */
    this.flow_ = null;

    // Always hook onreadystatechange.
    // By doing it here we get first access to the event.
    var self = this;
    var handle = this.handle_;
    var props = this.props_;
    this.handle_.addEventListener('readystatechange', function(e) {
      var flow = self.flow_;
      if (!flow) {
        return;
      }

      var value = undefined;
      if (handle.readyState == 2) {
        var headers = {};
        var allHeaders = handle.getAllResponseHeaders().split('\r\n');
        for (var n = 0; n < allHeaders.length; n++) {
          if (allHeaders[n].length) {
            var parts = allHeaders[n].split(':');
            headers[parts[0]] = parts[1].substr(1);
          }
        }
        value = {
          'status': this.status,
          'statusText': this.statusText,
          'headers': headers
        };
        // TODO(benvanik): appendFlowData
      }
      // TODO(benvanik): response size/type/etc

      // Extend flow, terminate if required.
      if (handle.readyState < 4) {
        wtf.trace.Flow.extend(flow, 'readyState: ' + handle.readyState, value);
      } else {
        wtf.trace.Flow.terminate(flow, 'readyState: ' + handle.readyState);
      }
    }, false);

    // Add data to interesting events.
    this.setEventHook('readystatechange', function(e) {
      wtf.trace.appendScopeData('url', props['url']);
      wtf.trace.appendScopeData('readyState', handle['readyState']);
    });
    this.setEventHook('load', function(e) {
      wtf.trace.appendScopeData('url', props['url']);
    });

    wtf.trace.Scope.leave(scope);
  }
1141195
function addHook (hook) {
    /* Accepting a nodeback, promisify it; else, store as it */
    const pHook = (hook.length > 1) ? Promise.promisify(hook) : hook;
    G.hooks.push(pHook);
}
997633
function _websocketPort(ctx, port) {
  const forwarded = ctx.header['x-forwarded-proto'];
  const protocol = forwarded ? forwarded.split(',')[0] : undefined;
  return protocol === 'https' ? 443 : port;
}
157881
function RequestHooks_process(api) {
        var that = this, route = api.parsedUrl.pathname;
        logger.info('RequestHooks.process:', route);
        return new Promise(function (resolve, reject) {
            var hook;
            try {
                hook = that.get(route);
                logger.info('RequestHooks.hook:', hook);
                if (!!hook) {
                    resolve(hook.func(api));
                } else {
                    resolve(false);
                }
            } catch (e) {
                logger.error('RequestHooks.hook:', {
                    hook: hook,
                    e: e
                });
                reject(new error.HttpError(500, {hook: route}, 'Hook error', e));
            }
        });
    }
497441
function Server(config) {
  utils.verbose(config.verbose)

  this._wsStarted = false
  this._wsStopped = false

  this._wsConfig = config
  this._wsServer = new websocket.server()

  this._onRequest = config.onRequest

  this._wsServer.addListener("request", this._onRequest)
  this._wsServer.addListener("connect", onConnect)
}
680208
function SockJS(url, protocols, options) {
  if (!(this instanceof SockJS)) {
    return new SockJS(url, protocols, options);
  }
  if (arguments.length < 1) {
    throw new TypeError("Failed to construct 'SockJS: 1 argument required, but only 0 present");
  }
  EventTarget.call(this);

  this.readyState = SockJS.CONNECTING;
  this.extensions = '';
  this.protocol = '';

  // non-standard extension
  options = options || {};
  if (options.protocols_whitelist) {
    log.warn("'protocols_whitelist' is DEPRECATED. Use 'transports' instead.");
  }
  this._transportsWhitelist = options.transports;
  this._transportOptions = options.transportOptions || {};

  var sessionId = options.sessionId || 8;
  if (typeof sessionId === 'function') {
    this._generateSessionId = sessionId;
  } else if (typeof sessionId === 'number') {
    this._generateSessionId = function() {
      return random.string(sessionId);
    };
  } else {
    throw new TypeError('If sessionId is used in the options, it needs to be a number or a function.');
  }

  this._server = options.server || random.numberString(1000);

  // Step 1 of WS spec - parse and validate the url. Issue #8
  var parsedUrl = new URL(url);
  if (!parsedUrl.host || !parsedUrl.protocol) {
    throw new SyntaxError("The URL '" + url + "' is invalid");
  } else if (parsedUrl.hash) {
    throw new SyntaxError('The URL must not contain a fragment');
  } else if (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') {
    throw new SyntaxError("The URL's scheme must be either 'http:' or 'https:'. '" + parsedUrl.protocol + "' is not allowed.");
  }

  var secure = parsedUrl.protocol === 'https:';
  // Step 2 - don't allow secure origin with an insecure protocol
  if (loc.protocol === 'https:' && !secure) {
    throw new Error('SecurityError: An insecure SockJS connection may not be initiated from a page loaded over HTTPS');
  }

  // Step 3 - check port access - no need here
  // Step 4 - parse protocols argument
  if (!protocols) {
    protocols = [];
  } else if (!Array.isArray(protocols)) {
    protocols = [protocols];
  }

  // Step 5 - check protocols argument
  var sortedProtocols = protocols.sort();
  sortedProtocols.forEach(function(proto, i) {
    if (!proto) {
      throw new SyntaxError("The protocols entry '" + proto + "' is invalid.");
    }
    if (i < (sortedProtocols.length - 1) && proto === sortedProtocols[i + 1]) {
      throw new SyntaxError("The protocols entry '" + proto + "' is duplicated.");
    }
  });

  // Step 6 - convert origin
  var o = urlUtils.getOrigin(loc.href);
  this._origin = o ? o.toLowerCase() : null;

  // remove the trailing slash
  parsedUrl.set('pathname', parsedUrl.pathname.replace(/\/+$/, ''));

  // store the sanitized url
  this.url = parsedUrl.href;

  // Step 7 - start connection in background
  // obtain server info
  // http://sockjs.github.io/sockjs-protocol/sockjs-protocol-0.3.3.html#section-26
  this._urlInfo = {
    nullOrigin: !browser.hasDomain()
  , sameOrigin: urlUtils.isOriginEqual(this.url, loc.href)
  , sameScheme: urlUtils.isSchemeEqual(this.url, loc.href)
  };

  this._ir = new InfoReceiver(this.url, this._urlInfo);
  this._ir.once('finish', this._receiveInfo.bind(this));
}
701537
public WebhookResponseData createWebHook(Webhook webhook) throws UnauthorizedException, GeneralException {
        if (webhook.getTitle() == null) {
            throw new IllegalArgumentException("Title of webhook must be specified.");
        }

        if (webhook.getUrl() == null) {
            throw new IllegalArgumentException("URL of webhook must be specified.");
        }

        String url = String.format("%s%s", VOICE_CALLS_BASE_URL, WEBHOOKS);
        return messageBirdService.sendPayLoad(url, webhook, WebhookResponseData.class);
    }
96421
function createWebservice (opts) {
    var server = new Hapi.Server(opts.host, opts.port, {
        cors: {
            methods: ['GET']
        }
    });
    defineRoutes(server, opts);
    return {
        address: 'http://' + opts.host + ':' + opts.port + '/',
        hapi: server,
        options: opts,
        start: server.start.bind(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;
}
803768
def create_webhook_app(self, path, loop=None):
        
        app = web.Application(loop=loop)
        app.router.add_route("POST", path, self.webhook_handle)
        return app
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);
        }
    });
}