惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Scott Helme
Scott Helme
N
Netflix TechBlog - Medium
AI
AI
Security Latest
Security Latest
GbyAI
GbyAI
P
Proofpoint News Feed
Y
Y Combinator Blog
A
Arctic Wolf
G
Google Developers Blog
U
Unit 42
爱范儿
爱范儿
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
V
Vulnerabilities – Threatpost
Know Your Adversary
Know Your Adversary
Cisco Talos Blog
Cisco Talos Blog
T
Tor Project blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
T
Threatpost
L
Lohrmann on Cybersecurity
C
CERT Recently Published Vulnerability Notes
C
Check Point Blog
B
Blog RSS Feed
The GitHub Blog
The GitHub Blog
Microsoft Azure Blog
Microsoft Azure Blog
博客园 - 【当耐特】
博客园 - Franky
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
C
Cisco Blogs
云风的 BLOG
云风的 BLOG
NISL@THU
NISL@THU
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Microsoft Security Blog
Microsoft Security Blog
T
The Blog of Author Tim Ferriss
阮一峰的网络日志
阮一峰的网络日志
Latest news
Latest news
L
LINUX DO - 最新话题
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
美团技术团队
WordPress大学
WordPress大学
L
LangChain Blog
Stack Overflow Blog
Stack Overflow Blog
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
酷 壳 – CoolShell
酷 壳 – CoolShell
大猫的无限游戏
大猫的无限游戏
The Hacker News
The Hacker News
Simon Willison's Weblog
Simon Willison's Weblog
V
V2EX
Project Zero
Project Zero
博客园_首页

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
HTTP Server in Erlang with Cowboy
Mathieu K · 2026-05-29 · via DEV Community

Finally, a bit of Erlang! Instead of writing the same 101 introduction to this marvelous language, we will switch directly on the most used HTTP Web Server on this ecosystem: Cowboy. The goal will be to create a flexible module letting us configuring HTTP/1.1, HTTP/2, HTTP/3 and WebSocket easily. Why do I need that? For some of my local test, especially for Dart/Flutter.

Anyway, it's time to create a new fresh project to explain that, let call it Buckaroo.

Project Bootstrapping with rebar3

Just a quick reminder for the newcomers who never tried Erlang, below, the command to generate a new app project.

$ rebar3 new app name=buckaroo

Enter fullscreen mode Exit fullscreen mode

All the magic will happen in the src/ directory but cowboy must be added in the dependencies list in rebar.config.

{erl_opts, [debug_info]}.
{deps, [cowboy]}.
{shell, [{apps, [buckaroo]}]}.

Enter fullscreen mode Exit fullscreen mode

Let fetch everything.

$ rebar3 get-deps
$ rebar3 compile

Enter fullscreen mode Exit fullscreen mode

Starting Cowboy

To make things easier, a dedicated module to manage cowboy called buckaroo_cowboy is created. And to avoid too much complexity, only 2 functions will be exported

  • start_link/0 to start the cowboy listener;

  • stop/0 to stop the cowboy listener.

-module(buckaroo_cowboy).
-export([start_link/0, stop/0]).

Enter fullscreen mode Exit fullscreen mode

A cowboy listener needs a name, let create a function called name/0 to deal with that. It will return the listener name.

name() ->
  buckaroo_listener.

Enter fullscreen mode Exit fullscreen mode

Now, the HTTP API routes are required, the cowboy routing documentation is complete and should be way enough to understand how to routes requests with cowboy. 2 routes will be created there, the default one (/) will be used for HTTP requests, and (/ws) for the WebSockets. In both case, the last element of the tuple passed by the router will be a map(), this value will be used as connection state.

routes() ->
  [
    {'_', [
      {"/", buckaroo_handler, #{}},
      {"/ws", buckaroo_websocket_handler, #{}}
    ]
  }].

Enter fullscreen mode Exit fullscreen mode

The routes, then, must be compiled with the help of the cowboy_router:compile/1 function.

dispatch() ->
  cowboy_router:compile(
    routes()
  ).

Enter fullscreen mode Exit fullscreen mode

A cowboy listener will also require 2 kinds of options, the transport options (TCP) and the protocol options (including HTTP and HTTP/2 options). In our case, only the listening port (TCP/8081) will be set.

transport_options() ->
  [
    {port, 8081}
  ].

Enter fullscreen mode Exit fullscreen mode

The protocol options can be defined, in this case, only the routing will be configured via the dispatch key.

protocol_options() ->
  #{
    env => #{
      dispatch => dispatch()
    }
  }.

