rwf2 / Rocket

A web framework for Rust.
https://rocket.rs
Other
24.61k stars 1.57k forks source link

Add a `#[derive(Responder)]` for enums #590

Closed kestred closed 6 years ago

kestred commented 6 years ago

Feature Request

It is sometimes the case that a request may want to respond with different responses types depending on the details of the request. Sometimes this can be handled with request guards and sometimes this can be handled by co-opting Result's responder behavior, but in a fair amount of cases it'd be convenient to define an enum with variants for all of the Responders that are possible and then have Responder automatically derived for that enum.

Here are a few use examples:

Different content types:

#[derive(Responder)]
enum MyResponse {
    Json(Json<MyObject>),
    Xml(Xml<MyObject>),
}

Different objects:

#[derive(Responder)]
enum MyResponse {
    Person(Json<Person>),
    Business(Json<Business>),
}

Different errors - This case is especially useful when working with multiple libraries with builtin-support for rocket.

#[derive(Responder)]
enum MyError {
    Custom(Json),
    GraphQL(GraphQLError),
    Twirp(TwirpError),
}
SergioBenitez commented 6 years ago

Absolutely. I already have a partial implementation of this complete and will polish and push as soon as I have some free time. This will be in 0.4.