JoeCode

TIL: Sinatra Rack Middleware

Dec 07, 2023

GeoIP database resources

Rack Middleware resources and inspiration

Limit requests by ISO country code Sinatra example

rack-geoip.rb

require 'maxmind/geoip2'
module Rack
  class GeoIPFilter
    def initialize(app)
      @mmdb = MaxMind::GeoIP2::Reader.new('./GeoLite2-Country.mmdb')
      @app = app
    end
    def call(request)
      begin
        geo_record = @mmdb.country(request['REMOTE_ADDR'])
        country_codes = ['US','CA']
        if (country_codes.include? geo_record.country.iso_code)
          @app.call(request.merge(:country_code => geo_record.country.iso_code))
        else
          [503, {}, ["503 Service Unavailable"]]
        end
      rescue
        @app.call(request.merge(:country_code => nil))
      end
    end
  end
end

config.ru

require './lib/rack-geoip'
use Rack::GeoIPFilter
...