Extracts a `key="value"` or `key=value` parameter from a header value such as `form-data; name="file"; filename="clip.wav"`.
| 24 | // Extracts a `key="value"` or `key=value` parameter from a header value such as |
| 25 | // `form-data; name="file"; filename="clip.wav"`. |
| 26 | std::string extract_header_param(const std::string & header_value, const std::string & key) { |
| 27 | const std::string needle = key + "="; |
| 28 | const std::string lowered = lower_ascii(header_value); |
| 29 | size_t pos = 0; |
| 30 | while (true) { |
| 31 | pos = lowered.find(needle, pos); |
| 32 | if (pos == std::string::npos) { |
| 33 | return {}; |
| 34 | } |
| 35 | // Make sure we matched a whole parameter name, not a suffix (e.g. "filename" vs "name"). |
| 36 | if (pos == 0 || header_value[pos - 1] == ' ' || header_value[pos - 1] == ';') { |
| 37 | break; |
| 38 | } |
| 39 | pos += needle.size(); |
| 40 | } |
| 41 | size_t start = pos + needle.size(); |
| 42 | if (start < header_value.size() && header_value[start] == '"') { |
| 43 | const size_t end = header_value.find('"', start + 1); |
| 44 | if (end == std::string::npos) { |
| 45 | return header_value.substr(start + 1); |
| 46 | } |
| 47 | return header_value.substr(start + 1, end - start - 1); |
| 48 | } |
| 49 | size_t end = header_value.find(';', start); |
| 50 | if (end == std::string::npos) { |
| 51 | end = header_value.size(); |
| 52 | } |
| 53 | return trim(header_value.substr(start, end - start)); |
| 54 | } |
| 55 | |
| 56 | std::string strip_trailing_newline(std::string value) { |
| 57 | if (value.size() >= 2 && value.compare(value.size() - 2, 2, "\r\n") == 0) { |
no test coverage detected