Understanding HTTP
HTTP is an application layer protocol that provides communication standards between clients (such as web browsers) and web servers. This standardization helps browsers and servers talk to each other as long as the request and the response follow a specific format.
An HTTP request is a text document with four elements:
- Request line: This line contains the HTTP method, the resource requested (URI), and the HTTP version being used for the request. The HTTP method generally symbolizes the intended action being performed on the requested resource. For example,
GET
is used to retrieve resource information, whereasPOST
is used to send new resource information as a form. - Request headers: The next group of lines contains headers, which contain information about the request and the client. These headers are usually used for authorization, determining the type of request or resource, storing web browser information, and so on.
- Line break: This indicates the end of the request headers.
- Request body (optional): If present, this information contains data to be passed to the server. This is generally used to submit domain-specific forms.
Here’s an example of an HTTP request document:
GET / HTTP/1.1 Host: localhost:8080 User-Agent: curl/7.75.0 Accept: */* Body of the request
As you can see, the preceding request was made with the GET
method to localhost:8080
with the body, Body of
the request
.
Similarly, an HTTP response contains four elements:
- Response status line: This line consists of the HTTP version, a status code, and a reason phrase, which generally corresponds to the status code. Status codes are three-digit integers that help us categorize responses. For example,
2XX
status codes are used for a successful response, whereas4XX
status codes are used for errors due to the request. - Response headers: Just like request headers, this group of lines contains information about the response and the server’s state. These headers are usually used to show the size of the response body, server type, date/time of the response, and so on.
- Line break: This indicates the end of response headers.
- Response body (optional): If present, this section contains the information being relayed to the client.
The following is an example of an HTTP response document:
HTTP/1.1 404 Not Found content-length: 13 content-type: text/html server: Cowboy 404 Not found
The preceding response is an example of a 404 (Not found)
response. Notice that content-length
shows the number of characters present in the response body.
Now that we know how HTTP facilitates client-server communication, it is time to build a web server using Cowboy.