2017-04-19 41 views
0

我正在編寫一個基於Sinatra的API,並且想要使用API​​密鑰保護某些端點,在處理路由之前驗證密鑰。如何從前一個塊返回JSON響應

我明白爲什麼在before塊不起作用拋出一個錯誤,因爲begin/rescue陳述沒有被調用呢,不過我要發送一個JSON響應返回給客戶端的錯誤消息一個JSON對象。

我該怎麼做?

namespace '/v1/sponser/:key' do 

    before do 
    if APIHelper.valid_key?(params[:key]) == false 
     throw 'Error, invalid API key' 
     # is it possible to return a JSON response from the before statement here? 
    end 
    end 

    get '/test' do 
    begin 
     json status: 200, body: 'just a test' 
    rescue => error 
     json status: 404, error: error 
    end 
    end 

end 

回答

1

我會考慮使用halt

before do 
    unless APIHelper.valid_key?(params[:key]) 
    halt 404, { 'Content-Type' => 'application/json' }, 
       { error: 'Error, invalid API key' }.to_json 
    end 
end 

get '/test' do 
    json status: 200, body: 'just a test' 
end 
0

您可以使用halt方法返回的響應與特定代碼,身體和頭部。所以它看起來像這樣: before do halt 401, {'Content-Type' => 'application/json'}, '{"Message": "..."}' end 它看起來馬虎,所以你可以重定向到另一個網址,提供一些服務