Function registerHandler

Synopsis

#include <lib/inc/drogon/HttpAppFramework.h>

template <typename FUNCTION>
HttpAppFramework & registerHandler(const std::string &pathPattern, FUNCTION &&function, const std::vector< internal::HttpConstraint > &filtersAndMethods=std::vector< internal::HttpConstraint >{}, const std::string &handlerName="")

Description

Register a handler into the framework.

Parameters:

pathPattern - When the path of a http request matches the pathPattern, the handler indicated by the function parameter is called.

function - indicates any type of callable object with a valid processing interface.

filtersAndMethods - is the same as the third parameter in the above method.

Example:
  app().registerHandler("/hello?username={1}",
                        [](const HttpRequestPtr& req,
                           std::function<void (const HttpResponsePtr&)>
&&callback, const std::string &name)
                           {
                               Json::Value json;
                               json["result"]="ok";
                               json["message"]=std::string("hello,")+name;
                               auto
resp=HttpResponse::newHttpJsonResponse(json); callback(resp);
                           },
                        {Get,"LoginFilter"});
Note
As you can see in the above example, this method supports parameters mapping.

Mentioned in

Source

Lines 413-449 in lib/inc/drogon/HttpAppFramework.h.

template <typename FUNCTION>
HttpAppFramework &registerHandler(
    const std::string &pathPattern,
    FUNCTION &&function,
    const std::vector<internal::HttpConstraint> &filtersAndMethods =
        std::vector<internal::HttpConstraint>{},
    const std::string &handlerName = "")
{
    LOG_TRACE << "pathPattern:" << pathPattern;
    internal::HttpBinderBasePtr binder;
    binder = std::make_shared<internal::HttpBinder<FUNCTION>>(
        std::forward<FUNCTION>(function));
    std::vector<HttpMethod> validMethods;
    std::vector<std::string> filters;
    for (auto const &filterOrMethod : filtersAndMethods)
    {
        if (filterOrMethod.type() == internal::ConstraintType::HttpFilter)
        {
            filters.push_back(filterOrMethod.getFilterName());
        }
        else if (filterOrMethod.type() ==
                 internal::ConstraintType::HttpMethod)
        {
            validMethods.push_back(filterOrMethod.getHttpMethod());
        }
        else
        {
            LOG_ERROR << "Invalid controller constraint type";
            exit(1);
        }
    }
    registerHttpController(
        pathPattern, binder, validMethods, filters, handlerName);
    return *this;
}





Add Discussion as Guest

Log in