Enter fullscreen mode Exit fullscreen mode

To start a cowboy listener, the (cowboy:start_clear/3)(https://ninenines.eu/docs/en/cowboy/2.15/manual/cowboy.start_clear/) function can be used. If a TLS certificate is configured, the cowboy:start_tls/3 must be used instead. The first argument is the name of the listener, the second the transport options and the last one the protocol options.

start_link() ->
  cowboy:start_clear(
    name(),
    transport_options(),
    protocol_options()
  ).

Enter fullscreen mode Exit fullscreen mode

Finally, the stop() function can be created to help shutdown cowboy, using simply the name previously configured and with the cowboy:stop_listener/1 function.

stop() ->
    cowboy:stop_listener(name()).

Enter fullscreen mode Exit fullscreen mode

A quick remark regarding my coding style. I like creating really small functions and call them in some part of the code. It can help to document but also to test the module. We will see that in another publication about finite state machines.

The final modification, is to add the cowboy listener in the supervision tree by editing src/buckaroo_sup.erl.

-module(buckaroo_sup).
-behavior(supervisor).
-export([start_link/0, init/1]).

start_link() ->
  supervisor:start_link({local, ?MODULE}, ?MODULE, []).

init(_) ->
  {ok, {supervisor_flags(), child_specs()}}.

supervisor_flags() ->
  #{
    strategy => one_for_all,
    intensity => 0,
    period => 1
  }.

child_specs() ->
  [
    #{
      id => buckaroo_cowboy,
      start => {buckaroo_cowboy, start_link, []}
    }
  ].

Enter fullscreen mode Exit fullscreen mode

Now, the application can be started, for development and debug purpose only, it will be started with an Erlang shell.

$ rebar3 shell
===> Verifying dependencies...
===> Analyzing applications...
===> Compiling buckaroo
Erlang/OTP 29 [erts-17.0] [source] [64-bit] [smp:16:16] [ds:16:16:10] [async-threads:1] [jit:ns]

Eshell V17.0 (press Ctrl+G to abort, type help(). for help)
===> Booted cowlib
===> Booted ranch
===> Booted cowboy
===> Booted buckaroo

Enter fullscreen mode Exit fullscreen mode

Well done, but it will not work correctly, because the handlers are missing... Let fix that in the next sections of this article.

Dealing with HTTP Requests

An handler can usually deal with HTTP requests but also with WebSocket ones. Let

-module(buckaroo_handler).
-export([init/2]).
-include_lib("kernel/include/logger.hrl").

Enter fullscreen mode Exit fullscreen mode

init(Req, State) ->
  Reply = cowboy_req:reply(200,
    #{
      <<"content-type">> => <<"text/plain">>
    },
    <<"hello">>,
    Req
  ),
  {ok, Reply, State}.

Enter fullscreen mode Exit fullscreen mode

The cowboy request object is the core data structure used by any handlers, here a quick view of its content when using curl locally.

#{
  pid => <0.1260.0>,
  port => 8081,
  scheme => <<"http">>,
  version => 'HTTP/1.1',
  path => <<"/">>,
  host => <<"localhost">>,
  peer => {{127,0,0,1},50986},
  bindings => #{},
  cert => undefined,
  headers => #{
    <<"accept">> => <<"*/*">>,
    <<"host">> => <<"localhost:8081">>,
    <<"user-agent">> => <<"curl/8.14.1">>
  },
  ref => buckaroo_listener,
  host_info => undefined,
  path_info => undefined,
  streamid => 1,
  method => <<"GET">>,
  body_length => 0,
  has_body => false,
  qs => <<>>,
  sock => {{127,0,0,1},8081}}
}.

Enter fullscreen mode Exit fullscreen mode

As you can see, this is a simple map() containing specific keys. The value of those keys can be retrieved using Erlang pattern matching, or by using the cowboy functions helpers from the module cowboy_req. This data structure will be used to route the request and alter the final response, so, let check them one by one.

  • pid is the process id of the process in charge of the request;

  • port is the port from the listener and can also be extracted using cowboy_req:port/1 function;

  • scheme is the scheme using, usually http or https. This information can be obtained using cowboy_req:scheme/1 function as well;

  • version is the protocol version used, it can be HTTP/1.0, HTTP/1.1, HTTP/2 or HTTP/3. It can be extracted with the help of cowboy_req:version/1 function;

  • path represents the full path requested by the client, this value is more or less related to the routing defined when starting cowboy, it can be extracted using cowboy_req:path/1 function;

  • host represents the host name requested by the client, it is also a part of the routing configuration, this value can also be extracted using cowboy_req:host/1 function;

  • peer contains the IP address/port of the client, it can also be extracted using cowboy_req:peer/1 function;

  • bindings is set when the route is configured with pattern matching, if it was the case, the variables defined in the route would have been converted into bindings;

  • cert is set when a certificate is sent by the client, it can be extracted using cowboy_req:cert/1 function;

  • headers are the HTTP Headers sent by the client, an header value can be extracted using cowboy_req:header/2 or cowboy_req:header/3 functions;

  • ref (internal usage) stores the name of the listener;

  • host_info returns the routing pattern matching result, it can also be accessed using cowboy_req:host_info/1 function;

  • path_info returns the routing pattern matching result, it can also be extracted using cowboy_req:path_info/1 function;

  • streamid (internal usage) defines the stream id of the connection;

  • method defines the HTTP method used by the client for the request, it can also be retrieved using cowboy_req:method/1 function;

  • body_length defines the size of the data sent by the client in the HTTP body, the value of this key can be also fetched using cowboy_req:body_length/1 function;

  • has_body defines if the request contains a body or not. Mostly used with POST, PUT and other HTTP methods sending data. It can also be checked using cowboy_req:has_body/1 function;

  • qs is the raw query string, it should be parsed using uri_string:dissect_query/1 function or with your own method. The value can also be retrieved using cowboy_req:qs/1;

  • sock contains the IP address and port of the server, it can be extracted using cowboy_req:sock/1 function.

The handler is done, it's a really simple one, but just to check if it's working, we can use curl.

