Skip to content

Instantly share code, notes, and snippets.

@kazu69
Created July 7, 2015 05:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kazu69/bc66cdbdaf8c1c7550ae to your computer and use it in GitHub Desktop.
Save kazu69/bc66cdbdaf8c1c7550ae to your computer and use it in GitHub Desktop.
simple rack mimddlewear
require 'sinatra'
class MyApp < Sinatra::Base
get '/hoge' do
'Hello world!'
end
end
require './app'
require File.expand_path 'lib/my_rack_middleware', File.dirname(__FILE__)
use MyRackMiddleware
run MyApp
source "https://rubygems.org"
gem 'sinatra'
tree -L 2
.
├── Gemfile
├── Gemfile.lock
├── app.rb
├── config.ru
├── lib
│   └── my_rack_middleware.rb
└── vendor
└── bundle
bundle install
bundle exec rackup -p 4567
open http://localhost:4567
# /lib/my_rack_middlewear.rb
class MyRackMiddleware
def initialize(app)
@app = app
end
def call(env)
if env["PATH_INFO"] == '/hoge'
status, headers, response = @app.call(env)
status = 200
response = ["hogehoge"]
content_length = response.inject(0) do |sum, content|
sum + content.bytesize
end
headers = { "Content-Type" => "text/html;charset=utf-8",
"Content-Length" => content_length.to_s,
"X-XSS-Protection" => "1; mode=block",
"X-Content-Type-Options" => "nosniff",
"X-Frame-Options" => "SAMEORIGIN"}
else
res = @app.call(env)
end
[status, headers, response]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment