Change Theme


Building a Basic HTTP Server with Elixir - Part 1

December 28th 2018

A few days ago, I read a post about Why you shouldn't use a web framework that gave me a bit of inspiration. Frameworks are great tools for full-fledged apps, but sometimes you don't need or want all the magic a framework provides.

Full disclosure though, a much better solution to what we're building is better done in Phoenix by passing --no-ecto --no-webpack which would get you a much better, more stable, more efficient base in which to build upon.

But thats not the point of this tutorial. We're not fully replicating Phoenix, we're making this a super simple HTTP server. You can view the full implementation here.

Go ahead and open up a terminal and do mix new todo --sup which will get us a nice little project started with a Supervision tree. That will allow us to start the GenServer automatically when the application is ran.

We'll start by building up the GenServer portion of it. We need to be able to do all CRUD functions in the app, so we'll make a file under todo/elixir/lib/todo/ called server.ex.

That lays out the client interface for us so that we can begin implementation. To start a GenServer, we call start/1 or start_link/1 which handles the call to init/1.

Going back to our Terminal, we can run our app by typingiex -S mixwhich will get a REPL. Inside, we can make sure our server starts by typingTodo.Server.start_link([]), and you should get the following

The PID will likely be different for you, of course. 

We can go ahead and make sure that the Todo Server starts when we run iex -S mix. Go into lib/todo/application.ex and to the start/2 function already there.

Next, we'll implement the Add and List functions.

Notice that I'm using call here instead of cast. This is because when we make our HTTP server, it will reply with the list of Todos with every response. We're not going to be dealing with holding any state on the front end, so we can't just reply with an :ok.

We can then go back to our terminal again and  iex -S mix. Our GenServer should boot up with the application, so no need to call start_link this time. Lets try it out!

Your response should look something like that. If it does, great! Lets move on to our toggle/1 function.

And again, we'll test it out.

Wonderful! Next up, remove/1.

And we test..

Great, that makes up our abilities to add, toggle, remove and list Todos in a GenServer app. Next, we'll make our HTTP server.

Check out part 2 here

Have any questions or comments? Feel free to send me a tweet!

Built with Gatsby and Prismic.

© Copyright 2019, Matthew Secrist