rupring

Module request

Source
Expand description

HTTP request module

§About Request

  • You can access any value provided in an HTTP Request through the Request parameter.
#[rupring::Get(path = /:id)]
pub fn hello(request: rupring::Request) -> rupring::Response {
    let method = request.method;
    assert_eq!(method, rupring::Method::GET);

    let path = request.path;
    assert_eq!(path, "/");

    let body = request.body;
    assert_eq!(body, "");

    let headers = request.headers;
    let content_type = headers.get("content-type").unwrap();
    assert_eq!(content_type, "text/plain");

    let id = request.path_parameters["id"].clone();
    assert_eq!(id, "123");

    let query = request.query_parameters["query"].clone();
    assert_eq!(query, vec!["asdf".to_string()]);

    //...

    response
}

§Request: Path Param

For path parameters, auto binding is provided through annotation.

The annotation name can be one of Path, path, or PathVariable.

#[rupring::Get(path = /echo/:id)]
pub fn echo(
    #[PathVariable="id"] id: i32
) -> rupring::Response {
    println!("id: {}", id);

    rupring::Response::new().text(request.body)
}

If the Path Param is optional, just wrap the type in Option.

#[rupring::Get(path = /echo/:id)]
pub fn echo(
    #[PathVariable="id"] id: Option<i32>
) -> rupring::Response {
    // ...

    rupring::Response::new().text("OK".to_string())
}

If you need Swagger documentation for the Path Param, you should add the Description annotation. Description can also be used as Desc, desc, etc.

#[rupring::Get(path = /echo/:id)]
pub fn echo(
    #[path="id"] #[desc="asdf"] id: i32
) -> rupring::Response {
    println!("id: {}", id);

    rupring::Response::new().text(request.body)
}

If you want to define a custom type for PathParam, you can implement the ParamStringDeserializer trait.

struct SomeCustomType {}

impl rupring::ParamStringDeserializer<SomeCustomType> for rupring::ParamString {
    type Error = ();

    fn deserialize(&self) -> Result<SomeCustomType, Self::Error> {
        //...
        Ok(SomeCustomType {})
    }
}

Structs§

Traits§