当内容类型为应用程序/JSON时,会自动用JSON编码机架输出
-
26-09-2019 - |
题
我有一个模块化的Sinatra应用程序,并且在内容类型指示时,我想将输出编码为JSON。目前,我在路线上手动这样做:
get 'someroute' do
# content-type is actually set with a before filter
# included only for clarity
content_type 'application/json', :charset => 'utf-8'
# .. #
{:success=>true}.to_json
end
我希望它看起来像这样:
get 'someroute' do
content_type 'application/json', :charset => 'utf-8'
# .. #
{:success=>true}
end
而且,如果它检测到适当的内容类型,我想使用机架中间件进行编码。
我一直在尝试使以下内容工作,但无济于事(内容长度变成了 - 返回原始内容的内容长度,而不是JSON编码的内容):
require 'init'
module Rack
class JSON
def initialize app
@app = app
end
def call env
@status, @headers, @body = @app.call env
if json_response?
@body = @body.to_json
end
[@status, @headers, @body]
end
def json_response?
@headers['Content-Type'] == 'application/json'
end
end
end
use Rack::JSON
MyApp.set :run, false
MyApp.set :environment, ENV['RACK_ENV'].to_sym
run MyApp
有任何指示让我回到正轨吗?
解决方案
除了一件事外,您的一切都正确:机架期望身体是一个响应的物体 each
但不是字符串。只需将您的身体放入阵列即可。
这可能不是必需的,但是如果要手工设置内容长度,只需将其添加到标题中即可。
if json_response?
@body = [@body.to_json]
@headers["Content-Length"] = @body[0].size.to_s
end
不隶属于 StackOverflow