Last active
July 20, 2021 17:42
-
-
Save gohumble/d76e537d0fe8c714d32763fbf0c4da0d 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
func (c *Connection) duplexPipe() { | |
upstreamChannel := chanFromConnection(c.upstream) | |
clientChannel := chanFromConnection(c.client) | |
for { | |
select { | |
case b1 := <-upstreamChannel: | |
if b1 == nil { | |
return | |
} else { | |
c.client.Write(b1) | |
} | |
case b2 := <-clientChannel: | |
if b2 == nil { | |
return | |
} else { | |
c.upstream.Write(b2) | |
} | |
} | |
} | |
} | |
func chanFromConnection(tcpConnection net.Conn) chan []byte { | |
channel := make(chan []byte) | |
go func() { | |
b := make([]byte, 2<<10) | |
for { | |
n, err := tcpConnection.Read(b) // --- blocking operation --- | |
if n > 0 { | |
res := make([]byte, n) | |
copy(res, b[:n]) | |
channel <- res | |
} | |
if err != nil { | |
close(channel) | |
return | |
} | |
} | |
}() | |
return channel | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment