I'm trying out the net.Pipe()
. I thought writing the "haha"
string and then reading it back might be a good experiment.
Here is my first version. It blocks on the Write
func TestNetPipe(t *testing.T) {
out1 := make([]byte, 10)
c1, c2 := net.Pipe()
c1.Write([]byte("haha"))
c2.Read(out1)
}
I tried to use a goroutine
func TestNetPipe(t *testing.T) {
out1 := make([]byte, 10)
c1, c2 := net.Pipe()
go func() {
c1.Write([]byte("haha"))
}()
fmt.Printf("%v\n", out1)
c2.Read(out1)
fmt.Printf("%v\n", out1)
}
It works. But I felt there is no guarantee that the Read
will read the whole "haha"
string. It might only read the "hah"
part.
I'm wondering if there is a better way to demo the usage of net.Pipe()
Use ReadAll
function from package io/ioutil
.
As ReadAll
function blocks until EOF the following code needs no synchronization of goroutines. The call of close
method causes the EOF on the stream.
package main
import (
"fmt"
"io/ioutil"
"log"
"net"
)
func main() {
r, w := net.Pipe()
go func() {
w.Write([]byte("haha"))
w.Close()
}()
b, err := ioutil.ReadAll(r)
if err != nil {
log.Fatalf(err.Error())
}
fmt.Println(string(b))
}
Playground
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With