Last Updated: February 25, 2016
·
2.059K
· otobrglez

Asynchronous Ruby calculator with Goliath and Grape

Goliath is non-blocking (asynchronous) Ruby web server framework. Internally it uses EventMachine reactor and Ruby Fibers. Combined with Grape - REST-like API micro-framework for Ruby you get super nice and super fast framework for building APIs.

Simple Server:

%w(goliath grape).each { |l| require l }

class CalculatorAPI < Grape::API
    format :json

    get '/add' do
      { result: params[:a].to_i + params[:b].to_i }
    end

    get '/subtract' do
      { result: params[:a].to_i - params[:b].to_i }
    end

end

class APIServer < Goliath::API
    def response(env) CalculatorAPI.call(env); end
end

Run like so:

ruby api_server.rb -sv -p 9000

Test with cURL:

curl -D - "http://localhost:9000/add?a=1&b=20"