Skip to content

Commit 5658191

Browse files
committed
refactor(http): replace status code integers with enum values
- Replace raw status code integers with StatusCode enum for better type safety - Update HttpResponse to use StatusCode instead of StatusCoder trait - Add Custom variant to StatusCode enum for custom status codes - Improve JSON handling in responder example with BodyReader implementation
1 parent a0dda92 commit 5658191

7 files changed

Lines changed: 42 additions & 22 deletions

File tree

moon.mod.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "oboard/mocket",
3-
"version": "0.5.8",
3+
"version": "0.6.0",
44
"deps": {
55
"illusory0x0/native": "0.2.1",
66
"moonbitlang/x": "0.4.34",

src/examples/responder/main.mbt

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,16 @@
1+
///|
2+
using @mocket {type HttpResponse}
3+
14
///|
25
struct Person {
36
name : String
47
age : Int
5-
} derive(ToJson)
8+
} derive(ToJson, FromJson)
9+
10+
///|
11+
impl @mocket.BodyReader for Person with from_request(req) -> Person raise {
12+
@json.from_json(req.body())
13+
}
614

715
///|
816
fn main {
@@ -13,13 +21,29 @@ fn main {
1321
..get("/", _event => "⚡️ Tadaa!")
1422

1523
// Object Response
16-
..get("/", _event => { name: "oboard", age: 21 }.to_json())
24+
..get("/json", _event => { name: "oboard", age: 21 }.to_json())
25+
26+
// JSON Request
27+
// curl --location 'localhost:4000/json' \
28+
// --header 'Content-Type: application/json' \
29+
// --data '{
30+
// "name": "oboard",
31+
// "age": 21
32+
// }'
33+
..post("/json", event => try {
34+
let person : Person = event.req.body()
35+
HttpResponse::new(OK).body(
36+
"Hello, \{person.name}. You are \{person.age} years old.",
37+
)
38+
} catch {
39+
_ => HttpResponse::new(BadRequest).body("Invalid JSON")
40+
})
1741

1842
// Echo Server
1943
..post("/echo", e => e.req)
2044

2145
// 404 Page
22-
..get("/404", _ => @mocket.HttpResponse::new(@mocket.NotFound).body(
46+
..get("/404", _ => HttpResponse::new(NotFound).body(
2347
@mocket.html(
2448
(
2549
#|<html>

src/not_found.mbt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
///|
22
pub async fn handle_not_found(_ : MocketEvent) -> &Responder noraise {
3-
HttpResponse::new(404).body("Not Found")
3+
HttpResponse::new(NotFound).body("Not Found")
44
}

src/request.mbt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ pub(all) struct HttpRequest {
88

99
///|
1010
pub(open) trait BodyReader {
11-
from_request(HttpRequest) -> Self raise
11+
from_request(req: HttpRequest) -> Self raise
1212
}
1313

1414
///|

src/response.mbt

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
///|
22
pub(all) struct HttpResponse {
3-
mut status_code : &StatusCoder
3+
mut status_code : StatusCode
44
headers : Map[StringView, StringView]
55
cookies : Map[String, CookieItem]
66
mut raw_body : Bytes
77
}
88

99
///|
1010
pub fn HttpResponse::new(
11-
status_code : &StatusCoder,
11+
status_code : StatusCode,
1212
headers? : Map[StringView, StringView],
1313
cookies? : Map[String, CookieItem],
1414
raw_body? : Bytes,
@@ -33,8 +33,8 @@ pub fn HttpResponse::body(
3333
}
3434

3535
///|
36-
pub fn HttpResponse::json(self : HttpResponse, body : Json) -> HttpResponse {
37-
self.body(body)
36+
pub fn HttpResponse::json(self : HttpResponse, obj : &ToJson) -> HttpResponse {
37+
self.body(obj.to_json())
3838
}
3939

4040
///|

src/static.mbt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ pub fn Mocket::static_assets(
5353
return next()
5454
}
5555
event.res.headers.set("Allow", "GET, HEAD")
56-
return HttpResponse::new(405)
56+
return HttpResponse::new(MethodNotAllowed)
5757
}
5858
let original_id = event.req.url[path.length():].to_string() catch {
5959
_ => return next()

src/status_code.mbt

Lines changed: 7 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,3 @@
1-
///|
2-
pub trait StatusCoder {
3-
to_int(self : Self) -> Int
4-
}
5-
6-
///|
7-
pub impl StatusCoder for Int with to_int(self) -> Int {
8-
self
9-
}
10-
111
///|
122
/// HTTP status codes as registered with IANA.
133
/// See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
@@ -136,10 +126,15 @@ pub(all) enum StatusCode {
136126
NotExtended
137127
/// RFC 6585, 6
138128
NetworkAuthenticationRequired
129+
Custom(Int)
139130
} derive(Show, ToJson)
140131

132+
pub fn StatusCode::from_int(i : Int) -> StatusCode {
133+
Custom(i)
134+
}
135+
141136
///|
142-
pub impl StatusCoder for StatusCode with to_int(self) -> Int {
137+
pub fn StatusCode::to_int(self: StatusCode) -> Int {
143138
match self {
144139
Continue => 100
145140
SwitchingProtocols => 101
@@ -203,6 +198,7 @@ pub impl StatusCoder for StatusCode with to_int(self) -> Int {
203198
LoopDetected => 508
204199
NotExtended => 510
205200
NetworkAuthenticationRequired => 511
201+
Custom(i) => i
206202
}
207203
}
208204

0 commit comments

Comments
 (0)