nit: Added link to `CONTRIBUTING.md` from the README
[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 class HTCPCPAction
25 super Action
26 var brewing = false
27 var is_teapot = false
28
29 redef fun answer(http_request, turi) do
30 var message: String
31 var method = http_request.method
32 var headers = http_request.header
33 var response: HttpResponse
34
35 if is_teapot == true then
36 response = new HttpResponse(418)
37 response.body = "I'm a teapot!\n"
38 response.header["Content-Type"] = "text"
39 return response
40 end
41
42 if method == "POST" or method == "BREW" then
43 if brewing then
44 message = "Pot Busy"
45 response = new HttpResponse(400)
46 else
47 message = "Brewing a new pot of coffee\n"
48 brewing = true
49 response = new HttpResponse(200)
50 end
51 else if method == "WHEN" then
52 if brewing then
53 message = "Stopped adding milk, your coffee is ready!\n"
54 brewing = false
55 response = new HttpResponse(200)
56 else
57 message = "There is no coffee brewing!\n"
58 response = new HttpResponse(405)
59 end
60 else if method == "PROPFIND" or method == "GET" then
61 if brewing then
62 message = "The pot is busy\n"
63 else
64 message = "The pot is ready to brew more coffee\n"
65 end
66 response = new HttpResponse(200)
67 else
68 message = "Unknown method: {method}"
69 brewing = false
70 response = new HttpResponse(405)
71 end
72
73 response.header["Content-Type"] = "text"
74 response.body = message
75
76 return response
77 end
78 end
79
80
81 class HTCPCServer
82 var port: Int
83
84 fun run do
85 var vh = new VirtualHost("localhost:{port}")
86 vh.routes.add new Route("/", new HTCPCPAction)
87 var factory = new HttpFactory.and_libevent
88 factory.config.virtual_hosts.add vh
89 print "Nit4Coffee is now running at port: {port}"
90 factory.run
91 end
92 end
93
94 var server = new HTCPCServer(1227)
95
96 server.run