/
context.cr
66 lines (54 loc) · 1.56 KB
/
context.cr
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# `HTTP::Server::Context` is the class which holds `HTTP::Request` and
# `HTTP::Server::Response` alongside with information such as request params,
# request/response content_type, session data and alike.
#
# Instances of this class are passed to an `HTTP::Server` handler.
class HTTP::Server
class Context
# :nodoc:
STORE_MAPPINGS = [Nil, String, Int32, Int64, Float64, Bool]
macro finished
alias StoreTypes = Union({{ *STORE_MAPPINGS }})
@store = {} of String => StoreTypes
end
def params
@request.url_params ||= route_lookup.params
@params ||= if @request.param_parser
@request.param_parser.not_nil!
else
Kemal::ParamParser.new(@request)
end
end
def redirect(url : String, status_code : Int32 = 302)
@response.headers.add "Location", url
@response.status_code = status_code
end
def route
route_lookup.payload
end
def websocket
ws_route_lookup.payload
end
def route_lookup
Kemal::RouteHandler::INSTANCE.lookup_route(@request.override_method.as(String), @request.path)
end
def route_defined?
route_lookup.found?
end
def ws_route_lookup
Kemal::WebSocketHandler::INSTANCE.lookup_ws_route(@request.path)
end
def ws_route_defined?
ws_route_lookup.found?
end
def get(name : String)
@store[name]
end
def set(name : String, value : StoreTypes)
@store[name] = value
end
def get?(name : String)
@store[name]?
end
end
end