Created
March 18, 2019 06:22
-
-
Save elct9620/9e45afd7223360d8cdb8a7201a66a922 to your computer and use it in GitHub Desktop.
Golang's io.TeeReader in Ruby implement use prepend
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
# frozen_string_literal: true | |
require 'socket' | |
# :nodoc: | |
module TeeReader | |
attr_reader :buffer | |
def initialize(*args) | |
super | |
@buffer = StringIO.new | |
end | |
def read(*args) | |
_, buffer = args | |
buffer = super | |
writed = @buffer.write(buffer) | |
@buffer.seek(@buffer.pos - writed) | |
buffer | |
end | |
end | |
# :nodoc: | |
class VHostSocket < TCPSocket | |
prepend TeeReader | |
end | |
s = VHostSocket.new('google.com', 80) | |
s.write "GET / HTTP/1.1\r\n\r\n" | |
puts '=== READING ===' | |
pp s.read(1024) | |
puts '=== Buffer ===' | |
pp s.buffer.read(1024) | |
# Need override `read_nonblock` | |
puts '=== NON BLOCKING ===' | |
pp s.read_nonblock(1024, exception: false) | |
puts '=== Buffer Non Blocking ===' | |
pp s.buffer.read_nonblock(1024, exception: false) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment