Creates new middleware using provided options
967063
function create (options) {
  const {
    xForwardedProto,
    redirectPort,
    redirectHost,
    statusCode,
    redirectUnknown,
    redirect,
    exclude
  } = Object.assign({}, defaults, options)
  const _port = redirectPort === 443 ? '' : (': ' + redirectPort)

  return function redirectSSL (req, res, next) {
    if (redirect && !isExcluded(req.url, exclude)) {
      const _isHttps = isHTTPS(req, xForwardedProto)
      const shouldRedirect = _isHttps === false || (redirectUnknown && _isHttps === null)
      if (shouldRedirect) {
        const ـredirectURL = 'https://' + (redirectHost || req.headers.host) + _port + req.url
        res.writeHead(statusCode, { Location: ـredirectURL })
        return res.end()
      }
    }

    return next()
  }
}
123656
function Resource (options) {
    EventEmitter.call(this, { wildcard: true });

    options = options || {};

    this.method = options.method || 'get';
    this.route = options.route || '';
    this.middleware = [];
    this.properties = options.properties || {};

    return this;
}
1105280
function makeServeMiddleware(/* config */) {
  return function handle(req, resp, next) {
    if (/^\/.*\.css$/.test(req.url)) {
      resp.end("");
    }
    else {
      next();
    }
  };
}
1142602
function promiseMiddleware (request, response, middleware) {
  return new promiseMiddleware.Promise(function (resolve, reject) {
    middleware(request, response, function next (error) {
      return error ? reject(error) : resolve()
    })
  })
}
1055579
async function createApp(middlewareConfig) {
  const app = new Koa()

  const middleware = await setupMiddleware(middlewareConfig, app)

  if (app.env == 'production') {
    app.proxy = true
  }

  return {
    app,
    middleware,
  }
}
261077
public function createHttpClient($baseUri, array $middlewares = [], array $options = [])
    {
        $stack = HandlerStack::create();

        foreach ($middlewares as $middleware) {
            $stack->push($middleware);
        }

        return new Client(array_merge([
            'base_uri' => $baseUri,
            'handler' => $stack,
        ], $options));
    }
1022814
function addRouteFactory(router, method, end) {
  return (pattern, ...middlewares) => {
    if (typeof pattern === 'function') {
      middlewares = [pattern, ...middlewares];
      pattern = '/';
    }

    // create a route with multiple middlewares
    const route = compose(middlewares, { beforeRunMiddleware: (middleware, req, resp) => {
      const len = req.routePath ? req.routePath.length : 0;
      if (req.url.slice(0, len) !== req.routePath) return false;// url changed
      return true;
    } });
    route.method = method;

    const keys = [];
    const re = ptre(pattern, keys, { end, strict: false, sensitive: false });
    route.re = re;// used to test the remain of req.url
    route.keys = keys;

    router.routes.push(route);

    return router;
  };
}
94268
function createMiddleware(options) {
  /**
   * Express middleware handling Git API Blob requests
   *
   * Only a small subset will be implemented
   *
   * @param {Request} req Request object
   * @param {Response} res Response object
   * @param {callback} next next middleware in chain
   *
   * @see https://developer.github.com/v3/git/blobs/#get-a-blob
   */
  return (req, res, next) => {
    // GET /repos/:owner/:repo/git/blobs/:file_sha
    const { owner } = req.params;
    const repoName = req.params.repo;
    const sha = req.params.file_sha;
    const host = req.mappedSubDomain ? `localhost:${options.listen[req.protocol].port}` : req.headers.host;

    const repPath = resolveRepositoryPath(options, owner, repoName);

    if (sha.match(/[0-9a-f]/g).length !== 40) {
      // invalid sha format
      res.status(422).json({
        message: 'The sha parameter must be exactly 40 characters and contain only [0-9a-f].',
        documentation_url: 'https://developer.github.com/v3/git/blobs/#get-a-blob',
      });
      return;
    }
    getObject(repPath, sha)
      .then(({ object: content }) => {
        res.json({
          sha,
          size: content.length,
          url: `${req.protocol}://${host}${req.path}`,
          content: `${content.toString('base64')}\n`,
          encoding: 'base64',
        });
      })
      .catch((err) => {
        // TODO: use generic errors
        if (err.code === 'ReadObjectFail') {
          options.logger.debug(`[blobHandler] resource not found: ${err.message}`);
          res.status(404).json({
            message: 'Not Found',
            documentation_url: 'https://developer.github.com/v3/git/blobs/#get-a-blob',
          });
        } else {
          options.logger.debug(`[blobHandler] code: ${err.code} message: ${err.message} stack: ${err.stack}`);
          next(err);
        }
      });
  };
}
743366
function Middleware(name) {
    if (!(this instanceof Middleware)) return new Middleware(name);
    this.name = name || '';

    Object.defineProperty(this, '_', {
        enumerable: false,
        configurable: false,
        value: {
            length: 0,
            ordered: null,
            weights: new Map()
        }
    });

    /**
     * Returns the length of the middleware.
     * @type {number}
     */
    Object.defineProperty(this, 'length', {
        get: () => this._.length
    });
}
254443
def middleware(self, func):
        """"""
        self.middlewares.append(web.middleware(to_coroutine(func)))
