Handling http request with JSON

In the building web example in the book we have these 2 lines for illustration:

    let get = b"GET / HTTP/1.1\r\n";
    let sleep = b"GET /sleep HTTP/1.1\r\n";

What if I wanted to get JSON.

I know there are frameworks that do this for me, but interested in understanding it without using other crate.

It’s not clear to me how JSON is applicable here. Can you give an example of the JSON output you expect to produce?

Do you want to get JSON from server (and use it in browser), or on server (when it is posted from browser)?

I want it:

i want to receive JSON from browser, and process it in the server.

An HTTP request as a number of header lines, which include the 'GET' line you show above. There are also other header lines following that.

That header is terminated by a blank line which might then be be followed by a 'body'. It is the body where you would put the JSON formatted data you want to send from browser to server.

GET requests do not have a body. You will need to use a POST request.

You can read all about HTTP requests and their format here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Overview

1 Like

Thanks, I read the article, but now how can I extract the POST body content in Rust?

You just have to read all of the request the browser is sending, not just the single GET/POST or whatever request line. That includes reading the headers then continue reading more for the body.

As an experiment you could read everything that comes from the request stream until the connection is closed by the browser and print it all out. Then you will see exactly what the browser is sending and and what you have to parse out of it.

You should find headers that indicate the type of the content as JSON and tell how long it is in bytes.

This is an interesting learning exercise but it can be a lot of fiddly parsing. Ultimately you will want to use ready made modules to do that: https://docs.rs/http/0.2.1/http/request/index.html

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.