1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
//! An example to show how to accept `multipart/form-data` uploads using the
//! [`Multipart`] extractor.
//!
//! [`HttpServer`]: crate::http::server::HttpServer
//! [`Multipart`]: crate::http::service::web::extract::multipart::Multipart
//!
//! This example will create a server that listens on `127.0.0.1:62028`.
//!
//! # Run the example
//!
//! ```sh
//! RUST_LOG=trace cargo run --example http_multipart --features=http-full
//! ```
//!
//! # Expected output
//!
//! The server starts and listens on `:62028`. Submit a multipart upload with
//! `curl`:
//!
//! ```sh
//! echo "hello rama" > /tmp/rama-upload.txt
//! curl -v -X POST http://127.0.0.1:62028/upload \
//! -F "username=glen" \
//! -F "attachment=@/tmp/rama-upload.txt;type=text/plain"
//! ```
//!
//! You should see a `200 OK` response containing a summary of the parts the
//! server received.
//!
//! Or open the page in a browser:
//!
//! ```sh
//! open http://127.0.0.1:62028
//! ```
//!
//! and use the upload form.
#![expect(
clippy::expect_used,
reason = "example: panic-on-error is the standard pattern for demos"
)]
use rama::{
Layer,
http::{
Response,
layer::trace::TraceLayer,
matcher::HttpMatcher,
server::HttpServer,
service::web::{
WebService,
extract::multipart::{Multipart, MultipartRejection},
response::{Html, IntoResponse},
},
},
rt::Executor,
telemetry::tracing::{
self,
level_filters::LevelFilter,
subscriber::{EnvFilter, fmt, layer::SubscriberExt, util::SubscriberInitExt},
},
};
use std::time::Duration;
#[tokio::main]
async fn main() {
tracing::subscriber::registry()
.with(fmt::layer())
.with(
EnvFilter::builder()
.with_default_directive(LevelFilter::DEBUG.into())
.from_env_lossy(),
)
.init();
let graceful = rama::graceful::Shutdown::default();
graceful.spawn_task_fn(async move |guard| {
let exec = Executor::graceful(guard);
HttpServer::auto(exec)
.listen(
"127.0.0.1:62028",
TraceLayer::new_for_http().layer(
WebService::default()
.with_get(
"/",
Html(
r##"<html>
<body>
<h1>Upload</h1>
<form action="/upload" method="post" enctype="multipart/form-data">
<label>Username: <input type="text" name="username"></label><br>
<label>File: <input type="file" name="attachment"></label><br>
<button type="submit">Send</button>
</form>
</body>
</html>"##,
),
)
.with_matcher(
HttpMatcher::method_post().and_path("/upload"),
handle_upload,
),
),
)
.await
.expect("failed to run service");
});
graceful
.shutdown_with_limit(Duration::from_secs(30))
.await
.expect("graceful shutdown");
}
async fn handle_upload(mut multipart: Multipart) -> Result<Response, MultipartRejection> {
let mut summary = String::new();
while let Some(field) = multipart.next_field().await? {
let name = field.name().unwrap_or("<unnamed>").to_owned();
let file_name = field.file_name().map(str::to_owned);
// `as_ref` keeps any parameters (e.g. `text/plain; charset=utf-8`);
// `essence_str` would drop them.
let content_type = field.content_type().map(|m| m.as_ref().to_owned());
let bytes = field.bytes().await?;
tracing::info!(
field.name = %name,
field.file_name = ?file_name,
field.content_type = ?content_type,
field.size = bytes.len(),
"received multipart field",
);
summary.push_str(&format!(
"field={name} file_name={file_name:?} content_type={content_type:?} size={}\n",
bytes.len()
));
}
Ok(summary.into_response())
}