Kemal set headers (change content-type)



examples/kemal/src/set_header.cr
require "kemal"

base_url = "https://code-maven.com"

get "/" do
  "Hello Kemal"
end

# source
get "/sitemap.xml" do |env|
  now = Time.utc
  now_str = now.to_s("%Y-%m-%d")
  env.response.content_type = "application/xml"
  xml = %{
     <?xml version="1.0" encoding="UTF-8"?>
     <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
     <url>
       <loc>#{base_url}/</loc>
       <lastmod>#{now_str}</lastmod>
     </url>
     </urlset>
  }
  xml
end

Kemal.run

examples/kemal/spec/set_header_spec.cr
ENV["KEMAL_ENV"] = "test"
require "spec-kemal"
require "../src/set_header"

describe "Web Application" do
  it "renders /" do
    get "/"
    response.status_code.should eq 200
    response.headers["Content-Type"].should eq "text/html"
    response.body.should contain(%{Hello Kemal})
  end

  it "renders /sitemap.xml" do
    get "/sitemap.xml"
    response.status_code.should eq 200
    response.headers["Content-Type"].should eq "application/xml"
    response.body.should contain(%{<?xml version="1.0" encoding="UTF-8"?>})
  end
end