When I try to copy from a Reader to a Writer manually, I notice that this works:
func fromAToB(a, b net.Conn) {
buf := make([]byte, 1024*32)
for {
n, err := a.Read(buf)
if n > 0 {
if err != nil {
log.Fatal(err)
}
b.Write(buf[0:n])
}
}
}
But this doesn't
func fromAToB(a, b net.Conn) {
buf := make([]byte, 1024*32)
for {
_, err := a.Read(buf)
if err != nil {
log.Fatal(err)
}
b.Write(buf)
}
}
So the questions are:
if n>0
necessary?EDIT: The second snippet runs fine without any runtime error, just that the behavior is not correct. I want to know what is the effect of that n>0
check and what will happen under the surface when I remove it.
There's already a function io.Copy
to do exactly this. You can see how it's implemented for a good example. It works with all io.Reader
/io.Writer
types.
I figured it out: without n
, it will write the whole buffer (32*1024 bytes) to the Writer instead of just n
bytes, and that's the source of the weird behavior.