lib/nitcorn: fix `missing doc` warnings
[nit.git] / lib / nitcorn / examples / src / htcpcp_server.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2015 Guilherme Mansur<guilhermerpmansur@gmail.com>
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16 #
17 # Hyper Text Coffee Pot Control Protocol
18
19 # A server that implements HTCPCP. At the moment there are no additions.
20 module htcpcp_server
21
22 import nitcorn
23
24 # Nitcorn Action used to answer requests.
25 class HTCPCPAction
26 super Action
27
28 # Brewing status.
29 var brewing = false
30
31 # Teapot status.
32 var is_teapot = false
33
34 redef fun answer(http_request, turi) do
35 var message: String
36 var method = http_request.method
37 var headers = http_request.header
38 var response: HttpResponse
39
40 if is_teapot == true then
41 response = new HttpResponse(418)
42 response.body = "I'm a teapot!\n"
43 response.header["Content-Type"] = "text"
44 return response
45 end
46
47 if method == "POST" or method == "BREW" then
48 if brewing then
49 message = "Pot Busy"
50 response = new HttpResponse(400)
51 else
52 message = "Brewing a new pot of coffee\n"
53 brewing = true
54 response = new HttpResponse(200)
55 end
56 else if method == "WHEN" then
57 if brewing then
58 message = "Stopped adding milk, your coffee is ready!\n"
59 brewing = false
60 response = new HttpResponse(200)
61 else
62 message = "There is no coffee brewing!\n"
63 response = new HttpResponse(405)
64 end
65 else if method == "PROPFIND" or method == "GET" then
66 if brewing then
67 message = "The pot is busy\n"
68 else
69 message = "The pot is ready to brew more coffee\n"
70 end
71 response = new HttpResponse(200)
72 else
73 message = "Unknown method: {method}"
74 brewing = false
75 response = new HttpResponse(405)
76 end
77
78 response.header["Content-Type"] = "text"
79 response.body = message
80
81 return response
82 end
83 end
84
85 # Nitcorn server.
86 class HTCPCServer
87
88 # Port to listen to.
89 var port: Int
90
91 # Start listening.
92 fun run do
93 var vh = new VirtualHost("localhost:{port}")
94 vh.routes.add new Route("/", new HTCPCPAction)
95 var factory = new HttpFactory.and_libevent
96 factory.config.virtual_hosts.add vh
97 print "Nit4Coffee is now running at port: {port}"
98 factory.run
99 end
100 end
101
102 var server = new HTCPCServer(1227)
103
104 server.run