HTTP Server with Hono
This example demonstrates how to use hono
with a custom adapter that works with the wasi:http
interface. The hono
library is a lightweight and fast web framework for building HTTP servers. See the hono documentation for more details.
Additionally, it makes use of the wasi:logging/logging
to log details about incoming requests and responses with a hono middleware and it uses the wasi:config/runtime
to pass config from the environment to the hono app as part of the env key on the request context.
Setup
-
Install dependencies:
bashnpm install
-
Build the project:
bashnpm run build
-
Start the server:
bashnpm start
Overview
App
This component implements the wasi:http/incoming-handler
interface, as defined in its WIT (WebAssembly Interface Types) world.
Adapter
The adapter in src/wasmcloud/hono-adapter
bridges the gap between the hono
web framework and the wasi:http
interface. It converts incoming WASI HTTP requests into standard Web Request
objects that Hono can process, and then transforms the Hono Response
back into a WASI-compatible response. This allows you to use Hono's familiar routing and middleware patterns in a Wasm Component, just like you would in a Node.js or edge environment.
How it works:
- The adapter exposes a
serve(app)
function that takes a Hono app and returns a WASI-compatible handler function. - When a request comes in, it converts the WASI HTTP request into a standard Web
Request
object. - The Hono app processes the request and returns a standard Web
Response
. - The adapter reads the response status, headers, and streams the response body (if present) back to the WASI HTTP provider, ensuring compatibility with both text and binary responses.
- Any errors in the request handling are caught and a 500 Internal Server Error is returned to the client.
Logging Middleware
The logging middleware in src/wasmcloud/hono-middleware-wasi-logging
provides request and response logging for your Hono app using the wasi:logging/logging
interface. It logs details about each incoming request and outgoing response, such as method, path, status code, and duration, to the wasmCloud host's log system.
How it works:
- Attaches to your Hono app as middleware
- Logs request details before passing to the next handler
- Logs response details (including status and timing) after the handler completes
- Uses the WASI logging interface for compatibility with wasmCloud and other WASI hosts
This makes it easy to observe and debug your HTTP component's behavior in production or development environments.