#net/http
Xu 0.16.0 API
import: #net/http
counts: 23 functions, 68 methods, 10 types, 0 constants, 0 method sets
Serve a text response
Use net/http to serve an HTTP text response from a request handler.
This native example listens on loopback; stop it with Ctrl-C. In another terminal run curl http://127.0.0.1:8080/.
Save the complete program as main.xu and run xu run main.xu locally.
@main
#net/http
fn hello(c http.Context) {
c.text(200, "hello\n") >>> (err) {
println(err.msg())
<<
}
}
fn main() int {
http.listen_and_serve_handler("127.0.0.1:8080", hello) >>> (err) {
println(err.msg())
<< 1
}
<< 0
}
Expected response body: hello followed by a newline.
Servers dispatch complete requests concurrently with bounded connection intake, buffers and timeouts. Handlers may overlap; synchronize shared mutable state and transfer request ownership explicitly. Use server_options() for defaults and serve_with_options to configure limits. Short response writes are retried. Idle or incomplete requests do not occupy a handler indefinitely.
Examples · API declarations
Examples
These sources come from the official examples repository and can be copied or downloaded. Run them with a local Xu SDK in the complete project; network, database, and desktop examples require the corresponding services or assets.
12_file_server/main.xu
Required SDK: Xu 0.8.13-dev.7 · Complete project · Download source
@main
#net/http
// Go:
// http.ListenAndServe(":8080", http.FileServer(http.Dir(".")))
// Xu:
// http.listen_and_serve("127.0.0.1:8080", ".")
//
// 参数:要对外的目录。默认本示例的 www/(从仓库根运行)。
fn main() int {
$root := "examples/12_file_server/www"
av := args()
if av.len >= 2 {
root = av[1] + ""
}
println("FileServer " + root)
println("http://127.0.0.1:8080")
http.listen_and_serve("127.0.0.1:8080", root) >>> (err) {
println(err.msg())
<< 1
}
<< 0
}
13_http_context/main.xu
Required SDK: Xu 0.8.13-dev.7 · Complete project · Download source
@main
#net/http
// 写法 C — 请求上下文(Go Handler / HandlerFunc)。
//
// Go:
// func hello(w http.ResponseWriter, r *http.Request) {
// fmt.Fprint(w, "hello")
// }
// http.ListenAndServe(":8080", http.HandlerFunc(hello))
//
// Xu: w 和 r 收成一个 Context。
fn app(c http.Context) {
p := c.path()
if p == "/" || p == "/index.html" {
page := "<!doctype html><html><head><meta charset=\"utf-8\"><title>Xu</title></head>" +
"<body><h1>Context</h1>" +
"<p><a href=\"/hello\">/hello</a> · <a href=\"/health\">/health</a></p>" +
"<p>POST /echo</p></body></html>"
c.html(200, page) >>> (err) { << }
<<
}
if p == "/hello" {
c.text(200, "hello, xu\n") >>> (err) { << }
<<
}
if p == "/health" {
c.text(200, "ok\n") >>> (err) { << }
<<
}
if p == "/echo" {
m := c.method()
if m != "POST" && m != "PUT" {
c.text(405, "method not allowed\n") >>> (err) { << }
<<
}
b := c.body()
c.text(200, b) >>> (err) { << }
<<
}
miss := "not found: " + p + "\n"
c.text(404, miss) >>> (err) { << }
}
fn main() int {
println("http://127.0.0.1:18081")
http.listen_and_serve_handler("127.0.0.1:18081", app) >>> (err) {
println(err.msg())
<< 1
}
<< 0
}
16_ui_webview/xu_design_system/server.xu
Required SDK: Xu 0.10.11 · Complete project · Download source
@main
#net/http
// Xu Design System & VI Specification 官方本地 HTTP 服务
// 运行指令:
// ./xu_design_server.xin [--addr 127.0.0.1:8088] [--root <www-dir>]
// 位置参数仍兼容旧形式:<port> <www-dir>。
fn main() int {
$addr := "127.0.0.1:8088"
$root := "examples/16_ui_webview/xu_design_system/www"
av := args()
$i := 1
while i < av.len {
arg := av[i] + ""
if arg == "--help" || arg == "-h" {
println("Xu Design System HTTP server")
println("usage: xu_design_server [--addr HOST:PORT] [--root DIR]")
println("legacy: xu_design_server PORT DIR")
<< 0
}
if arg == "--addr" {
if i + 1 >= av.len {
println("missing value for --addr")
<< 2
}
addr = av[i + 1] + ""
i = i + 2
->
}
if arg == "--root" {
if i + 1 >= av.len {
println("missing value for --root")
<< 2
}
root = av[i + 1] + ""
i = i + 2
->
}
// Preserve the original positional interface: port, then root.
if i == 1 {
addr = "127.0.0.1:" + arg
} else if i == 2 {
root = arg
} else {
println("unknown argument: " + arg)
<< 2
}
i = i + 1
}
println("==================================================================")
println(" __ __ _ _ ")
println(" \\ \\/ / | | | | ⚡ Xu Official HTTP Server (Design System)")
println(" \\ / | | | | 🔥 Rock-Solid Ownership · Supersonic AOT")
println(" / \\ | |_| | 🌐 Serving: " + root)
println(" /_/\\_\\ \\___/ 🔗 Local URL: http://" + addr + "/")
println("==================================================================")
println("Press Ctrl+C to stop server.\n")
http.listen_and_serve(addr, root) >>> (err) {
println("Server error: " + err.msg())
<< 1
}
<< 0
}
More related examples
-
11_http_server/main.xu
Required SDK: Xu 0.8.13-dev.7 · Complete project · Download source
@main
#net
#net/http
// 自己 listen / accept / 按路径处理(Go HandleFunc 那种)。
// GET / HTML
// GET /hello text
// GET /health ok
// POST /echo 回显 body
// 静态目录见 12file_server;Handler 上下文见 13http_context。
fn path_only(p string) string {
$i := 0
while i < p.len {
if (p[i] & 255) == 63 {
<< p[0:i]
}
i = i + 1
}
<< p + ""
}
fn write_http(fd int, status int, ctype string, body string) int {
$reason := "OK"
if status == 404 {
reason = "Not Found"
}
if status == 400 {
reason = "Bad Request"
}
if status == 405 {
reason = "Method Not Allowed"
}
$out := "HTTP/1.1 " + str(status) + " " + reason + "\r\n"
out = out + "Content-Type: " + ctype + "\r\n"
out = out + "Content-Length: " + str(body.len) + "\r\n"
out = out + "Connection: close\r\n"
out = out + "\r\n"
out = out + body
<< net.conn_write(fd, &out) >>> (err) { >> err }
}
fn index_page() string {
<< "<!doctype html><html><head><meta charset=\"utf-8\"><title>Xu HTTP</title>" +
"<style>body{font-family:ui-sans-serif,system-ui,sans-serif;max-width:40rem;" +
"margin:3rem auto;padding:0 1.5rem;background:#0f1419;color:#e7ecf1}" +
"h1{font-weight:650;letter-spacing:-.03em}a{color:#7dd3fc}" +
"code{background:#1b2430;padding:.15rem .4rem;border-radius:4px}" +
"ul{line-height:1.8}</style></head><body>" +
"<h1>Xu HTTP</h1>" +
"<p>自己 <code>listen</code> / <code>accept</code> / 按 path 分支。</p>" +
"<ul>" +
"<li><a href=\"/hello\">/hello</a></li>" +
"<li><a href=\"/health\">/health</a></li>" +
"<li>POST <code>/echo</code></li>" +
"</ul></body></html>"
}
fn handle(fd int) {
$req := http.new_request()
req.read(fd) >>> (err) {
msg := err.msg()
write_http(fd, 400, "text/plain; charset=utf-8", msg) >>> (e2) { << }
net.conn_close(fd) >>> (e3) { << }
<<
}
method := req.method()
raw_path := req.path()
path := path_only(raw_path)
if path == "/" || path == "/index.html" {
page := index_page()
write_http(fd, 200, "text/html; charset=utf-8", page) >>> (err) { << }
net.conn_close(fd) >>> (err) { << }
<<
}
if path == "/hello" {
body := "hello, xu\n"
write_http(fd, 200, "text/plain; charset=utf-8", body) >>> (err) { << }
net.conn_close(fd) >>> (err) { << }
<<
}
if path == "/health" {
body := "ok\n"
write_http(fd, 200, "text/plain; charset=utf-8", body) >>> (err) { << }
net.conn_close(fd) >>> (err) { << }
<<
}
if path == "/echo" {
if method != "POST" && method != "PUT" {
body := "method not allowed\n"
write_http(fd, 405, "text/plain; charset=utf-8", body) >>> (err) { << }
net.conn_close(fd) >>> (err) { << }
<<
}
echo := req.body()
write_http(fd, 200, "text/plain; charset=utf-8", echo) >>> (err) { << }
net.conn_close(fd) >>> (err) { << }
<<
}
miss := "not found: " + path + "\n"
write_http(fd, 404, "text/plain; charset=utf-8", miss) >>> (err) { << }
net.conn_close(fd) >>> (err) { << }
}
fn main() int {
$s := http.new_server()
s.listen("127.0.0.1:18080") >>> (err) {
println(err.msg())
<< 1
}
println("http://127.0.0.1:18080")
$running := true
while running {
fd := s.accept() >>> (err) {
->
}
// The deployable example uses the portable, deterministic path on all
// hosts. The stackful `xu` scheduler has dedicated stress fixtures,
// but it is not yet a production request-execution primitive; keeping
// request handling sequential also gives local and server builds the
// same lifecycle contract. Put TLS, limits and concurrency in the
// reverse proxy until that runtime gate is closed.
handle(fd)
}
<< 0
}
API declarations
struct Response
pub struct Response {
pub status_code int
pub status string
pub headers string
pub body string
pub sticky string
}
Purpose
Http Server response payload containing status, headers, and body.
Public fields
status_code int- field (int)
status string- field (string)
headers string- field (string)
body string- body
sticky string- field (string)
new_response
pub fn new_response() Response
Purpose
Construct response.
Parameters
No arguments are required.
Returns
Response — a value of this type
(Response) status_code
pub fn (r Response) status_code() int
Purpose
Operation on Response: status code.
Parameters
r Response- The
Response instance used by this call (value receiver).
Returns
int — a value of this type
(Response) status
pub fn (r Response) status() string
Purpose
Execute status on Response.
Parameters
r Response- The
Response instance used by this call (value receiver).
Returns
string — result string
(Response) body
pub fn (r Response) body() string
Purpose
Execute body on Response.
Parameters
r Response- The
Response instance used by this call (value receiver).
Returns
string — result string
struct Request
pub struct Request {
pub method string
pub path string
pub headers string
pub body string
pub sticky string
pub remote_addr string
}
Purpose
Structure encapsulating method, path, headers, body, sticky.
Public fields
method string- field (string)
path string- filesystem path
headers string- field (string)
body string- body
sticky string- field (string)
remote_addr string- field (string)
new_request
pub fn new_request() Request
Purpose
Construct request.
Parameters
No arguments are required.
Returns
Request — a value of this type
See usage example
(Request) method
pub fn (r Request) method() string
Purpose
Execute method on Request.
Parameters
r Request- The
Request instance used by this call (value receiver).
Returns
string — result string
(Request) path
pub fn (r Request) path() string
Purpose
Execute path on Request.
Parameters
r Request- The
Request instance used by this call (value receiver).
Returns
string — result string
(Request) body
pub fn (r Request) body() string
Purpose
Execute body on Request.
Parameters
r Request- The
Request instance used by this call (value receiver).
Returns
string — result string
(Request) user_agent
pub fn (r Request) user_agent() string
Purpose
Operation on Request: user agent.
Parameters
r Request- The
Request instance used by this call (value receiver).
Returns
string — result string
(Request) host
pub fn (r Request) host() string
Purpose
Operation on Request: host.
Parameters
r Request- The
Request instance used by this call (value receiver).
Returns
string — result string
(Request) remote_addr
pub fn (r Request) remote_addr() string
Purpose
Operation on Request: remote address.
Parameters
r Request- The
Request instance used by this call (value receiver).
Returns
string — result string
(Request) query_value
pub fn (r Request) query_value(key string) string
Purpose
Operation on Request: query value.
Parameters
r Request- The
Request instance used by this call (value receiver).
key string- key (string)
Returns
string — result string
(Request) form_value
pub fn (r Request) form_value(key string) string
Purpose
Operation on Request: form value.
Parameters
r Request- The
Request instance used by this call (value receiver).
key string- key (string)
Returns
string — result string
struct Server
pub struct Server {
pub lfd int
pub laddr string
}
Purpose
Structure encapsulating lfd, laddr.
Public fields
lfd int- field (int)
laddr string- field (string)
new_server
pub fn new_server() Server
Purpose
Construct server.
Parameters
No arguments are required.
Returns
Server — a value of this type
See usage example
(Server) clone
pub fn (s Server) clone() Server
Purpose
Operation on Server: copy into a new independent string.
Parameters
s Server- The
Server instance used by this call (value receiver).
Returns
Server — a value of this type
($&Server) listen
pub fn (s $&Server) listen(addr string) int
Purpose
Operation on $&Server: listen for connections. Throws on failure; handle the error or propagate it to the caller.
Parameters
s $&Server- The
Server instance used by this call (exclusive borrow).
addr string- address (string)
Returns
int — a value of this type
(Server) addr
pub fn (s Server) addr() string
Purpose
Operation on Server: address.
Parameters
s Server- The
Server instance used by this call (value receiver).
Returns
string — result string
(Server) accept
pub fn (s Server) accept() int
Purpose
Operation on Server: accept one connection. Throws on failure; handle the error or propagate it to the caller.
Parameters
s Server- The
Server instance used by this call (value receiver).
Returns
int — a value of this type
($&Server) close
pub fn (s $&Server) close() int
Purpose
Operation on $&Server: close the resource.
Parameters
s $&Server- The
Server instance used by this call (exclusive borrow).
Returns
int — a value of this type
($&Server) shutdown
pub fn (s $&Server) shutdown() int
Purpose
Execute shutdown on $&Server.
Parameters
s $&Server- The
Server instance used by this call (exclusive borrow).
Returns
int — a value of this type
status_text
pub fn status_text(code int) string
Purpose
Status text.
Parameters
code int- code (int)
Returns
string — result string
($&Response) get
pub fn (r $&Response) get(url string) int
Purpose
Execute get on $&Response. Throws on failure; handle the error or propagate it to the caller.
Parameters
r $&Response- The
Response instance used by this call (exclusive borrow).
url string- url (string)
Returns
int — a value of this type
($&Response) post
pub fn (r $&Response) post(url string, body &string) int
Purpose
Execute post on $&Response. Throws on failure; handle the error or propagate it to the caller.
Parameters
r $&Response- The
Response instance used by this call (exclusive borrow).
url string- url (string)
body &string- body (read-only borrow; caller keeps the original; type &string)
Returns
int — a value of this type
(Response) cookies
pub fn (r Response) cookies() []Cookie
Purpose
Execute cookies on Response.
Parameters
r Response- The
Response instance used by this call (value receiver).
Returns
[]Cookie — slice result
struct Client
pub struct Client {
pub jar cookiejar.Jar
pub jar_on int
pub insecure_skip_verify bool
pub timeout_ns int
pub max_redirects int
pub max_response_bytes int
}
Purpose
Http Client session maintaining connection and operations.
Public fields
jar cookiejar.Jar- field (cookiejar.Jar)
jar_on int- field (int)
insecure_skip_verify bool- field (bool)
timeout_ns int- One budget for HTTP/TLS I/O and redirects; 0 disables it. Synchronous DNS and Linux TCP connect still need cancellable platform adapters.
max_redirects int- Negative returns redirect responses unchanged; zero uses the default 10.
max_response_bytes int- Positive overrides the default 10 MiB buffered response limit, including headers.
new_client
pub fn new_client() Client
Purpose
Construct client.
Parameters
No arguments are required.
Returns
Client — a value of this type
($&Client) set_jar
pub fn (c $&Client) set_jar(j cookiejar.Jar)
Purpose
Operation on $&Client: set jar.
Parameters
c $&Client- The
Client instance used by this call (exclusive borrow).
j cookiejar.Jar- index (cookiejar.Jar)
Returns
This call does not return a value.
($&Client) set_timeout
pub fn (c $&Client) set_timeout(ns int)
Purpose
Operation on $&Client: set timeout.
Parameters
c $&Client- The
Client instance used by this call (exclusive borrow).
ns int- ns (int)
Returns
This call does not return a value.
($&Client) do
pub fn (c $&Client) do(method string, raw_url string, body &string) Response
Purpose
Execute do on $&Client. Throws on failure; handle the error or propagate it to the caller.
Parameters
c $&Client- The
Client instance used by this call (exclusive borrow).
method string- method (string)
raw_url string- raw_url (string)
body &string- body (read-only borrow; caller keeps the original; type &string)
Returns
Response — a value of this type
($&Client) get
pub fn (c $&Client) get(raw_url string) Response
Purpose
Execute get on $&Client. Throws on failure; handle the error or propagate it to the caller.
Parameters
c $&Client- The
Client instance used by this call (exclusive borrow).
raw_url string- raw_url (string)
Returns
Response — a value of this type
($&Client) post
pub fn (c $&Client) post(raw_url string, body &string) Response
Purpose
Execute post on $&Client. Throws on failure; handle the error or propagate it to the caller.
Parameters
c $&Client- The
Client instance used by this call (exclusive borrow).
raw_url string- raw_url (string)
body &string- body (read-only borrow; caller keeps the original; type &string)
Returns
Response — a value of this type
($&Client) post_form
pub fn (c $&Client) post_form(raw_url string, data &url.Query) Response
Purpose
Operation on $&Client: post form. Throws on failure; handle the error or propagate it to the caller.
Parameters
c $&Client- The
Client instance used by this call (exclusive borrow).
raw_url string- raw_url (string)
data &url.Query- data (read-only borrow; caller keeps the original; type &url.Query)
Returns
Response — a value of this type
($&Request) read
pub fn (req $&Request) read(fd int) int
Purpose
Operation on $&Request: read up to max bytes. Throws on failure; handle the error or propagate it to the caller.
Parameters
req $&Request- The
Request instance used by this call (exclusive borrow).
fd int- file descriptor (int)
Returns
int — a value of this type
($&Request) read_timeout
pub fn (req $&Request) read_timeout(fd int, timeout_ns int) int
Purpose
read_timeout applies one absolute budget to all headers and body reads. A zero timeout preserves the caller-owned blocking read contract. Throws on failure; handle the error or propagate it to the caller.
Parameters
req $&Request- The
Request instance used by this call (exclusive borrow).
fd int- file descriptor (int)
timeout_ns int- timeout in nanoseconds (int)
Returns
int — a value of this type
write_response
pub fn write_response(fd int, status_code int, body &string) int
Purpose
Write response. Throws on failure; handle the error or propagate it to the caller.
Parameters
fd int- file descriptor (int)
status_code int- status_code (int)
body &string- body (read-only borrow; caller keeps the original; type &string)
Returns
int — a value of this type
write
pub fn write(fd int, status_code int, content_type string, body &string) int
Purpose
write is the typed-body form of a one-shot HTTP/1.1 response ( http.ResponseWriter WriteHeader+Write, Connection: close).
Parameters
fd int- file descriptor (int)
status_code int- status_code (int)
content_type string- content_type (string)
body &string- body (read-only borrow; caller keeps the original; type &string)
Returns
int — bytes written
(&Client) has_idle_connection
pub fn (c &Client) has_idle_connection() bool
Purpose
Operation on &Client: whether it has idle connection.
Parameters
c &Client- The
Client instance used by this call (borrow).
Returns
bool — true or false
($&Client) close_idle_connections
pub fn (c $&Client) close_idle_connections()
Purpose
Operation on $&Client: close idle connections.
Parameters
c $&Client- The
Client instance used by this call (exclusive borrow).
Returns
This call does not return a value.
struct Context
pub struct Context {
pub fd int
pub req Request
}
Purpose
Structure encapsulating fd, req.
Public fields
fd int- file descriptor
req Request- field (Request)
See usage example
(Context) method
pub fn (c Context) method() string
Purpose
Execute method on Context.
Parameters
c Context- The
Context instance used by this call (value receiver).
Returns
string — result string
(Context) raw_path
pub fn (c Context) raw_path() string
Purpose
Operation on Context: raw path.
Parameters
c Context- The
Context instance used by this call (value receiver).
Returns
string — result string
(Context) path
pub fn (c Context) path() string
Purpose
Execute path on Context.
Parameters
c Context- The
Context instance used by this call (value receiver).
Returns
string — result string
(Context) query
pub fn (c Context) query() string
Purpose
Execute query on Context.
Parameters
c Context- The
Context instance used by this call (value receiver).
Returns
string — result string
(Context) remote_addr
pub fn (c Context) remote_addr() string
Purpose
Operation on Context: remote address.
Parameters
c Context- The
Context instance used by this call (value receiver).
Returns
string — result string
(Context) query_value
pub fn (c Context) query_value(key string) string
Purpose
Operation on Context: query value.
Parameters
c Context- The
Context instance used by this call (value receiver).
key string- key (string)
Returns
string — result string
(Context) form_value
pub fn (c Context) form_value(key string) string
Purpose
Operation on Context: form value.
Parameters
c Context- The
Context instance used by this call (value receiver).
key string- key (string)
Returns
string — result string
(Context) body
pub fn (c Context) body() string
Purpose
Execute body on Context.
Parameters
c Context- The
Context instance used by this call (value receiver).
Returns
string — result string
(Context) persistent
pub fn (c Context) persistent() bool
Purpose
persistent reports whether this request's protocol permits connection reuse.
Parameters
c Context- The
Context instance used by this call (value receiver).
Returns
bool — true or false
(Context) hijack
pub fn (c Context) hijack() int
Purpose
hijack hands socket ownership to the caller and prevents the server from re-arming or closing c.fd after the handler returns.
Parameters
c Context- The
Context instance used by this call (value receiver).
Returns
int — a value of this type
(Context) text
pub fn (c Context) text(status int, body string) int
Purpose
Operation on Context: return the current text. Throws on failure; handle the error or propagate it to the caller.
Parameters
c Context- The
Context instance used by this call (value receiver).
status int- status (int)
body string- body (string)
Returns
int — a value of this type
(Context) html
pub fn (c Context) html(status int, body string) int
Purpose
Execute html on Context. Throws on failure; handle the error or propagate it to the caller.
Parameters
c Context- The
Context instance used by this call (value receiver).
status int- status (int)
body string- body (string)
Returns
int — a value of this type
(Context) bytes
pub fn (c Context) bytes(status int, content_type string, body string) int
Purpose
Operation on Context: return the buffered bytes. Throws on failure; handle the error or propagate it to the caller.
Parameters
c Context- The
Context instance used by this call (value receiver).
status int- status (int)
content_type string- content_type (string)
body string- body (string)
Returns
int — a value of this type
(&Server) serve
pub fn (s &Server) serve(handle fn(Context)) int
Purpose
serve is (*Server).Serve for an already-listening Server. close from another goroutine unblocks Accept and ends the loop.
Parameters
s &Server- The
Server instance used by this call (borrow).
handle fn(Context)- handle (function value; type fn(Context))
Returns
int — a value of this type
listen_and_serve_handler
pub fn listen_and_serve_handler(addr string, handle fn(Context)) int
Purpose
listen_and_serve_handler is ListenAndServe(addr, HandlerFunc(fn)). Throws on failure; handle the error or propagate it to the caller.
Parameters
addr string- address (string)
handle fn(Context)- handle (function value; type fn(Context))
Returns
int — a value of this type
See usage example
struct Cookie
pub struct Cookie {
pub name string
pub value string
pub path string
pub domain string
pub expires string
pub max_age int
pub secure bool
pub http_only bool
pub same_site string
}
Purpose
Structure encapsulating name, value, path, domain, expires.
Public fields
name string- name
value string- field (string)
path string- filesystem path
domain string- field (string)
expires string- field (string)
max_age int- field (int)
secure bool- field (bool)
http_only bool- field (bool)
same_site string- field (string)
parse_cookie
pub fn parse_cookie(line &string) []Cookie
Purpose
Parse as cookie. Throws on failure; handle the error or propagate it to the caller.
Parameters
line &string- line (read-only borrow; caller keeps the original; type &string)
Returns
[]Cookie — slice result
parse_set_cookie
pub fn parse_set_cookie(line &string) Cookie
Purpose
Parse as set cookie. Throws on failure; handle the error or propagate it to the caller.
Parameters
line &string- line (read-only borrow; caller keeps the original; type &string)
Returns
Cookie — a value of this type
(Cookie) to_string
pub fn (c Cookie) to_string() string
Purpose
Operation on Cookie: convert to string.
Parameters
c Cookie- The
Cookie instance used by this call (value receiver).
Returns
string — result string
(Request) cookies
pub fn (r Request) cookies() []Cookie
Purpose
Execute cookies on Request.
Parameters
r Request- The
Request instance used by this call (value receiver).
Returns
[]Cookie — slice result
struct FileServer
pub struct FileServer {
pub root string
}
Purpose
Structure encapsulating root.
Public fields
root string- field (string)
file_server
pub fn file_server(root string) FileServer
Purpose
File server.
Parameters
root string- root (string)
Returns
FileServer — a value of this type
listen_and_serve
pub fn listen_and_serve(addr string, root string) int
Purpose
Listen and serve. Throws on failure; handle the error or propagate it to the caller.
Parameters
addr string- address (string)
root string- root (string)
Returns
int — a value of this type
See usage example
(FileServer) serve
pub fn (fs FileServer) serve(fd int)
Purpose
Execute serve on FileServer.
Parameters
fs FileServer- The
FileServer instance used by this call (value receiver).
fd int- file descriptor (int)
Returns
This call does not return a value.
(FileServer) serve_context
pub fn (fs FileServer) serve_context(c Context)
Purpose
Operation on FileServer: serve context.
Parameters
fs FileServer- The
FileServer instance used by this call (value receiver).
c Context- byte or character code (Context)
Returns
This call does not return a value.
serve_file
pub fn serve_file(fd int, name string) int
Purpose
Serve file. Throws on failure; handle the error or propagate it to the caller.
Parameters
fd int- file descriptor (int)
name string- name (string)
Returns
int — a value of this type
struct ServeMux
pub struct ServeMux {
pub patterns []string
pub handlers []fn(Context)
}
Purpose
Structure encapsulating patterns, handlers.
Public fields
patterns []string- field ([]string)
handlers []fn(Context)- field ([]fn(Context))
new_serve_mux
pub fn new_serve_mux() ServeMux
Purpose
Construct serve mux.
Parameters
No arguments are required.
Returns
ServeMux — a value of this type
($&ServeMux) handle_func
pub fn (m $&ServeMux) handle_func(pattern string, handler fn(Context))
Purpose
Operation on $&ServeMux: handle callback.
Parameters
m $&ServeMux- The
ServeMux instance used by this call (exclusive borrow).
pattern string- pattern (string)
handler fn(Context)- handler (function value; type fn(Context))
Returns
This call does not return a value.
(&ServeMux) serve_http
pub fn (m &ServeMux) serve_http(c Context)
Purpose
Operation on &ServeMux: serve http.
Parameters
m &ServeMux- The
ServeMux instance used by this call (borrow).
c Context- byte or character code (Context)
Returns
This call does not return a value.
($&Client) set_download_progress
pub fn (c $&Client) set_download_progress(report fn(int, int))
Purpose
Observe successful response-body reads, at most every 100 ms plus the initial, first payload and final counts. total is -1 for chunked or close-delimited bodies. The callback runs synchronously; it must not re-enter this client.
Parameters
c $&Client- The
Client instance used by this call (exclusive borrow).
report fn(int, int)- report (function value; type fn(int, int))
Returns
This call does not return a value.
(Response) reusable
pub fn (r Response) reusable(method string) bool
Purpose
Call only after read_response has validated and consumed the entire message.
Parameters
r Response- The
Response instance used by this call (value receiver).
method string- method (string)
Returns
bool — true or false
read_response
pub fn read_response(fd int, method string) Response
Purpose
Read one response on a caller-owned socket. Serial keep-alive requests are supported; pipelined requests require a persistent buffered transport. Throws on failure; handle the error or propagate it to the caller.
Parameters
fd int- file descriptor (int)
method string- method (string)
Returns
Response — a value of this type
struct ServerOptions
pub struct ServerOptions {
pub read_timeout_ns int
pub write_timeout_ns int
pub max_connections int
pub max_header_bytes int
pub max_body_bytes int
pub max_buffer_bytes int
pub max_active_handlers int
pub workers int
pub sync_handlers bool
}
Purpose
Read time is an absolute request-intake budget. Write time bounds blocking response I/O. max_buffer_bytes bounds the reserved pending-input buffers in each loop, including concurrent old and new buffers during growth. The single read chunk and dispatched handler input have separate lifetimes. max_connections bounds accepted client sockets.
Public fields
read_timeout_ns int- field (int)
write_timeout_ns int- field (int)
max_connections int- field (int)
max_header_bytes int- field (int)
max_body_bytes int- field (int)
max_buffer_bytes int- field (int)
max_active_handlers int- Maximum number of handler coroutines running concurrently. Defaults to 256; raise for handlers that block on I/O (database, RPC). Has no effect when sync_handlers is true.
workers int- Number of event-loop worker tasks. Defaults to 1. When > 1, multiple independent event sets share the listener to distribute connection intake across CPU cores (Nginx multi-worker model).
sync_handlers bool- Runs handlers directly on the event-loop owner instead of
xu. Defaults to false; enable only when handlers do not block or wait for I/O.
server_options
pub fn server_options() ServerOptions
Purpose
Defaults: 10-second I/O budgets, 110,000 connections with the event-set backend (256 with the portable legacy backend), 64 KiB headers, 10 MiB bodies, 32 MiB total pending input, and 256 concurrent handlers.
Parameters
No arguments are required.
Returns
ServerOptions — a value of this type
serve_listener
pub fn serve_listener(lfd int, handle fn(Context)) int
Purpose
All server helpers share the same incremental intake. Idle and partial requests stay here and never consume a worker waiting for socket input. Complete requests run in a bounded worker set; handlers must synchronize shared state. Retains the legacy integer status contract (1 on invalid configuration).
Parameters
lfd int- lfd (int)
handle fn(Context)- handle (function value; type fn(Context))
Returns
int — a value of this type
(&Server) serve_with_options
pub fn (s &Server) serve_with_options(handle fn(Context), options ServerOptions) int
Purpose
Serves concurrently with validated positive limits. Invalid options throw. Throws on failure; handle the error or propagate it to the caller.
Parameters
s &Server- The
Server instance used by this call (borrow).
handle fn(Context)- handle (function value; type fn(Context))
options ServerOptions- options (ServerOptions)
Returns
int — a value of this type
serve_listener_with_options
pub fn serve_listener_with_options(lfd int, handle fn(Context), options ServerOptions) int
Purpose
Serve listener with options. Throws on failure; handle the error or propagate it to the caller.
Parameters
lfd int- lfd (int)
handle fn(Context)- handle (function value; type fn(Context))
options ServerOptions- options (ServerOptions)
Returns
int — a value of this type
detect_content_type
pub fn detect_content_type(data &string) string
Purpose
Detect MIME Content-Type by sniffing the first 512 bytes.
Parameters
data &string- data (read-only borrow; caller keeps the original; type &string)
Returns
string — result string