Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I properly write the `Read` and `Write` the `net.Pipe()`

Tags:

go

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()

like image 851
zjk Avatar asked Apr 29 '16 07:04

zjk


1 Answers

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

like image 175
Grzegorz Żur Avatar answered Oct 18 '22 19:10

Grzegorz Żur