-
Notifications
You must be signed in to change notification settings - Fork 125
Description
The problem
I was looking for a way to change the status code of my response and it has been hard to find to me, I based on the next example to create a CORS middleware, but the response status code was always 200 code, instead of 401 (unauthorized), so I had to change the status code manually, but I don't find any way to change it properly.
gotham/examples/middleware/introduction/src/main.rs
Lines 75 to 92 in 84c7f08
let f = result.and_then(move |(state, mut response)| { | |
{ | |
let headers = response.headers_mut(); | |
let data = ExampleMiddlewareData::borrow_from(&state); | |
// All our middleware does is add a header to the Response generated by our handler. | |
headers.insert( | |
"X-User-Agent", | |
format!( | |
"Supplied: {}, Supported: {}", | |
data.user_agent, data.supported | |
) | |
.parse() | |
.unwrap(), | |
); | |
}; | |
future::ok((state, response)) | |
}); |
I also tried to base on this documentation to change the status code, but that doesn't work with my problem, since this example instead of modifying an existing response is creating a new empty response.
gotham/examples/middleware/introduction_await/src/main.rs
Lines 100 to 112 in 84c7f08
pub fn middleware_reliant_handler(mut state: State) -> (State, Response<Body>) { | |
{ | |
let data = ExampleMiddlewareData::borrow_mut_from(&mut state); | |
// Mark any kind of web client as supported. A trival example but it highlights the | |
// interaction that is possible between Middleware and Handlers via state. | |
data.supported = true; | |
}; | |
// Finally we create a basic Response to complete our handling of the Request. | |
let res = create_empty_response(&state, StatusCode::OK); | |
(state, res) | |
} |
Then I noticed the status_mut
function in the response struct, but it doesn't have any documentation about how to use it. So I couldn't use it anyway. Later I checked and found this block of code in this GitHub repository and I based on it to change the response status code, and that worked properly. But I think it could be included in the examples, for example, the first one that I mentioned could include this part about how to change the status code
gotham/gotham_derive/src/extenders.rs
Lines 15 to 19 in 7251955
fn extend(state: &mut ::gotham::state::State, res: &mut ::gotham::hyper::Response<Self::ResBody>) { | |
res.headers_mut().insert(::gotham::helpers::http::header::X_REQUEST_ID, | |
::gotham::state::request_id(state).parse().unwrap()); | |
*res.status_mut() = ::gotham::hyper::StatusCode::BAD_REQUEST; | |
} |
The request
I suggest to add examples about how to use status_mut()
to the middleware examples or to another example where it was visible so beginners can easily change the status_mut
of a response