-
-
Save f-mer/727c04e6ec843e92317ef0d76750e748 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "http" | |
HTTP::Server.new(8081) do |ctx| | |
case {ctx.request.method, ctx.request.path} | |
when {"GET", "/sse"} | |
Action.new.call(ctx) | |
else | |
ctx.response.puts <<-HTML | |
<html> | |
<body> | |
<script> | |
const body = document.body | |
const client = new EventSource(document.location.href + 'sse') | |
client.onmessage = function (msg) { | |
const el = document.createElement('div') | |
el.innerText = msg.data | |
body.appendChild(el) | |
} | |
</script> | |
</body> | |
</html> | |
HTML | |
end | |
end.listen | |
class Action | |
include HTTP::Handler | |
def call(ctx : HTTP::Server::Context) | |
call(ctx.request, ctx.response) | |
end | |
def call(req : HTTP::Request, res : HTTP::Server::Response) | |
HTTP::Client.get("http://localhost:8080/") do |log_res| | |
stream(res, log_res.body_io) do |r, w| | |
r.each_line do |line| | |
w.puts "data: #{line}\n\n" | |
w.flush | |
end | |
rescue ex | |
puts ex.inspect | |
end | |
end | |
puts "never gets executed" | |
end | |
def stream(res, io, heartbeat = 5.seconds, &blk : (IO, IO) ->) | |
res.not_nil!.headers["Content-Type"] = "text/event-stream" | |
spawn do | |
blk.call(io, res) | |
end | |
while !res.closed? | |
res.puts ";ok\n\n" | |
res.flush | |
sleep heartbeat | |
end | |
ensure | |
io.close | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "http/server" | |
HTTP::Server.new(8080) do |ctx| | |
ctx.response.headers["Content-Type"] = "text/event-stream" | |
loop do | |
ctx.response.puts "#{Time.now}\n\n" | |
ctx.response.flush | |
sleep 1.second | |
end | |
end.listen |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment