Sure! Here's a simple HTTP server in Elixir using the built-in Plug and Cowboy libraries—this is the most common way to write web servers in Elixir (similar to how you might use Express.js in TypeScript or Flask in Python).
We'll build a basic server that responds with "Hello, World!" for any request.
🛠️ Step 1: Create a New Mix Project
If you haven’t already, create a new Elixir project:
bash
mix new hello_server
cd hello_server
📦 Step 2: Add Dependencies
Open mix.exs and add plug and cowboy to your dependencies:
elixir
defp deps do
[
{:plug_cowboy, "~> 2.6"}
]
end
Then run:
bash
mix deps.get
💻 Step 3: Write the Server Code
Replace the contents of lib/hello_server.ex with this:
elixir
defmodule HelloServer do
use Plug.Router
plug(:match)
plug(:dispatch)
get "/" do
send_resp(conn, 200, "Hello, World!")
end
match _ do
send_resp(conn, 404, "Not Found")
end
end
🚀 Step 4: Start the Server
Create a file named server.exs at the root of your project:
defmodule HelloServer do
use Plug.Router
import Jason # You may need to add jason to deps if not included
plug(:match)
plug(:dispatch)
get "/json" do
conn
|> put_resp_content_type("application/json")
|> send_resp(200, Jason.encode!(%{message: "Hello, World!"}))
end
get "/" do
send_resp(conn, 200, "Hello, World!")
end
match _ do
send_resp(conn, 404, "Not Found")
end
end
Add {:jason, "~> 1.4"} to deps if needed:
elixir
defp deps do
[
{:plug_cowboy, "~> 2.6"},
{:jason, "~> 1.4"}
]
end