data Server
An HTTP/1.1 server (II.1 std.http): keep-alive, chunked request bodies, Expect: 100-continue, size and time limits,
streamed responses (Reply.stream, Reply.sse), WebSocket upgrades (Reply.websocket) and graceful shutdown.
let router = Router.new().get("/hello/:name", (req: Request) => Reply.text("hi {req.param("name") ?? "?"}"))
let srv = Server.bind(ServerConfig{ port: 8080 })?
srv.serve(router)?serve runs the accept loop in the calling task; every connection is served by its own task of a scope, so the call returns
after shutdown() (from another task or a handler) once the connections have drained, or when the node starts to drain.
Example:
use std.http { Server, ServerConfig, ServerHandle, Router, Request, Reply, Client, Header, HttpConfig, Response, Middleware, Next, withMiddleware, requireHeader, logRequests, timing, WebSocket, WsConfig, SseWriter, BodyWriter, chunks }
fn body(req: Request) -> str {
match req.text() {
str t => t
DecodeError _ => ""
}
}
fn run() -> () | NetError | DecodeError | Panicked net, io, time {
let srv = Server.bind(ServerConfig{ port: 0, followNode: false })?
defer srv.close()
let stop = srv.handle()
let base = "http://127.0.0.1:{srv.port()}"
let router = Router.new().get("/", (req: Request) => Reply.text("welcome"))
scope {
spawn stop.serve(router)
print((Client.get("{base}/")?).text()?)
stop.shutdown()
()
}?
}
fn main() io, net, time {
match run() {
NetError _ => print("net error")
DecodeError _ => print("decode error")
Panicked _ => print("panicked")
_ => {}
}
}Output
welcome
@must_close
pub(api) data ServerThread safety. `serve` runs the accept loop in the calling task; every connection has a task of its own. Stop it from elsewhere with a `ServerHandle`.
Since. 1.0.0-beta
Methods
bind | (cfg: ServerConfig) -> Server | NetError netBinds and listens. |
handle | () -> ServerHandleA token for shutdown() that handlers and other tasks can hold. |
port | () -> u16The port the server listens on (useful with port |
scheme | () -> strhttp or https. |
connections | () -> i64Open connections (idle keep-alive ones included). |
accepted | () -> i64Connections accepted so far. |
requests | () -> i64Requests read so far. |
panics | () -> i64Requests whose handler panicked (each was answered with 500 if its answer had not begun, D-3994). |
shutdown | ()Starts the graceful shutdown |
serveWith | (handler: Handler) -> () | NetError net, io, timeServes requests with handler until shutdown() (or the node drains). |
serve | (router: Router) -> () | NetError net, io, timeServes requests with a Router. |
close | ()Stops listening and releases the server (after serve returned). |
Defined in: std/http/http.oxl:3977