mirror of
https://gitea.invidious.io/iv-org/shard-kemal.git
synced 2024-08-15 00:53:36 +00:00
Added response and headers
This commit is contained in:
parent
ffdaecace4
commit
4ce1bc908f
4 changed files with 44 additions and 5 deletions
|
@ -33,4 +33,14 @@ describe "Context" do
|
|||
response = kemal.call(request)
|
||||
response.body.should eq "Hello kemal"
|
||||
end
|
||||
|
||||
it "sets response headers" do
|
||||
kemal = Kemal::Handler.new
|
||||
kemal.add_route "GET", "/" do |env|
|
||||
env.set_header "Accept-Language", "tr"
|
||||
end
|
||||
request = HTTP::Request.new("GET", "/")
|
||||
response = kemal.call(request)
|
||||
response.headers["Accept-Language"].should eq "tr"
|
||||
end
|
||||
end
|
||||
|
|
|
@ -2,18 +2,33 @@
|
|||
# information such as params, content_type e.g
|
||||
class Kemal::Context
|
||||
getter request
|
||||
getter response
|
||||
getter params
|
||||
getter content_type
|
||||
|
||||
def initialize(@request, @params)
|
||||
@content_type = "text/html"
|
||||
@response = Kemal::Response.new
|
||||
end
|
||||
|
||||
def headers
|
||||
request.headers
|
||||
@request.headers
|
||||
end
|
||||
|
||||
def response_headers
|
||||
@response.headers
|
||||
end
|
||||
|
||||
def set_header(name, value)
|
||||
@response.headers.add name, value
|
||||
end
|
||||
|
||||
def content_type
|
||||
@response.content_type
|
||||
end
|
||||
|
||||
def set_content_type(content_type)
|
||||
@content_type = content_type
|
||||
@response.content_type = content_type
|
||||
end
|
||||
|
||||
delegate status_code, @response
|
||||
end
|
||||
|
|
|
@ -26,8 +26,7 @@ class Kemal::Handler < HTTP::Handler
|
|||
context = Context.new(request, params.not_nil!)
|
||||
begin
|
||||
body = route.handler.call(context).to_s
|
||||
content_type = context.content_type
|
||||
return HTTP::Response.ok(content_type, body)
|
||||
return HTTP::Response.new(200, body, context.response_headers)
|
||||
rescue ex
|
||||
return HTTP::Response.error("text/plain", ex.to_s)
|
||||
end
|
||||
|
|
15
src/kemal/response.cr
Normal file
15
src/kemal/response.cr
Normal file
|
@ -0,0 +1,15 @@
|
|||
class Kemal::Response
|
||||
property headers
|
||||
property status_code
|
||||
property content_type
|
||||
|
||||
def initialize
|
||||
@status_code :: String
|
||||
@content_type = "text/html"
|
||||
@headers = HTTP::Headers{"Content-Type": @content_type}
|
||||
end
|
||||
|
||||
def content_type=(content_type)
|
||||
@headers["Content-Type"] = content_type
|
||||
end
|
||||
end
|
Loading…
Reference in a new issue