Build a Web Server
A complete HTTP server in Wyn - under 30 lines.
The Server
wyn
server = Http.listen(8080)
print("Listening on http://localhost:8080")
while true {
req = Http.accept(server)
parts = req.split("|")
method = parts[0]
path = parts[1]
Log.info(method + " " + path)
if path == "/" {
Http.respond(req, 200, "text/html", "<h1>Hello from Wyn! 🐉</h1>")
} else if path == "/api/time" {
now = "${DateTime.now()}"
Http.respond(req, 200, "application/json", "{\"time\": " + now + "}")
} else {
Http.respond(req, 404, "text/html", "Not Found")
}
}Run It
sh
wyn run server.wynThen visit http://localhost:8080 in your browser.
Add Concurrency
Handle requests in parallel with spawn:
wyn
server = Http.listen(8080)
print("Listening on :8080")
while true {
req = Http.accept(server)
spawn handle(req)
}
fn handle(req: string) {
parts = req.split("|")
path = parts[1]
Log.info("handling " + path)
if path == "/" {
Http.respond(req, 200, "text/plain", "Hello!")
} else {
Http.respond(req, 404, "text/html", "Not Found")
}
}Each request runs on its own thread pool worker - lightweight tasks, not blocking the main thread.
Build for Production
sh
wyn build server.wyn --release -o server
./server # ~69KB binary, starts instantlySee Also
- Networking - HTTP client and server
- Web Framework - routing and middleware
- Database - SQLite for persistence
- JSON - parse and generate JSON
- Docker Deployment - containerize your web server
- I Built a Web Server Without Installing a Single Package - real-world example
- Build a Complete REST API in 93 Lines - CRUD API tutorial