Search code examples
rustrust-rocketserde-json

How to work around "data limit exceeded" error in Rocket?


I need to make an API in Rust to which you give a string, it performs some function, and then returns a new string. But an error occurs if the string is too long:

POST /test:
   >> Matched: (test) POST /test
   >> Data guard `String` failed: Custom { kind: UnexpectedEof, error: "data limit exceeded" }.
   >> Outcome: Failure
   >> No. 400 catcher registered. Using Rocket default.
   >> Response succeeded.

Here is my code:

#[macro_use] extern crate rocket;
#[macro_use] extern crate serde_json;

#[get("/")]
fn index() -> String {
    json!({"message": "Hello, world!"}).to_string()
}

#[post("/test", data = "<data>")]
fn test(data: String) -> String {
    json!({"data": data}).to_string()
}

#[launch]
fn rocket() -> _ {
    rocket::build().mount("/", routes![index, test])
}
[dependencies]
rocket = "0.5.0-rc.3"
serde_json = "1.0.64"
rocket_sync_db_pools = "0.1.0-rc.3"
serde = { version = "1.0", features = ["derive"] }
rocket_contrib = "0.4.11"

Solution

  • You can configure limits based on the incoming data type in your rocket.toml like so:

    [default.limits]
    form = "64 kB"
    json = "1 MiB"
    msgpack = "2 MiB"
    "file/jpg" = "5 MiB"
    

    See Configuration in the Rocket Programming Guide for more. Here's also the built-in limits.


    In your case, you are using String, which will map to the "string" limit which is 8KiB by default. Curious that you aren't using the Json type, which would handle serializing and deserializing for you in addition to having a higher limit by default, but to each their own.

    So you would do something like this (higher or lower as you prefer):

    [default.limits]
    string = "1 MiB"