XU XUv0.16.0

#net/http

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

XuLocal SDK example
@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

XuLocal SDK example
@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

XuLocal SDK example
@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

    XuLocal SDK example
    @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

XuAPI
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

XuAPI
pub fn new_response() Response

Purpose

Construct response.

Parameters

No arguments are required.

Returns

Response — a value of this type

(Response) status_code

XuAPI
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

XuAPI
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

XuAPI
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

(Response) header

XuAPI
pub fn (r Response) header(name string) string

Purpose

Execute header on Response.

Parameters

r Response
The Response instance used by this call (value receiver).
name string
name (string)

Returns

string — result string

struct Request

XuAPI
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

XuAPI
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

XuAPI
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

XuAPI
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

XuAPI
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) header

XuAPI
pub fn (r Request) header(name string) string

Purpose

Execute header on Request.

Parameters

r Request
The Request instance used by this call (value receiver).
name string
name (string)

Returns

string — result string

(Request) user_agent

XuAPI
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

XuAPI
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

XuAPI
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

XuAPI
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

XuAPI
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

XuAPI
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

XuAPI
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

XuAPI
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

XuAPI
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

XuAPI
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

XuAPI
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

XuAPI
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

XuAPI
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

XuAPI
pub fn status_text(code int) string

Purpose

Status text.

Parameters

code int
code (int)

Returns

string — result string

($&Response) get

XuAPI
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

XuAPI
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

XuAPI
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

XuAPI
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

XuAPI
pub fn new_client() Client

Purpose

Construct client.

Parameters

No arguments are required.

Returns

Client — a value of this type

($&Client) set_jar

XuAPI
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

XuAPI
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_extra

XuAPI
pub fn (c $&Client) do_extra(method string, raw_url string, extra string, body &string) Response

Purpose

Operation on $&Client: do extra. 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)
extra string
extra (string)
body &string
body (read-only borrow; caller keeps the original; type &string)

Returns

Response — a value of this type

($&Client) get_extra

XuAPI
pub fn (c $&Client) get_extra(raw_url string, extra string) Response

Purpose

Operation on $&Client: read extra. 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)
extra string
extra (string)

Returns

Response — a value of this type

($&Client) do

XuAPI
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

XuAPI
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

XuAPI
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

XuAPI
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

XuAPI
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

XuAPI
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

XuAPI
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

XuAPI
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

XuAPI
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

XuAPI
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

XuAPI
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

XuAPI
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

XuAPI
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

XuAPI
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

XuAPI
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) header

XuAPI
pub fn (c Context) header(name string) string

Purpose

Execute header on Context.

Parameters

c Context
The Context instance used by this call (value receiver).
name string
name (string)

Returns

string — result string

(Context) remote_addr

XuAPI
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

XuAPI
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

XuAPI
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

XuAPI
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

XuAPI
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

XuAPI
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

XuAPI
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) text_extra

XuAPI
pub fn (c Context) text_extra(status int, extra string, body string) int

Purpose

Operation on Context: text extra. 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)
extra string
extra (string)
body string
body (string)

Returns

int — a value of this type

(Context) html

XuAPI
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

XuAPI
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

(Context) write_extra

XuAPI
pub fn (c Context) write_extra(status int, content_type string, extra string, body &string) int

Purpose

Operation on Context: write extra. 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)
extra string
extra (string)
body &string
body (read-only borrow; caller keeps the original; type &string)

Returns

int — a value of this type

(&Server) serve

XuAPI
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

XuAPI
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

(Request) cookies

XuAPI
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

XuAPI
pub struct FileServer {
    pub root string
}

Purpose

Structure encapsulating root.

Public fields

root string
field (string)

file_server

XuAPI
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

XuAPI
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

XuAPI
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

XuAPI
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

XuAPI
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 Header

XuAPI
pub struct Header {
    pub keys []string
    pub vals []string
}

Purpose

Http Metadata header descriptor structure.

Public fields

keys []string
field ([]string)
vals []string
field ([]string)

new_header

XuAPI
pub fn new_header() Header

Purpose

Construct header.

Parameters

No arguments are required.

Returns

Header — a value of this type

canonical_header_key

XuAPI
pub fn canonical_header_key(s &string) string

Purpose

Canonical header key.

Parameters

s &string
source string (read-only borrow; caller keeps the original; type &string)

Returns

string — result string

($&Header) add

XuAPI
pub fn (h $&Header) add(key &string, value &string)

Purpose

Operation on $&Header: add.

Parameters

h $&Header
The Header instance used by this call (exclusive borrow).
key &string
key (read-only borrow; caller keeps the original; type &string)
value &string
value (read-only borrow; caller keeps the original; type &string)

Returns

This call does not return a value.

($&Header) del

XuAPI
pub fn (h $&Header) del(key &string)

Purpose

Delete the entry matching the given key or identifier.

Parameters

h $&Header
The Header instance used by this call (exclusive borrow).
key &string
key (read-only borrow; caller keeps the original; type &string)

Returns

This call does not return a value.

($&Header) set

XuAPI
pub fn (h $&Header) set(key &string, value &string)

Purpose

Execute set on $&Header.

Parameters

h $&Header
The Header instance used by this call (exclusive borrow).
key &string
key (read-only borrow; caller keeps the original; type &string)
value &string
value (read-only borrow; caller keeps the original; type &string)

Returns

This call does not return a value.

(Header) get

XuAPI
pub fn (h Header) get(key &string) string

Purpose

Execute get on Header.

Parameters

h Header
The Header instance used by this call (value receiver).
key &string
key (read-only borrow; caller keeps the original; type &string)

Returns

string — result string

(Header) values

XuAPI
pub fn (h Header) values(key &string) []string

Purpose

Return a slice containing all values in the collection.

Parameters

h Header
The Header instance used by this call (value receiver).
key &string
key (read-only borrow; caller keeps the original; type &string)

Returns

[]string — slice result

(Header) clone

XuAPI
pub fn (h Header) clone() Header

Purpose

Operation on Header: copy into a new independent string.

Parameters

h Header
The Header instance used by this call (value receiver).

Returns

Header — a value of this type

(Header) len

XuAPI
pub fn (h Header) len() int

Purpose

Operation on Header: return the length.

Parameters

h Header
The Header instance used by this call (value receiver).

Returns

int — a value of this type

(Header) write

XuAPI
pub fn (h Header) write() string

Purpose

Operation on Header: write data and return the byte count.

Parameters

h Header
The Header instance used by this call (value receiver).

Returns

string — result string

parse_header

XuAPI
pub fn parse_header(raw &string) Header

Purpose

Parse as header.

Parameters

raw &string
raw (read-only borrow; caller keeps the original; type &string)

Returns

Header — a value of this type

struct ServeMux

XuAPI
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

XuAPI
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

XuAPI
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

XuAPI
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

XuAPI
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

XuAPI
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

XuAPI
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

XuAPI
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

XuAPI
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

XuAPI
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

XuAPI
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

XuAPI
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

XuAPI
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