Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Log before compressing #1656

Open
TimaFrolov opened this issue Aug 31, 2023 · 2 comments
Open

Log before compressing #1656

TimaFrolov opened this issue Aug 31, 2023 · 2 comments

Comments

@TimaFrolov
Copy link

Right now logger gets called after response body has been compressed, which means it is logged in a non-human-readable format
Wouldn't it be better to log request before encoding the response body?

@yhirose
Copy link
Owner

yhirose commented Sep 1, 2023

@TimaFrolov thanks for the suggestion. It would be nice to do it, there are some difficulties. The easiest way to do this is to keep the original uncompressed text as well, but I don't prefer this approach since it may cause much more memory usage. Another way we may think is to log a response object right before compressing text. But it can't be done since the server will add more HTTP header values to the response object afterward...

I don't have a solution for it at this point, but I'll leave it as 'enhancement'.

@cplussharp
Copy link

I use this workaround in my log method:

#if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT)
    std::string encoding = res.get_header_value("Content-Encoding");
    std::unique_ptr<httplib::detail::decompressor> decompressor;
#ifdef CPPHTTPLIB_ZLIB_SUPPORT
    if (encoding == "gzip") {
        decompressor = httplib::detail::make_unique<httplib::detail::gzip_decompressor>();
    }
#endif
#ifdef CPPHTTPLIB_BROTLI_SUPPORT
    if (!decompressor && encoding == "br") {
        decompressor = httplib::detail::make_unique<httplib::detail::brotli_decompressor>();
    }
#endif
    if (decompressor && decompressor->is_valid()) {
        std::string decompressed;
        decompressor->decompress(res.body.c_str(), res.body.length(), [&](const char* buf, size_t n) {
            decompressed.append(buf);
            return true;
        });
        std::cout << decompressed;
    } else {
        std::cout << res.body;
    }
#else
    // body is always uncompressed
    std::cout << res.body;
#endif

maybe this can be moved into a helper method on the Response. Something like getUncompressedBody() or so.
Btw. is there a way to disable the compression in the server at runtime?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants