|
| 1 | +from lightbug_api import ( |
| 2 | + App, |
| 3 | + BaseRequest, |
| 4 | + FromReq, |
| 5 | + Router, |
| 6 | + HandlerResponse, |
| 7 | + JSONType, |
| 8 | +) |
| 9 | +from lightbug_http import HTTPRequest, HTTPResponse, OK |
| 10 | + |
| 11 | + |
| 12 | +fn printer(req: HTTPRequest) raises -> HandlerResponse: |
| 13 | + print("Got a request on ", req.uri.path, " with method ", req.method) |
| 14 | + return OK(req.body_raw) |
| 15 | + |
| 16 | +fn hello(req: HTTPRequest) raises -> HandlerResponse: |
| 17 | + return OK("Hello 🔥!") |
| 18 | + |
| 19 | + |
| 20 | +fn nested(req: HTTPRequest) raises -> HandlerResponse: |
| 21 | + print("Handling route:", req.uri.path) |
| 22 | + # Returning a string will get marshaled to a proper `OK` response |
| 23 | + return req.uri.path |
| 24 | + |
| 25 | + |
| 26 | +struct Payload(FromReq): |
| 27 | + var request: HTTPRequest |
| 28 | + var json: JSONType |
| 29 | + var a: Int |
| 30 | + |
| 31 | + def __init__(out self, request: HTTPRequest, json: JSONType): |
| 32 | + self.a = 1 |
| 33 | + self.request = request.copy() |
| 34 | + self.json = json.copy() |
| 35 | + |
| 36 | + def __init__(out self, *, copy: Self): |
| 37 | + self.a = copy.a |
| 38 | + self.request = copy.request.copy() |
| 39 | + self.json = copy.json.copy() |
| 40 | + |
| 41 | + def __str__(self) -> String: |
| 42 | + return String(self.a) |
| 43 | + |
| 44 | + def from_request(mut self, req: HTTPRequest) raises -> Self: |
| 45 | + self.a = 2 |
| 46 | + return self.copy() |
| 47 | + |
| 48 | + |
| 49 | +fn custom_request_payload(req: HTTPRequest) raises -> HandlerResponse: |
| 50 | + var payload = Payload(request=req, json=JSONType()) |
| 51 | + payload = payload.from_request(req) |
| 52 | + print(payload.a) |
| 53 | + |
| 54 | + # Returning a JSON as the response, this is a very limited placeholder for now |
| 55 | + var json_response = JSONType() |
| 56 | + json_response["a"] = String(payload.a) |
| 57 | + return json_response^ |
| 58 | + |
| 59 | + |
| 60 | +fn main() raises: |
| 61 | + var app = App() |
| 62 | + |
| 63 | + app.get("/", hello) |
| 64 | + |
| 65 | + app.get("custom/", custom_request_payload) |
| 66 | + |
| 67 | + app.post("/", printer) |
| 68 | + |
| 69 | + var nested_router = Router("nested") |
| 70 | + nested_router.get(path="all/echo/", handler=nested) |
| 71 | + app.add_router(nested_router^) |
| 72 | + |
| 73 | + app.start_server() |
0 commit comments