|
| 1 | +package export_wasi_http_handler |
| 2 | + |
| 3 | +import ( |
| 4 | + . "wit_component/wasi_http_types" |
| 5 | + |
| 6 | + . "go.bytecodealliance.org/pkg/wit/types" |
| 7 | +) |
| 8 | + |
| 9 | +// Handle the specified `Request`, returning a `Response` |
| 10 | +func Handle(request *Request) Result[*Response, ErrorCode] { |
| 11 | + method := request.GetMethod().Tag() |
| 12 | + path := request.GetPathWithQuery().SomeOr("/") |
| 13 | + |
| 14 | + if method == MethodGet && path == "/hello" { |
| 15 | + // Say hello! |
| 16 | + |
| 17 | + tx, rx := MakeStreamU8() |
| 18 | + |
| 19 | + go func() { |
| 20 | + defer tx.Drop() |
| 21 | + tx.WriteAll([]uint8("Hello, world!")) |
| 22 | + }() |
| 23 | + |
| 24 | + response, send := ResponseNew( |
| 25 | + FieldsFromList([]Tuple2[string, []byte]{ |
| 26 | + {F0: "content-type", F1: []byte("text/plain")}, |
| 27 | + }).Ok(), |
| 28 | + Some(rx), |
| 29 | + trailersFuture(), |
| 30 | + ) |
| 31 | + send.Drop() |
| 32 | + |
| 33 | + return Ok[*Response, ErrorCode](response) |
| 34 | + |
| 35 | + } else { |
| 36 | + // Bad request |
| 37 | + |
| 38 | + response, send := ResponseNew( |
| 39 | + MakeFields(), |
| 40 | + None[*StreamReader[uint8]](), |
| 41 | + trailersFuture(), |
| 42 | + ) |
| 43 | + send.Drop() |
| 44 | + response.SetStatusCode(400).Ok() |
| 45 | + |
| 46 | + return Ok[*Response, ErrorCode](response) |
| 47 | + |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +func trailersFuture() *FutureReader[Result[Option[*Fields], ErrorCode]] { |
| 52 | + tx, rx := MakeFutureResultOptionFieldsErrorCode() |
| 53 | + go tx.Write(Ok[Option[*Fields], ErrorCode](None[*Fields]())) |
| 54 | + return rx |
| 55 | +} |
| 56 | + |
| 57 | +func unitFuture() *FutureReader[Result[Unit, ErrorCode]] { |
| 58 | + tx, rx := MakeFutureResultUnitErrorCode() |
| 59 | + go tx.Write(Ok[Unit, ErrorCode](Unit{})) |
| 60 | + return rx |
| 61 | +} |
0 commit comments