Golang writing to a socket without worrying about incomplete data

Viewed 212

We all know that that the Write method does not guarantee writing tall the bytes from the buffer. Therefore the canonical way of writing bytes to a asocket using the raw Write method is like so

//how many bytes we have written
written := 0 

for written < len(msg){
    //write the bytes from buffer that havent been witten yet
    wr, err := conn.Write(msg[written:])

    if err != nil{
        return;
    }

    written += wr
}

Now let's say I dont want to use such low-level techniques and want to use a function that does this for me. Which function from the standard library should I use?

1 Answers

The canonical way to write bytes to a socket is:

_, err := conn.Write(msg)
if err != nil{
    // handle error
}

There's no need to loop because Write returns an error if the full buffer is not written. Write is different from Read in this regard. Read can succeed without filling the buffer.

Related