Ruby 占用空间最少的库,可托管非常简单的单个端点 API

Ruby library with least footprint to host a very simple single endpoint API

我有一个非常简单的数字运算 Ruby 功能,我想通过网络提供它 API。 API 本质上是一个单一的端点,例如http://example.com/crunch/<number> 并且它 returns JSON 输出。

我显然可以安装 Rails 并快速实施。除了为我处理 HTTP 之外,我不需要 'framework' 的更多帮助。没有 ORM、MVC 和其他多余的东西。

在远端,我可以编写一些 Ruby 代码来监听端口并接受 GET 请求并解析 HTTP headers 等等。我不想 re-invent那个轮子。

我可以使用什么来使用最少 footprint/dependencies 向网络公开最小 API。我读过 Sinatra、Ramaze 等,但我相信有一种方法可以做一些更简单的事情。我可以在 Rack 上破解一些代码来做我想做的事吗?

或者换句话说,nodejs 中最简单的 Ruby 等效于以下代码:

var http = require('http');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  var ans = crunch(number);
  res.end(ans);
}).listen(1337, "127.0.0.1");

console.log('Server running at http://127.0.0.1:1337/');

您似乎想使用 Rack directly. "Rack from the Beginning”是一个不错的教程,应该可以帮助您入门。

它可能看起来像这样:

class CrunchApp
  def self.crunch(crunchable)
    # top-secret crunching
  end
  def self.call(env)
    crunchy_stuff = input(env)
    [200, {}, crunch(crunchy_stuff)]
  end
  private
  def self.input(env)
    request = Rack::Request.new(env)
    request.params['my_input']
  end
end

Rack::Server.start app: CrunchApp

但我必须说,使用它而不是 Sinatra 之类的东西似乎很愚蠢,除非这只是一个有趣的项目。查看他们的 'Hello World':

require 'sinatra'

get '/hi' do
  "Hello World!"
end

Ruby-Grape 是适合您的用例的不错选择。它在 Rack 上有一个最小的实现,允许创建简单的 REST-API 端点。

Cuba is another good option with a thin layer over Rack itself.sample post

如果您熟悉 Rails,您可以使用 Rails API gem which is very well documented with minor overhead. Remember also that Rails-API will be part of Rails 5

最后,但不是最后,您可以直接在 Rack 上实现它。