答案很简单:
默认情况下,Sinatra侦听端口4567,因此我只是确保它绑定到所有接口,以防我想从其外部IP地址调用它,并禁用任何详细错误输出,如下所示:
listener.rb
require "sinatra"
set :bind, "0.0.0.0"
disable :show_exceptions
disable :raise_errors
post "/" do
# Check if the header matches
# If it did not match then halt and return code 401 Unauthorized
if request.env["HTTP_custom_header_name"] != "verystrongpassword"
halt 401
end
#the rest of your code goes here
status :ok
end
请注意,在比较标题值时,
超文本传输协议
Link
例子
require "sinatra"
set :bind, "0.0.0.0"
disable :show_exceptions
disable :raise_errors
post "/" do
# Check if the header matches
# If it did not match then halt and return code 401 Unauthorized
if request.env["HTTP_X_GIT_SECRET"] != "d4c74594d841139328695756648b6bd6"
halt 401
end
data = JSON.parse request.body.read
p data
status :ok
end
哪里
额外的
如果您不知道发送给sinatra的头的名称,那么您可以通过放置以下内容来检查所有请求内容
在if语句之前
p request.env
然后再次尝试发送请求,找到您的头并基于它进行比较。
注:
status :ok
aka 200 OK设置在块的末尾,因为当有人向sinatra发送请求时,它应该返回一些内容,否则将发生500内部服务器错误。