$ curl -kv http://localhost:8081/; echo
* Host localhost:8081 was resolved.
* IPv6: ::1
* IPv4: 127.0.0.1
* HTTPS-RR: -
*   Trying [::1]:8081...
* connect to ::1 port 8081 from ::1 port 48828 failed: Connection refused
*   Trying 127.0.0.1:8081...
* Established connection to localhost (127.0.0.1 port 8081) from 127.0.0.1 port 48800 
* using HTTP/1.x
> GET / HTTP/1.1
> Host: localhost:8081
> User-Agent: curl/8.20.0
> Accept: */*
> 
* Request completely sent off
< HTTP/1.1 200 OK
< content-length: 5
< content-type: text/plain
< date: Wed, 27 May 2026 12:20:21 GMT
< server: Cowboy
< 
* Connection #0 to host localhost:8081 left intact
hello

Enter fullscreen mode Exit fullscreen mode

Dealing with WebSockets

Cowboy can also managed WebSocket connections using websocket handlers. The idea is to create 4 callback functions, one for the HTTP request and three for the WebSocket events.

-module(buckaroo_websocket_handler).
-export([init/2]).
-export([websocket_init/1, websocket_handle/2, websocket_info/2]).
-include_lib("kernel/include/logger.hrl").

Enter fullscreen mode Exit fullscreen mode

When a client wants to use WebSocket protocol, it will first send an HTTP request with some specific information, then the server will start the negotiation, this step, is mostly done in init/2 callback.

init(Req, State) ->
  WebSocketOpts = #{
    active_n => 1,
    compress => false,
    data_delivuery => stream_handlers,
    data_delivery_flow => 1,
    deflate_opts => #{},
    dynamic_buffer => {1024, 131_072},
    idle_timeout => 60_000,
    max_frame_size => 120_000,
    req_filter => fun(Req) -> Req end,
    validate_utf8 => true
  },
  ?LOG_DEBUG("~p:~p: ~p~n", [
    ?MODULE,
    ?FUNCTION_NAME,
    WebSocketOpts,
    Req
  ]),
  {cowboy_websocket, Req, State, WebSocketOpts}.

Enter fullscreen mode Exit fullscreen mode

At the end of the negociation, the server can do some initialization state using the websocket_init/1 callback. In our case, the text event hey\n will send to the client by the server.

websocket_init(State) ->
  ?LOG_DEBUG("~p:~p: ~p~n", [?MODULE, ?FUNCTION_NAME]),
  {[{text, <<"hey\n">>}], State}.

Enter fullscreen mode Exit fullscreen mode

To handle messages sent by the client, a websocket_handle/2 function must be created and exported by the module. The first argument received is a tuple containing the type of data (defined in the websocket_handle callback and also defined as cow_ws:frame() type), and its content. The second argument is the connection state.

websocket_handle(Frame = {text, Message}, State) ->
  ?LOG_DEBUG("~p:~p: ~p, ~p~n", [?MODULE, ?FUNCTION_NAME, Frame]),
  {[{text, Message}], State};
websocket_handle(Frame = {binary, Message}, State) ->
  ?LOG_DEBUG("~p:~p: ~p, ~p~n", [?MODULE, ?FUNCTION_NAME, Frame]),
  {[{binary, Message}], State};
websocket_handle(Frame, State) ->
  ?LOG_DEBUG("~p:~p: ~p, ~p~n", [?MODULE, ?FUNCTION_NAME, Frame]),
  {[Frame], State}.

Enter fullscreen mode Exit fullscreen mode

The websocket handler is running in a process, and this process can receive message from another running process from the system. In this case, the message will be handled by websocket_info/2 function callback.

websocket_info(Event, State) ->
  ?LOG_DEBUG("~p:~p: ~p, ~p~n", [?MODULE, ?FUNCTION_NAME, Event]),
  {ok, State}.

Enter fullscreen mode Exit fullscreen mode

Let check that with curl to see what will happen.

$ curl -N -T. --no-progress-meter -v ws://localhost:8081/ws
* Host localhost:8081 was resolved.
* IPv6: ::1
* IPv4: 127.0.0.1
* HTTPS-RR: -
*   Trying [::1]:8081...
* connect to ::1 port 8081 from ::1 port 45396 failed: Connection refused
*   Trying 127.0.0.1:8081...
* Established connection to localhost (127.0.0.1 port 8081) from 127.0.0.1 port 43458 
* using HTTP/1.x
> GET /ws HTTP/1.1
> Host: localhost:8081
> User-Agent: curl/8.20.0
> Accept: */*
> Upgrade: websocket
> Sec-WebSocket-Version: 13
> Sec-WebSocket-Key: +t+tuHiQUK6MMQySUqDGtQ==
> Connection: Upgrade
> 
* Request completely sent off
< HTTP/1.1 101 Switching Protocols
< connection: Upgrade
< date: Wed, 27 May 2026 12:21:53 GMT
< sec-websocket-accept: F87i2EOBLl+kwTQ3PCdZqjjcxuA=
< server: Cowboy
< upgrade: websocket
< 
* Received 101, Switching to WebSocket
* [WS] Received 101, switch to WebSocket
{ [5 bytes data]
hey

hello!
hello!
test1
test1
* upload completely sent off: 32 bytes

Enter fullscreen mode Exit fullscreen mode

The websocket handler correctly acts as an echo server, it looks good!

Conclusion

It's always a pleasure to write Erlang code, even more after many weeks where I passed all my time learning Dart/Flutter. Erlang code is concise and efficient. Cowboy is following the same philosophy there, and give us a good idea how to manage requests.

This project example can be seen on niamokik/buckaroo repository at Github.

Have fun!

References and Resources


Cover Image by JJ Ying on Unsplash