userver: samples/multipart_service/service.cpp
Loading...
Searching...
No Matches
samples/multipart_service/service.cpp
namespace samples {
class Multipart final : public server::handlers::HttpHandlerBase {
public:
// `kName` is used as the component name in static config
static constexpr std::string_view kName = "handler-multipart-sample";
// Component is valid after construction and is able to accept requests
using HttpHandlerBase::HttpHandlerBase;
std::string HandleRequestThrow(const server::http::HttpRequest& req, server::request::RequestContext&)
const override;
};
std::string Multipart::HandleRequestThrow(const server::http::HttpRequest& req, server::request::RequestContext&)
const {
const auto content_type = http::ContentType(req.GetHeader(http::headers::kContentType));
if (content_type != "multipart/form-data") {
req.GetHttpResponse().SetStatus(server::http::HttpStatus::kBadRequest);
return "Expected 'multipart/form-data' content type";
}
const auto& image = req.GetFormDataArg("profileImage");
static constexpr std::string_view kPngMagicBytes = "\x89PNG\r\n\x1a\n";
if (!utils::text::StartsWith(image.value, kPngMagicBytes)) {
req.GetHttpResponse().SetStatus(server::http::HttpStatus::kBadRequest);
return "Expecting PNG image format";
}
req.GetHttpResponse().SetContentType(http::content_type::kApplicationJson);
const auto& address = req.GetFormDataArg("address");
auto json_addr = formats::json::FromString(address.value);
return fmt::format("city={} image_size={}", json_addr["city"].As<std::string>(), image.value.size());
}
} // namespace samples
int main(int argc, char* argv[]) {
const auto component_list = components::MinimalServerComponentList().Append<samples::Multipart>();
return utils::DaemonMain(argc, argv, component_list);
}