如何在Sinatra中创建不区分大小写的路由?

Jon*_*esø 7 sinatra

我正在玩Sinatra,我想让我的一条路线不区分大小写.我尝试添加这样的路线:

get "(?i)/tileflood/?" do
end
Run Code Online (Sandbox Code Playgroud)

但它与预期的/ tileflood的任何排列都不匹配.我在rubular.com上测试了以下正则表达式,它匹配得很好.我错过了什么吗?

\/(?i)tileflood\/?
Run Code Online (Sandbox Code Playgroud)

Phr*_*ogz 8

你想要一个真正的正则表达式:

require 'sinatra'
get %r{^/tileflood/?$}i do
  request.url + "\n"
end
Run Code Online (Sandbox Code Playgroud)

证明:

smagic:~ phrogz$ curl http://localhost:4567/tileflood
http://localhost:4567/tileflood

smagic:~ phrogz$ curl http://localhost:4567/tIlEflOOd
http://localhost:4567/tIlEflOOd

smagic:~ phrogz$ curl http://localhost:4567/TILEFLOOD/
http://localhost:4567/TILEFLOOD/

smagic:~ phrogz$ curl http://localhost:4567/TILEFLOOD/z
<!DOCTYPE html>
<html>
<head>
  <style type="text/css">
  body { text-align:center;font-family:helvetica,arial;font-size:22px;
    color:#888;margin:20px}
  #c {margin:0 auto;width:500px;text-align:left}
  </style>
</head>
<body>
  <h2>Sinatra doesn't know this ditty.</h2>
  <img src='/__sinatra__/404.png'>
  <div id="c">
    Try this:
    <pre>get '/TILEFLOOD/z' do
  "Hello World"
end</pre>
  </div>
</body>
</html>

smagic:~ phrogz$ curl http://localhost:4567/tileflaad
<!DOCTYPE html>
<html>
<head>
  <style type="text/css">
  body { text-align:center;font-family:helvetica,arial;font-size:22px;
    color:#888;margin:20px}
  #c {margin:0 auto;width:500px;text-align:left}
  </style>
</head>
<body>
  <h2>Sinatra doesn't know this ditty.</h2>
  <img src='/__sinatra__/404.png'>
  <div id="c">
    Try this:
    <pre>get '/tileflaad' do
  "Hello World"
end</pre>
  </div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

  • 通常,我不会在应用程序本身中实现此 url 规范化步骤,我会在 nginx/apache/您使用的任何 Web 服务器中执行此操作。 (2认同)