Stiffstream / restinio

Cross-platform, efficient, customizable, and robust asynchronous HTTP(S)/WebSocket server C++ library with the right balance between performance and ease of use
Other
1.15k stars 93 forks source link

How to extract header from request #142

Closed noctera closed 3 years ago

noctera commented 3 years ago

I looked in the docs but didn't find anything about it. How can I extract the header from a incomming request?

I tried it with

router->http_post(
        "/api/createPackage",
        [&](auto req, auto params) {
            const auto header = req->header();

which doesn't give any errors when extracting my specific header parameter with std::string jwt = restinio::cast_to<std::string>(header["jwt"]); it doesn't work no match for ‘operator[]’ (operand types are ‘const restinio::http_request_header_t’ and ‘const char [4]’) I'm pretty sure I am doing something wrong Could someone help me with it please? Thanks in advance :)

eao197 commented 3 years ago

Hi!

Working with header is described here: https://stiffstream.com/en/docs/restinio/0.6/workingwithheader.html

There are several sets of getters for http_request_header_t class. Some of them throw an exception in the case of an error:

auto enc_value = req->header().value_of("Accept-Encoding"); // string_view or an exception.
// or
auto enc_value = req->header().value_of(restinio::http_field::accept_encoding); // string_view or an exception.

Some of them return nullptr if the header is missing:

auto env_value = req->header().try_get_field(restinio::http_field::accept_encoding); // const std::string * that can be null.
if(env_value) {...}

Some of them return the value or the default value:

auto enc_value = req->header().get_field_or(
  restinio::http_field::accept_encoding, "gzip"); // std::string that contains actual value or "gzip"

Some of them return optional:

auto env_value = req->header().opt_value_of(restinio::http_field::accept_encoding); // optional<string_view>.
if(env_value) {...}

There is no operator[] for HTTP-fields container because some fields can be repeated. For enumeration of all values of a field (all occurrences of the field), there is for_each_value_of method.

noctera commented 3 years ago

Thank you :) auto enc_value = req->header().value_of("Jwt"); Did it for me and it is perfectly throwing an exception if this parameter is not available in the header

eao197 commented 3 years ago

Did it for me and it is perfectly throwing an exception if this parameter is not available in the header

Yes, if "Jwt" header is missed then an exception will be thrown.