Ruby's Sinatra is actually a bit similar to Python's Flask. I also wrote an example of building services with Flask and using request services in another blog: https://blog.csdn.net/TomorrowAndTuture/article/details/101421425 . They are the simplest examples used, and they are not complicated.
Install the sinatra module first:
gem install sinatra
Server:
# server.rb
require 'sinatra'
configure do
set :bind, 'localhost'
set :port, '1234'
end
get '/get-test' do
'get request success'
end
post '/post-test' do
puts request.body.read
'post request success'
end
Client:
# client.rb
require 'net/https'
domain = "localhost"
port = "1234"
# get 请求
http = Net::HTTP.new(domain, port)
response = http.request_get('/get-test')
puts response.body
# post 请求
post_data = { "aaa" => 1, "bbb" => 2 }
uri = URI.parse("http://#{domain}:#{port}/post-test")
response = Net::HTTP.post_form(uri, post_data)
puts response.body
Server running output:
[root@master ruby_learning]# ruby server.rb
== Sinatra (v2.1.0) has taken the stage on 1234 for development with backup from Thin
2020-12-02 22:23:02 +0800 Thin web server (v1.8.0 codename Possessed Pickle)
2020-12-02 22:23:02 +0800 Maximum connections set to 1024
2020-12-02 22:23:02 +0800 Listening on localhost:1234, CTRL+C to stop
::1 - - [02/Dec/2020:22:23:09 +0800] "GET /get-test HTTP/1.1" 200 19 0.0168
aaa=1&bbb=2
::1 - - [02/Dec/2020:22:23:09 +0800] "POST /post-test HTTP/1.1" 200 20 0.0005
Client running output:
[root@master ruby_learning]# ruby client.rb
get request success
post request success
Of course, if the client just sends get and post requests, there is an easier way (rest-client is a good choice):
gem install rest-client
# client.rb
require 'rest-client'
domain = "localhost"
port = "1234"
# get 请求
response = RestClient.get("http://#{domain}:#{port}/get-test")
puts response
# or
response = RestClient::Request.execute(
method: "get",
url: "http://#{domain}:#{port}/get-test"
)
puts response
# post 请求
post_data = { "aaa" => 1, "bbb" => 2 }
response = RestClient.post("http://#{domain}:#{port}/post-test", post_data)
puts response
# or
post_data = { "aaa" => 1, "bbb" => 2 }
response = RestClient::Request.execute(
method: "post",
url: "http://#{domain}:#{port}/post-test",
payload: post_data
)
puts response
[root@master ruby_learning]# ruby client.rb
get request success
get request success
post request success
post request success