0

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

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.

rust 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])
}

cargo.toml:

[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"

I tried to solve the problem with ChatGPT and perplexity ai but they didn't help

Duxtaa
  • 15
  • 3

2 Answers2

1

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"
kmdreko
  • 42,554
  • 6
  • 57
  • 106
0

Probably related to https://api.rocket.rs/v0.4/rocket/config/struct.Limits.html , if you are posting huge json string (>32KiB by rocket default setting).

To increase the body size limit, change fn rocket() to

use rocket::{
    config::{Environment, Limits},
    Config,
};

fn main() {
    let conf = Config::build(Environment::Development)
        .limits(Limits::new().limit("forms", 1048576 * 1024))
        .unwrap();

    rocket::custom(conf)
        .mount(...)
        .launch();
}