648735
function create(options) {
  return knex(extend({
    client: "pg",
    debug: debug(),
    connection: connection(),
    pool: pool()
  }, options));
}
87493
function createMiddleware(options) {
  /**
   * Express middleware handling Git API Blob requests
   *
   * Only a small subset will be implemented
   *
   * @param {Request} req Request object
   * @param {Response} res Response object
   * @param {callback} next next middleware in chain
   *
   * @see https://developer.github.com/v3/git/trees/#get-a-tree-recursively
   */
  return (req, res, next) => {
    // GET /repos/:owner/:repo/git/trees/:ref_or_sha?recursive
    const { owner } = req.params;
    const repoName = req.params.repo;
    const refOrSha = req.params.ref_or_sha;
    const recursive = typeof req.query.recursive !== 'undefined' && req.query.recursive !== '';
    const host = req.mappedSubDomain ? `localhost:${options.listen[req.protocol].port}` : req.headers.host;

    const repPath = resolveRepositoryPath(options, owner, repoName);

    async function dirEntryToJson({
      oid: sha, type, path, mode,
    }) {
      return {
        path,
        mode,
        type,
        sha,
        url: `${req.protocol}://${host}/api/repos/${owner}/${repoName}/git/trees/${sha}`,
      };
    }

    async function fileEntryToJson({
      oid: sha, type, path, mode,
    }) {
      const { object: content } = await getObject(repPath, sha);

      return {
        path,
        mode,
        type,
        sha,
        size: content.length,
        url: `${req.protocol}://${host}/api/repos/${owner}/${repoName}/git/blobs/${sha}`,
      };
    }

    async function collectTreeEntries(tree, result, treePath, deep) {
      const entries = tree.entries.map(({
        oid, type, mode, path,
      }) => {
        return {
          oid, type, mode, path: joinPaths(treePath, path),
        };
      });
      result.push(...entries);
      if (deep) {
        const treeEntries = entries.filter(entry => entry.type === 'tree');
        for (let i = 0; i < treeEntries.length; i += 1) {
          const { oid, path } = treeEntries[i];
          /* eslint-disable no-await-in-loop */
          const { object: subTree } = await getObject(repPath, oid);
          await collectTreeEntries(subTree, result, path, deep);
        }
      }
      return result;
    }

    async function treeEntriesToJson(tree, deep) {
      const result = [];
      await collectTreeEntries(tree, result, '', deep);
      return Promise.all(result.map(async (entry) => {
        /* eslint arrow-body-style: "off" */
        return entry.type === 'blob'
          ? fileEntryToJson(entry) : dirEntryToJson(entry);
      }));
    }

    resolveTree(repPath, refOrSha)
      .then(async ({ oid: sha, object: tree }) => {
        res.json({
          sha,
          url: `${req.protocol}://${host}/api/repos/${owner}/${repoName}/git/trees/${sha}`,
          tree: await treeEntriesToJson(tree, recursive),
          truncated: false,
        });
      })
      .catch((err) => {
        // TODO: use generic errors
        if (err.code === 'ReadObjectFail' || err.code === 'ResolveRefError') {
          options.logger.debug(`[treeHandler] resource not found: ${err.message}`);
          res.status(404).json({
            message: 'Not Found',
            documentation_url: 'https://developer.github.com/v3/git/trees/#get-a-tree',
          });
        } else {
          options.logger.debug(`[treeHandler] code: ${err.code} message: ${err.message} stack: ${err.stack}`);
          next(err);
        }
      });
  };
}
1366148
function createThingme (opts) {
    opts = defaultOptions(opts);
    validateThings(opts.things);
    return createWebservice(opts);
}
1205713
function compose(middleware) {
	const args = [].slice.call(arguments, 1);
  return function *(next) {
    if (!next) next = noop();

    var i = middleware.length;

    while (i--) {
      next = middleware[i].apply(this, args.concat(next));
    }

    return yield *next;
  }
}
85437
def create(callback=None, path=None, method=Method.POST, resource=None, tags=None, summary="Create a new resource",
           middleware=None):
    # type: (Callable, Path, Methods, Resource, Tags, str, List[Any]) -> Operation
    
    def inner(c):
        op = ResourceOperation(c, path or NoPath, method, resource, tags, summary, middleware)
        op.responses.add(Response(HTTPStatus.CREATED, "{name} has been created"))
        op.responses.add(Response(HTTPStatus.BAD_REQUEST, "Validation failed.", Error))
        return op
    return inner(callback) if callback else inner
1016017
function Router(options) {
  options = options || {};
  var self = this;
  this.map = {};
  this.params = {};
  this._params = [];
  this.caseSensitive = options.caseSensitive;
  this.strict = options.strict;
  this.middleware = function router(req, res, next){
    self._dispatch(req, res, next);
  };
}
1108875
def new(options = { only: [], except: [:id, :created_at, :updated_at], required: [] })
      @thing_model = thing
      @thing = @thing_model.new
      @attrs = CEO::Iterator.filter(@thing.attributes.keys, options)
      @route_name ||= @controller_name ||= controller_name
      @index_route = send(:"admin_#{@route_name}_path")

      render 'admin/new'
    end