OxL Справочник OxL
РусскийEnglish

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.

oxl
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:

oxl✓ проверяется в CI
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")
    _ => {}
  }
}
Вывод
welcome
@must_close
pub(api) data Server

Потокобезопасность. `serve` runs the accept loop in the calling task; every connection has a task of its own. Stop it from elsewhere with a `ServerHandle`.

С версии. 1.0.0-beta

Методы

bind(cfg: ServerConfig) -> Server | NetError net
Binds and listens.
handle() -> ServerHandle
A token for shutdown() that handlers and other tasks can hold.
port() -> u16
The port the server listens on (useful with port
scheme() -> str
http or https.
connections() -> i64
Open connections (idle keep-alive ones included).
accepted() -> i64
Connections accepted so far.
requests() -> i64
Requests read so far.
panics() -> i64
Requests 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, time
Serves requests with handler until shutdown() (or the node drains).
serve(router: Router) -> () | NetError net, io, time
Serves requests with a Router.
close()
Stops listening and releases the server (after serve returned).

Определено в: std/http/http.oxl:3977

См. также