facebook

Building an Elixir HTTP server

Building an Elixir HTTP server
Average rating: 0
(0 votes)

Thanks! You’ve rated this material!

Elixir is one of our favorite topics and we are never tired of sharing some interesting material with you. Today we are going to tell you about building an Elixir HTTP server.

We’ll start with the fundamentals. HTTP is a protocol that commonly uses TCP to transport requests and responses between an HTTP client—like a web browser—and a web server.

Erlang provides the :gen_tcp module that can be used to start a TCP socket that receives and transmits data. We’ll use that library as the basis of our server.  We start a socket to listen to the passed in port in start_link/1, and we’ll spawn accept/1 in a new process that waits until a request comes in over the socket by calling :gen_tcp.accept/1. When it does, we put it into the request variable and create a response to send to the client. In this case, we’ll be sending a response that shows the current time.

To make sure our web server can communicate with our web application, we need to build a %Plug.Conn{} struct to pass to CurrentTime.call/2. We’ll also need to turn the sent response into a string that our web server can send back over the socket.

With everyone in place, and no screws on the floor, our project to look into HTTP servers in Elixir is done. We’ve implemented a web server that extracts data from requests and used it to send a request to a Plug application. It even has concurrency included: since each request spawns a separate process, our web server can handle multiple concurrent users.

More code examples are presented here.

It can be interesting for you as well to read how you can use Elixir Component library for writing code as servers.

Rate this article, if you like it

Thanks! You’ve rated this material!

Got a project? Let's discuss it!

*By submitting this form you agree with our Privacy Policy.

Mailing & Legal Address

Syndicode Inc. 340 S Lemon Ave #3299, Walnut CA, 91789, USA

Visiting & Headquarters address
Kyiv Sofiivska 1/2a, 01001, Kyiv, Ukraine
Dnipro Hlinky 2, of. 1003, 49000, Dnipro, Ukraine
Email info@syndicode.com
Phone (+1) 9035021111