XU XUv0.16.0

13 · HTTP Context / mux

請求收成一個 http.Context:

fn hello(c http.Context) {
    c.text(200, "hello")
}
http.listen_and_serve_handler("127.0.0.1:18081", hello)

在一個 app(c) 裡按 c.path() 分支即可。

原始碼

@main

#net/http

// 請求上下文:收成一個 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
}

在獨立的 examples 倉庫根執行;原始碼位於 examples/。