Last active
June 8, 2023 13:25
-
-
Save hugs/11da6902ed0a2d3861cb721b3d4c98bf to your computer and use it in GitHub Desktop.
Minimal Viable Web Server in Nim
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Minimal Viable Web Server for Nim | |
# 1) Install Nim: | |
# https://nim-lang.org/install.html | |
# 2) To run, enter this in a terminal window: | |
# nim c -r webserver.nim | |
# 3) Press Control-C to quit / stop the server. | |
# Nim creates a small, compiled binary. | |
# To run again: | |
# ./webserver | |
# With thanks to Alasdair Allan (@aallan) for the inspiration: | |
# https://www.raspberrypi.com/news/how-to-run-a-webserver-on-raspberry-pi-pico-w/ | |
# Tested on macOS Monterey (12.6.6) | |
# and Termux v0.117, Android 13 | |
import std/net, std/strutils | |
from std/posix import SIGINT, SIGTERM, onSignal | |
var | |
address = "127.0.0.1" | |
port = 8080 | |
client: Socket | |
url = "" | |
let socket = newSocket() | |
socket.setSockOpt(OptReusePort, true) | |
socket.bindAddr(Port(port), address) | |
socket.listen() | |
onSignal(SIGINT, SIGTERM): | |
echo "⏹️ Stopping..." | |
quit() | |
echo "▶️ Starting server at http://" & address & ":" & $port & "/" | |
while true: | |
socket.acceptAddr(client, address) | |
var line: string | |
while true: | |
client.readLine(line) | |
var lineparts = line.split(' ') | |
if lineparts[0] == "GET": | |
url = lineparts[1] | |
echo lineparts[0] & " " & url | |
if line == "\r\n": | |
if url == "/": | |
client.send("HTTP/1.1 200 OK\r\n") | |
client.send("Content-type: text/html; charset=utf-8\r\n\r\n") | |
client.send("<h1 style='font-size: 50;'>Hello, World! 👋🏽🌐</h1>") | |
client.close() | |
break | |
else: | |
client.send("HTTP/1.1 404 Not Found\r\n") | |
client.send("Content-type: text/html; charset=utf-8\r\n\r\n") | |
client.send("<h1 style='font-size: 200;'>🤷</h1>") | |
client.close() | |
break |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment