Here's a simple HTTP server in Elixir using the built-in :gen_tcp module. I'll show you both a basic version and a more structured approach:
Basic HTTP Server (Raw TCP)
defmodule SimpleHTTPServer do
@port 4000
def start do
{:ok, socket} = :gen_tcp.listen(@port, [
:binary,
packet: :raw,
active: false,
reuseaddr: true
])
IO.puts("Server listening on port #{@port}")
accept_loop(socket)
end
defp accept_loop(socket) do
{:ok, client} = :gen_tcp.accept(socket)
# Spawn a new process to handle each client
spawn(fn -> handle_client(client) end)
# Continue accepting new connections
accept_loop(socket)
end
defp handle_client(client) do
case :gen_tcp.recv(client, 0) do
{:ok, request} ->
response = handle_request(request)
:gen_tcp.send(client, response)
:gen_tcp.close(client)
{:error, _reason} ->
:gen_tcp.close(client)
end
end
defp handle_request(request) do
# Parse the first line to get method and path
[request_line | _] = String.split(request, "\r\n")
[method, path, _version] = String.split(request_line, " ")
# Route the request
route(method, path)
end
defp route("GET", "/") do
html_response("""
<html>
<body>
<h1>Hello from Elixir!</h1>
<p>This is a simple HTTP server.</p>
<a href="/about">About</a>
</body>
</html>
""")
end
defp route("GET", "/about") do
html_response("""
<html>
<body>
<h1>About</h1>
<p>This server is built with Elixir and raw TCP sockets.</p>
<a href="/">Home</a>
</body>
</html>
""")
end
defp route("GET", "/api/hello") do
json_response(%{message: "Hello from API!", timestamp: DateTime.utc_now()})
end
defp route(_method, _path) do
not_found_response()
end
defp html_response(body) do
"HTTP/1.1 200 OK\r\n" <>
"Content-Type: text/html\r\n" <>
"Content-Length: #{byte_size(body)}\r\n" <>
"\r\n" <>
body
end
defp json_response(data) do
body = Jason.encode!(data) # You'll need to add Jason dependency
"HTTP/1.1 200 OK\r\n" <>
"Content-Type: application/json\r\n" <>
"Content-Length: #{byte_size(body)}\r\n" <>
"\r\n" <>
body
end
defp not_found_response do
body = "<html><body><h1>404 Not Found</h1></body></html>"
"HTTP/1.1 404 Not Found\r\n" <>
"Content-Type: text/html\r\n" <>
"Content-Length: #{byte_size(body)}\r\n" <>
"\r\n" <>
body
end
end
# Start the server
SimpleHTTPServer.start()
More Structured Version with GenServer
For production use, you'd typically use a GenServer to manage the server state:
defmodule HTTPServer do
use GenServer
@port 4000
# Client API
def start_link(opts \\ []) do
GenServer.start_link(__MODULE__, opts, name: __MODULE__)
end
def stop do
GenServer.stop(__MODULE__)
end
# GenServer Callbacks
def init(_opts) do
{:ok, socket} = :gen_tcp.listen(@port, [
:binary,
packet: :raw,
active: false,
reuseaddr: true
])
IO.puts("HTTP Server started on port #{@port}")
# Start accepting connections in a separate process
spawn_link(fn -> accept_loop(socket) end)
{:ok, %{socket: socket}}
end
def handle_info({:tcp_closed, _socket}, state) do
{:noreply, state}
end
def terminate(_reason, %{socket: socket}) do
:gen_tcp.close(socket)
end
# Private functions (same as above)
defp accept_loop(socket) do
{:ok, client} = :gen_tcp.accept(socket)
# Use Task for better process management
Task.start(fn -> handle_client(client) end)
accept_loop(socket)
end
defp handle_client(client) do
case :gen_tcp.recv(client, 0, 5000) do # 5 second timeout
{:ok, request} ->
response = handle_request(request)
:gen_tcp.send(client, response)
:gen_tcp.close(client)
{:error, :timeout} ->
IO.puts("Client timeout")
:gen_tcp.close(client)
{:error, reason} ->
IO.puts("Error: #{inspect(reason)}")
:gen_tcp.close(client)
end
end
# ... (same routing functions as above)
defp handle_request(request) do
[request_line | _] = String.split(request, "\r\n")
[method, path, _version] = String.split(request_line, " ")
route(method, path)
end
defp route("GET", "/"), do: html_response("<h1>Hello from GenServer!</h1>")
defp route("GET", "/health"), do: json_response(%{status: "ok"})
defp route(_, _), do: not_found_response()
defp html_response(body) do
"HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: #{byte_size(body)}\r\n\r\n#{body}"
end
defp json_response(data) do
body = inspect(data) # Simple JSON-like representation
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: #{byte_size(body)}\r\n\r\n#{body}"
end
defp not_found_response do
body = "Not Found"
"HTTP/1.1 404 Not Found\r\nContent-Length: #{byte_size(body)}\r\n\r\n#{body}"
end
end
# Usage
{:ok, _pid} = HTTPServer.start_link()
Using with Mix Project
To run this properly, create a new Mix project:
mix new http_server
cd http_server
Add to mix.exs dependencies (if you want JSON support):
defp deps do
[
{:jason, "~> 1.4"} # For JSON encoding
]
end
Then put the server code in lib/http_server.ex and start it from lib/http_server/application.ex:
defmodule HttpServer.Application do
use Application
def start(_type, _args) do
children = [
HTTPServer # This will call HTTPServer.start_link()
]
opts = [strategy: :one_for_one, name: HttpServer.Supervisor]
Supervisor.start_link(children, opts)
end
end
Testing the Server
Start the server and test with curl:
# Start the server
iex -S mix
# In another terminal:
curl http://localhost:4000/
curl http://localhost:4000/about
curl http://localhost:4000/api/hello
Production Note
For real applications, use established HTTP servers like:
- Plug + Cowboy (most common)
- Phoenix (full web framework)
- Bandit (newer HTTP server)
This raw TCP approach is educational but lacks many features like HTTP/2, SSL, proper header parsing, etc. The Plug ecosystem provides these out of the box.