1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
|
#!/usr/bin/env ruby
# Require the required libraries:
require 'async'
require 'async/io/host_endpoint'
require 'async/io/ssl_endpoint'
require 'async/http/server'
require 'async/http/client'
require 'localhost'
# The (self-signed) authority to use:
hostname = "localhost"
authority = Localhost::Authority.fetch(hostname)
# The server app:
app = lambda do |request|
Protocol::HTTP::Response[200, {}, ["Hello World"]]
end
# Bind to the specified host:
endpoint = Async::IO::Endpoint.tcp(hostname, "8080")
# Prepare the server, endpoint will be used for `bind`:
server_endpoint = Async::IO::SSLEndpoint.new(endpoint, ssl_context: authority.server_context)
server = Async::HTTP::Server.new(app, server_endpoint, protocol: Async::HTTP::Protocol::HTTP1, scheme: "https")
# Prepare the client, endpoint will be used for `connect`:
client_endpoint = Async::IO::SSLEndpoint.new(endpoint, ssl_context: authority.client_context)
client = Async::HTTP::Client.new(client_endpoint, protocol: Async::HTTP::Protocol::HTTP1, scheme: "https", authority: authority)
# Run the reactor:
Async do |task|
# Start the server task:
server_task = task.async do
server.run
end
# Connect to the server:
response = client.get("/")
puts "Status: #{response.status}\n#{response.read}"
# Stop the server:
server_task.stop
end
|