I spent a lot of time for something I would have never expected Rocket to handle out-of-the-box #2830
JensMertelmeyer
started this conversation in
Feedback
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I am new to Rocket, and even Rust. I had to build a server that accepts multipart posts with an arbitrary number of elements. The first element is a JSON array, followed by an arbitrary number of binary files (up to 50) which I then have to process.
After several approaches, I got it working, and I am super happy. I had a blast. In the end, barely any of my own code remains because Rocket is doing everything for me. I struggled for a while, because it never entered my mind Rocket could be so powerful and smart, parsing everything from the multipart body by itself. Amazing! 🪄✨
In detail, here is what I did:
After I got my "hello world" example running, I started looking into how I could access the payload. Accessing the first part was easy, still it felt somewhat magical.
Just this simple struct, and rocket just fills in the string field
json
directly for me? Great.I then struggled to access all the other fields. I spent a lot of time with
rocket::form::Contextual
but was heartbroken to see that it will just allow me to see the existence of data fields, but not their content.Due to Rockets lenient parsing strategy, I went forward with something like
which felt completely wrong. It did work (after increasing the limits for receiving byte arrays in
Rocket.toml
), but still...Through this discussion, I found the rocket-multipart crate, but was unsure of how to actually use it. Probably not a big deal for somebody with more Rust experience, but for me, it was.
I don't know why I always glossed over the relevant parts in the guide, but the documentation on the FromForm trait finally brought me on the right track:
Also, @SergioBenitez had a great example already posted here:
#2634
So I just ended up with this:
So easy! 😇
My mind was blown again after I followed the excellent guide on JSON in requests. As the first item in the multipart request, I get an array of JSON objects.
After properly defining my
NewSpot
struct, Rocket just casually parses everything back with just this:I just say "Well, I have a vector of these rust structures, and it's in JSON. Oh, and after that, there will be a couple of files. Please give me the bytes" and Rocket just does it. It still boggles my mind. 🤯
Needless to say, I had a lot of fun. Thank you, Rocket people 🚀
Beta Was this translation helpful? Give feedback.
All reactions