nitcorn: update nitrestful example
[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 # Example for the `restful` annotation documented at `lib/nitcorn/restful.nit`
16 module restful_annot
17
18 import nitcorn::restful
19
20 # An action root to its `restful` methods
21 class MyAction
22 super RestfulAction
23
24 # Method answering requests like `foo?s=some_string&i=42&b=true`
25 #
26 # By default, the name of the HTTP resource is the name of the method.
27 # Responds to all HTTP methods, including GET, POST, PUT and DELETE.
28 fun foo(s: String, i: Int, b: Bool): HttpResponse
29 is restful do
30 var resp = new HttpResponse(200)
31 resp.body = "foo {s} {i} {b}"
32 return resp
33 end
34
35 # Method answering requests like `api_name?s=these_arguments_are_optional`
36 #
37 # This method is available as both `api_name` and `alt_name` in HTTP.
38 # Responds only to the GET and PUT HTTP method.
39 fun bar(s: nullable String, i: nullable Int, b: nullable Bool): HttpResponse
40 is restful("api_name", "alt_name", GET, PUT) do
41
42 var resp = new HttpResponse(200)
43 resp.body = "bar {s or else "null"} {i or else "null"} {b or else "null"}"
44 return resp
45 end
46 end
47
48 var vh = new VirtualHost("localhost:8080")
49
50 # Set `rest_path` as the root for an instance of `MyAction`, so:
51 # * `MyClass::foo` is available as `localhost:8080/rest_path/foo?...`,
52 # * `MyClass::bar` is available as both `localhost:8080/rest_path/api_name?...`
53 # and `localhost:8080/rest_path/alt_name?...`.
54 vh.routes.add new Route("rest_path", new MyAction)
55
56 var factory = new HttpFactory.and_libevent
57 factory.config.virtual_hosts.add vh
58 factory.run