diff --git a/README.md b/README.md index 52f7c7f..f131cb7 100644 --- a/README.md +++ b/README.md @@ -2,12 +2,12 @@ ## Routing rules - Static first routing -- Path variables defined with `:foo` +- Path variables defined with colon prefix: `:foo` - Example: `/odin/:version/download` - Wild card routing not implemented ## Compile time user errors included -When defining the server you can pass a custom error type for the server. +When defining the server you can pass a custom error union type for the server. All the handler function will, of course, need to return these in as a pair with a response. ## Memory allocation @@ -27,6 +27,20 @@ import "core:strings" import fjord "fjord" import http "fjord/http" +InternalError :: enum { + DatabaseError, +} + +BadRequestError :: enum { + UserUnauthorised, + InputFormatWrong, +} + +Error :: union { + InternalError, + BadRequestError, +} + // Handler for GET /hello/:name hello_handler :: proc(request: ^http.Request) -> (http.Response, Error) { name := request.path_variables["name"] @@ -49,7 +63,7 @@ hello_handler :: proc(request: ^http.Request) -> (http.Response, Error) { // Handler for GET /users/:id/posts/:post_id user_post_handler :: proc(request: ^http.Request) -> (http.Response, Error) { user_id := request.path_variables["id"] - post_id := request.path_variables["post_id"] + post_id := request.path_variables["post-id"] body := strings.concatenate( {"
User ", user_id, " - Post ", post_id, "
"}, @@ -66,9 +80,32 @@ user_post_handler :: proc(request: ^http.Request) -> (http.Response, Error) { return response, nil } -UserError :: enum { - DatabaseError, - ValidationError, +error_callback :: proc(error: Error) -> http.Response { + switch err_type in error { + case BadRequestError: + switch err in err_type { + case UserUnauthorised: fallthrough + case InputFormatWrong: + body := "Bad request error" + return http.make_response( + .BadRequest, + transmute([]byte)body, + .Html, + context.temp_allocator, + ) + } + case InternalError: + switch err in err_type { + case DataBaseError: + body := "Internal server error" + return http.make_response( + .InternalServerError, + transmute([]byte)body, + .Html, + context.temp_allocator, + ) + } + } } main :: proc() { @@ -85,7 +122,9 @@ main :: proc() { defer fjord.server_destroy(&server) fjord.server_add_route(&server, .GET, {"hello", ":name"}, hello_handler) - fjord.server_add_route(&server, .GET, {"users", ":id", "posts", ":post_id"}, user_post_handler) + fjord.server_add_route(&server, .GET, {"users", ":id", "posts", ":post-id"}, user_post_handler) + + server_set_error_handler(&server, error_callback) log.infof("Server listening on http://127.0.0.1:%d", endpoint.port) fjord.server_listen_and_serve(&server)