adapt handle function type

main
floscodes 1 year ago
parent f6b25566f6
commit 0c8ec8e8a8

1
.gitignore vendored

@ -0,0 +1 @@
zig-cache/

@ -14,17 +14,17 @@ const Server = zrv.Server;
const Route = zrv.Route;
const allocator = std.heap.page_allocator; // Choose any allocator you want!
fn index(req: Request) Response {
fn index(req: *Request) Response {
_=req;
return Response.write("hello!");
}
fn about(req: Request) Response {
fn about(req: *Request) Response {
_=req;
return Response.write("about site");
}
fn writeJson(req: Request) Response {
fn writeJson(req: *Request) Response {
_=req;
Response.json("[1, 2, 3, 4]");
}
@ -57,11 +57,11 @@ const rt = [_]Route{.{"/hello", helloFunction}};
### Handler Functions
Every Request is handled by a handler function. It has to be of this type: `fn(req: Request) Response`
Every Request is handled by a handler function. It has to be of this type: `fn(req: *Request) Response`
Example:
```zig
fn hello(req: Request) Response {
fn hello(req: *Request) Response {
_ = req;
return Response.write("hello"); // `Server` will return a Reponse with body "hello". You will see "hello" on your browser.
}

@ -21,7 +21,6 @@ pub const Server = struct {
const server_options: std.net.StreamServer.Options = .{};
var server = std.net.StreamServer.init(server_options);
defer server.deinit();
defer server.close();
const addr = try std.net.Address.parseIp(ip, port);
try server.listen(addr);
@ -67,7 +66,7 @@ pub const Server = struct {
// Check if there is a match
if (eql(u8, req_path, req.uri)) {
// Change response with handling function in case of match.
res = r[1](req);
res = r[1](&req);
// Exit loop in case of match
break;
}
@ -164,6 +163,6 @@ test "Run server" {
try Server.listen("0.0.0.0", 8080, &rt, std.testing.allocator);
}
// Function for test "Run Server"
fn handlefn(_: types.Request) types.Response {
fn handlefn(_: *types.Request) types.Response {
return types.Response.write("<h1>Run Server Test OK!</h1>");
}

@ -8,7 +8,7 @@ const stat = @import("./status.zig");
/// e.g. `const rt = Route{"/home", home};`
/// It it usual that a webapp handles more than one path so you can declare an array of `Route`
/// e.g. `const rt =[_]Route{.{"/index", index}, .{"/home", home}};`
pub const Route = tuple(&.{ []const u8, *const fn (Request) Response });
pub const Route = tuple(&.{ []const u8, *const fn (*Request) Response });
/// A header of a `Request` or a `Response`.
/// It is usual that more than one is sent, so you can declare an array.

Loading…
Cancel
Save