Created
April 5, 2017 15:47
-
-
Save ismasan/76f0e6b8cf118bcdcfc8bcd9f4994a10 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 'uri' | |
| require 'net/http' | |
| require 'json' | |
| # simple SSE client in Ruby | |
| def stream(url, query = nil, parser, &block) | |
| parts = URI.split(url) | |
| uri = URI(url) | |
| if query | |
| uri.query = URI.encode_www_form query | |
| end | |
| Net::HTTP.start(uri.host, uri.port, :use_ssl => (uri.scheme == 'https')) do |http| | |
| request = Net::HTTP::Get.new uri.request_uri | |
| if parts[1] # user info | |
| request.basic_auth *parts[1].split(':') | |
| end | |
| http.request request do |response| | |
| response.read_body do |chunk| | |
| yield parser.call(chunk) | |
| end | |
| end | |
| end | |
| end | |
| sse_json_parser = ->(chunk) { | |
| str = chunk.to_s.gsub(/^data:\s*/, "") | |
| JSON.parse str | |
| } | |
| stream "https://foo:[email protected]/stream", sse_json_parser do |chunk| | |
| puts chunk.inspect | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment