Let's write an HTTP Client in Rust: Part 1

Let's write an HTTP Client in Rust: Part 1

Rust Nov 25, 2022

In this post, we are going to learn what is HTTP, and how we can write an HTTP Client in Rust programming language from scratch. Of course, After this post, you can write a client in any programming language you want. Let's begin, Shall we?

What is HTTP?

HTTP(Hypertext Transfer Protocol) is a text-based Protocol built on top of TCP(Transmission Control Protocol), layer 4 of the OSI model. HTTP has 5 versions:

  • HTTP 0.9
  • HTTP 1.0
  • HTTP 1.1
  • HTTP 2
  • HTTP 3

The HTTP/0.9 is the first version and it is versioned due to separating it from newer versions. The important versions are HTTP/1.0, HTTP/1.1, and HTTP/2. Anyway, We aren't here to talk about HTTP versions.

How HTTP works?

Basically, we create a REQUEST with a specific METHOD type and get a RESPONSE based on our request. We have a few request methods:

  • GET
  • POST
  • HEAD
  • OPTIONS
  • PUT
  • PATCH

Below, You can see the Scheme of an HTTP request:

{METHOD} {/PATH} {HTTP_VERSION}\r\n
{HEADER1: HeaderValue1}\r\n
{HEADER2: HeaderValue2}\r\n
{HEADER3: HeaderValue3}\r\n
\r\n
{BODY}
\r\n\r\n
HTTP request Scheme

The Important difference between HTTP/1.0 and HTTP/1.1 is in version 1.1, the connection remains open for reuse and If we want to close it, we have to specify it with a specific header.

What is \r\n? and why we use it. this is the famous CRLF which is an abbreviation for Carriage Return Line Feed. It is a sign for a new line. there you go, search about it.

This is a full example of an HTTP POST request to benyaamin.com/create/new for creating a post:

POST /create/new HTTP/1.1\r\n
HOST: benyaamin.com\r\n
Content-Length: 68\r\n
Connection: Close\r\n
\r\n
action=new_post&title=How to write an HttpClient in Rust&publish=now
\r\n\r\n
POST HTTP Request

Just POST request has a body on it, So let's see what a request without a body looks like:

GET /posts HTTP/1.1\r\n
HOST: benyaamin.com\r\n
Connection: Close\r\n
\r\n\r\n
GET HTTP Request

As I said earlier, HTTP is a text-based protocol so That's it.

In the next part, I'm going to write about how to send a request in code.

You can watch my Youtube Playlist for this article.

Tags

Benyamin Eskandari

Curious, Experienced Android Developer Also in love with Rust, DevOps, and System Programming Trying to read a lot of books and learn a lot of things, I will write posts about my path on this journey.