lib/nitcorn: add example and test for the restful annotation
[nit.git] / lib / nitcorn / examples / src / restful_annot.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 import nitcorn::restful
16
17 class MyAction
18 super RestfulAction
19
20 # Method answering requests like `foo?s=some_string&i=42&b=true`
21 fun foo(s: String, i: Int, b: Bool): HttpResponse
22 is restful do
23 var resp = new HttpResponse(200)
24 resp.body = "foo {s} {i} {b}"
25 return resp
26 end
27
28 # Method answering requests like `bar?s=these_arguments_are_optional`
29 fun bar(s: nullable String, i: nullable Int, b: nullable Bool): HttpResponse
30 is restful do
31 var resp = new HttpResponse(200)
32 resp.body = "bar {s or else "null"} {i or else "null"} {b or else "null"}"
33 return resp
34 end
35 end
36
37 var vh = new VirtualHost("localhost:8080")
38
39 # Serve everything with our restful action
40 vh.routes.add new Route(null, new MyAction)
41
42 # Avoid executing when running tests
43 if "NIT_TESTING".environ == "true" then exit 0
44
45 var factory = new HttpFactory.and_libevent
46 factory.config.virtual_hosts.add vh
47 factory.run