The Crystal Programming Language Forum

How to get raw post request without any modification?

Is it possible to obtain the raw string (or bytes that can be converted to string) of a json post request as it comes down the wire, without any modification/parsing? If so, how can that be done?

I need the exact body as it comes down the wire to create a payload and then encrypt it and then compare it with a signature.

Thank you.

Just wanted to mention that I figured it out. Please respond if you think there is a better way. I know that I should get content-length from the header, but other than that this works.

io = env.request.body.not_nil!
        
slice = Bytes.new(100000)
io.read(slice)
str = String.new(slice)

Could you not just do like env.request.body.not_nil!.gets_to_end?

I did not know about that. Will check and report. Would definitely be easier.

Thank you.

That works! Awesome!

Thank you for suggesting that.

NP, the request body is of type IO, so all methods on IO are available.

See https://crystal-lang.org/api/IO.html

Be careful using read, it might do a partial read. You can use read_fully, but the best solution is probably gets_to_end.

Thank you for that explanation @Blacksmoke16.
@asterite thanks for the warning. That is helpful to know. Yes, I switched it over to gets_to_end.