drogonframework / drogon

Drogon: A C++14/17/20 based HTTP web application framework running on Linux/macOS/Unix/Windows
MIT License
11.45k stars 1.1k forks source link

Add Global Path Prefix Setter #1340

Closed Dup4 closed 4 months ago

Dup4 commented 2 years ago

Notice If you need support or clarification regarding the usage of Drogon in your project, visit the official Drogon support channel at gitter

Please create a new issue only if you think you have found a bug or if have a feature request/enhancement.

Is your feature request related to a problem? Please describe. A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

Describe the solution you'd like A clear and concise description of what you want to happen.

I've checked all the interfaces in the HttpAppFramework and there doesn't seem to be an interface for setting the global path prefix.

This becomes important when we need to deploy an application to a sub-path of a domain, and we need to change this part of the prefix through the configuration.

Describe alternatives you've considered A clear and concise description of any alternative solutions or features you've considered.

Additional context Add any other context or screenshots about the feature request here.

like NestJS:

https://docs.nestjs.com/faq/global-prefix

Dup4 commented 2 years ago

Temporarily, I can add an advice to achieve this.

For instance:

auto add_global_path_prefix_advice = [this](const HttpRequestPtr& req) {
    auto path_prefix = config_->http_global_path_prefix_;
    if (path_prefix.empty()) {
        return;
    }

    const auto& current_path = req->getPath();
    if (current_path.length() < path_prefix.length()) {
        return;
    }

    auto head_path = current_path.substr(0, path_prefix.length());
    if (head_path != path_prefix) {
        return;
    }

    auto after_path = current_path.substr(path_prefix.length());
    req->setPath(after_path);
};

app().registerPreRoutingAdvice(add_global_path_prefix_advice);
hwc0919 commented 2 years ago

Adding a pre-routing advice is actually a good solution. You can make it a plugin, in that case you can easily enable/disable the feature and change configs.