HttpServer
An HTTP server for handling web requests.
HttpServer wraps Go's net/http server. It supports static file serving and route-based request handling with method filtering. Route handlers receive an HttpRequest and should return an HttpResponse or a string.
"Basic web server"
| server <HttpServer> |
server := HttpServer new: 8080.
server route: '/hello' method: 'GET' handler: [:req |
HttpResponse new: 200 body: 'Hello, world!'
].
server start
"Static file server with API endpoint"
| server <HttpServer> |
server := HttpServer new: 3000.
server serveStatic: '/assets/' from: './public'.
server route: '/api/echo' method: 'POST' handler: [:req |
HttpResponse new: 200 body: req body
].
server start
Class Methods
primitives
Create a new HTTP server listening on the given port.
The server is not started until start is called.
| server <HttpServer> |
server := HttpServer new: 8080
Instance Methods
primitives
Return true if the server is currently running.
| server <HttpServer> |
server := HttpServer new: 8080.
server isRunning "=> false"
Return the port number this server is configured to listen on.
(HttpServer new: 8080) port "=> 8080"
Register a route handler. The handler block receives an HttpRequest and should return an HttpResponse or a string. If method is empty, all HTTP methods are accepted. Returns self for chaining.
server route: '/api/data' method: 'GET' handler: [:req |
HttpResponse new: 200 body: 'OK'
]
Register a static file handler. Requests matching urlPath will be served from dirPath on the filesystem. Returns self for chaining.
server serveStatic: '/static/' from: './public'
Start the server. This blocks the current process until the server is stopped. Returns self on clean shutdown, or nil on error.
| server <HttpServer> |
server := HttpServer new: 8080.
[server start] fork.
"Server is now running in background"
Stop the server gracefully with a 5-second shutdown timeout. Returns self.
server stop