Skip to content

Commit a8bded8

Browse files
authored
veb: add an early startup panic error message, when the result type of route handler methods *is not* veb.Result (fix #25970) (#25973)
1 parent f79867d commit a8bded8

File tree

3 files changed

+51
-0
lines changed

3 files changed

+51
-0
lines changed

vlib/veb/parse.v

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,3 +95,23 @@ fn parse_form_from_request(request http.Request) !(map[string]string, map[string
9595
}
9696
return http.parse_form(request.data), map[string][]http.FileData{}
9797
}
98+
99+
// has_route_attributes checks if a method has attributes that indicate it should be a route handler
100+
fn has_route_attributes(attrs []string) bool {
101+
if attrs.len == 0 {
102+
return false
103+
}
104+
for attr in attrs {
105+
attru := attr.to_upper()
106+
if attru in ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'] {
107+
return true
108+
}
109+
if attr.starts_with('/') {
110+
return true
111+
}
112+
if attr.starts_with('host:') {
113+
return true
114+
}
115+
}
116+
return false
117+
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import veb
2+
3+
pub struct App {}
4+
5+
struct Context {
6+
veb.Context
7+
}
8+
9+
// Test that methods with route attributes but wrong return type are caught
10+
fn test_invalid_return_type_is_detected() {
11+
mut app := &App{}
12+
13+
// This should fail because get_task has route attributes but returns !veb.Result
14+
veb.generate_routes[App, Context](app) or {
15+
assert err.msg().contains('invalid return type'), 'Expected error about invalid return type, got: ${err.msg()}'
16+
assert err.msg().contains('get_task'), 'Expected error to mention method name, got: ${err.msg()}'
17+
return
18+
}
19+
20+
assert false, 'Expected generate_routes to return an error for invalid return type'
21+
}
22+
23+
@['/test'; get]
24+
pub fn (app &App) get_task(mut ctx Context) !veb.Result {
25+
return ctx.text('Hello')
26+
}

vlib/veb/veb.v

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,11 @@ fn generate_routes[A, X](app &A) !map[string]Route {
5353
}
5454

5555
routes[method.name] = route
56+
} $else {
57+
// If we have route attributes, but the wrong return type, return an error
58+
if has_route_attributes(method.attrs) {
59+
return error('method `${method.name}` has route attributes but invalid return type. Handler methods must return `veb.Result`, not `!veb.Result` or other types')
60+
}
5661
}
5762
}
5863
return routes

0 commit comments

Comments
 (0)