diff --git a/spec/context_spec.cr b/spec/context_spec.cr index 3a0113c..23fdb62 100644 --- a/spec/context_spec.cr +++ b/spec/context_spec.cr @@ -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 diff --git a/src/kemal/context.cr b/src/kemal/context.cr index 887320d..b3e981d 100644 --- a/src/kemal/context.cr +++ b/src/kemal/context.cr @@ -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 diff --git a/src/kemal/handler.cr b/src/kemal/handler.cr index f5e69aa..9241e16 100644 --- a/src/kemal/handler.cr +++ b/src/kemal/handler.cr @@ -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 diff --git a/src/kemal/response.cr b/src/kemal/response.cr new file mode 100644 index 0000000..3630c03 --- /dev/null +++ b/src/kemal/response.cr @@ -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