Nyx con Ejemplos

Servidor HTTP/2

HTTP/2 multiplexa muchos streams sobre una única conexión TCP. El handler del servidor recibe un stream_id para poder intercalar respuestas. HPACK comprime los encabezados repetidos entre streams.

Código

// nyx-http2 server — HTTP/2 with HPACK and multiplexing

import "std/http2"

fn on_request(fd: int, stream_id: int, method: String, path: String, body: String) -> int {
    // HTTP/2 handler receives stream_id so one connection handles many streams
    let hdrs: Array = ["content-type", "application/json"]

    if path == "/" {
        h2_send_response(fd, stream_id, 200, hdrs, "{\"message\": \"hello over HTTP/2\"}")
    } else {
        h2_send_response(fd, stream_id, 404, hdrs, "{\"error\": \"not found\"}")
    }
    return 0
}

fn main() -> int {
    let port: int = 3004
    let workers: int = 4

    print("HTTP/2 server starting on :" + int_to_string(port))
    print("  mode: h2c (HTTP/2 cleartext, no TLS)")
    print("  multiplexing: multiple streams per connection")
    print("  compression: HPACK for headers")

    // h2_serve blocks accepting connections, handling HTTP/2 frames,
    // dispatching streams to the handler.
    // h2_serve(port, workers, on_request)

    print("")
    print("test with: curl --http2-prior-knowledge http://localhost:3004/")
    return 0
}

Salida

HTTP/2 server starting on :3004
  mode: h2c (HTTP/2 cleartext, no TLS)
  multiplexing: multiple streams per connection
  compression: HPACK for headers

test with: curl --http2-prior-knowledge http://localhost:3004/

Explicación

El modelo de una-petición-por-conexión de HTTP/1.1 es un precipicio de rendimiento cuando una página necesita 80 recursos. HTTP/2 lo resuelve con multiplexado: cada petición abre un nuevo stream dentro de la misma conexión TCP, y las respuestas pueden volver fuera de orden. El stream_id atraviesa el handler para que el runtime pueda intercalar los frames. HPACK comprime los encabezados repetitivos (Host, User-Agent, Accept) que de otro modo dominarían las peticiones pequeñas. nyx-http2 implementa todo esto en Nyx puro sobre el runtime TCP crudo.

← Anterior Siguiente →

Source: examples/by-example/94-http2-server.nx