Kemal Route parameters



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

get "/" do
  %{
    <a href="/user/foo">/user/foo</a><br>
    <a href="/user/bar/bados">/user/bar/bados</a><br>
    <a href="/user/a/b/c">/user/a/b/c</a><br>
    <a href="/path/a/b/c/d">/path/a/b/c/d</a></br>
  }
end

get "/user/:fname" do |env|
  fname = env.params.url["fname"]
  "received fname: #{fname}"
end

get "/user/:fname/:lname" do |env|
  fname = env.params.url["fname"]
  lname = env.params.url["lname"]
  "received fname: #{fname} and lname: #{lname}"
end

get "/path/*all" do |env|
  all = env.params.url["all"]
  "received #{all}"
end

Kemal.run

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

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(%{<a href="/user/foo">/user/foo</a><br>})
    response.body.should_not contain(%{received})
  end

  it "renders /user/one" do
    get "/user/one"
    response.status_code.should eq 200
    response.headers["Content-Type"].should eq "text/html"
    response.body.should_not contain(%{<a})
    response.body.should contain(%{received fname: one})
  end

  it "renders /user/one/two" do
    get "/user/one/two"
    response.status_code.should eq 200
    response.headers["Content-Type"].should eq "text/html"
    response.body.should_not contain(%{<a})
    response.body.should contain(%{received fname: one and lname: two})
  end

  it "renders /user/one/two/three" do
    get "/user/one/two/three"
    response.status_code.should eq 200 # TODO should be 404
    response.headers["Content-Type"].should eq "text/html"
    response.body.should eq "" # TODO: where is the page?
  end

  it "renders /path/1/2/3/4/5" do
    get "/path/1/2/3/4/5"
    response.status_code.should eq 200
    response.headers["Content-Type"].should eq "text/html"
    response.body.should eq "received 1/2/3/4/5"
  end
end

crystal spec/post_params_spec.cr