ipkn / crow

Crow is very fast and easy to use C++ micro web framework (inspired by Python Flask)
BSD 3-Clause "New" or "Revised" License
7.47k stars 888 forks source link

Fetch non-int (string) url resource-id #299

Closed parthasarathyprsd closed 6 years ago

parthasarathyprsd commented 6 years ago

How to get a non-int resource-id. I cannot add a route CROW_ROUTE(app, "/uid/<std::string>") or CROW_ROUTE(app, "/uid/<char*>") as it ( correctly ) fails to compile. The examples donot have such a case. I have tried

int main() {
    crow::SimpleApp app;
    CROW_ROUTE(app, "/uid/*").methods("GET"_method)
    ([](const crow::request& req){
        return "hello";
        });

    CROW_ROUTE(app, "/uid/<int>").methods("GET"_method)
    ([](const crow::request& req, int id){
        return std::to_string(id);
        });
    app.port(8888).run();
}

But neither of them ( though correctly ) intercept GET /uid/uid_123 HTTP/1.1 ( with resource being a string "uid_123" )

For below python code, I want to acheive it in c++ crow library

from flask import Flask
app = Flask(__name__)
@app.route("/uid/<path:path>")
def hello1(path):
    print ("it is path is ", path)
    return "user id is -" + path

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8888)

Is there any workaround for the above?

jjhoo commented 6 years ago

I have not tested these, but <int> <uint> <float> <double> <str> <string> <path> might be the ones that are recognized.

https://github.com/ipkn/crow/blob/master/include/crow/routing.h#L784

erow commented 6 years ago

The map of tag to type in utillity.h .

template <int N>
        struct single_tag_to_type
        {
        };

        template <>
        struct single_tag_to_type<1>
        {
            using type = int64_t;
        };

        template <>
        struct single_tag_to_type<2>
        {
            using type = uint64_t;
        };

        template <>
        struct single_tag_to_type<3>
        {
            using type = double;
        };

        template <>
        struct single_tag_to_type<4>
        {
            using type = std::string;
        };

        template <>
        struct single_tag_to_type<5>
        {
            using type = std::string;
        };

and type value

enum class ParamType
    {
        INT,
        UINT,
        DOUBLE,
        STRING,
        PATH,

        MAX
    };

So you can do like this:

CROW_ROUTE(app,"/a/<path>")
            ([](std::string path){
                return path;
            });
parthasarathyprsd commented 6 years ago

yes, that worked, thx alot