Skip to content

Test an HTTP router without a port ​

kinmokusei/http implements http.Handler, so the standard Go HTTP testing tools work directly. This complete example opens no listener and needs no network access.

Source ​

ts
import { App, Context } from "kinmokusei/http";
import go fmt from "fmt";
import go http from "net/http";
import go httptest from "net/http/httptest";

function router(): http.Handler {
  const app = new App();
  app.get("/health", (ctx: Context): void => {
    ctx.writer.Header().Set("X-Route", "health");
    fmt.Fprint(ctx.writer, "ok");
  });
  app.get("/users/{id}", (ctx: Context): void => {
    ctx.writer.Header().Set("X-Route", "user");
    fmt.Fprintf(ctx.writer, "%s:%s", ctx.path("id"), ctx.query("view"));
  });
  return app.handler();
}

function request(handler: http.Handler, target: string): void {
  const recorder = httptest.NewRecorder();
  const incoming = httptest.NewRequest(http.MethodGet, target, nil);
  handler.ServeHTTP(recorder, incoming);
  fmt.Println(recorder.Code, recorder.Body.String(), recorder.Header().Get("X-Route"));
}

function main(): void {
  const handler = router();
  request(handler, "/health");
  request(handler, "/users/planet?view=full");
}

Run ​

sh
keika check http-router.km
keika run http-router.km

Expected output:

text
200 ok health
200 planet:full user

App delegates matching to Go's http.ServeMux. The {id} path variable is available through ctx.path("id"); query and response APIs remain the original net/http behavior.

For production, return app.handler() from a router function and configure an ordinary http.Server at the process boundary. Timeouts, TLS, listener ownership, and graceful shutdown remain explicit application policy.

See the kinmokusei/http API and HTTP application guide.

Kinmokusei is a pre-1.0 project. Documentation describes implemented behavior.