如何在Golang中的bufio.Writer中缓冲数据

When the buffered io writer is used, and some error occur, how can I perform the retry? For example, I've written 4096B using Write() and an error occur when the bufwriter automatically flushes the data. Then I want to retry writing the 4096B, how I can do it? It seems I must keep a 4096B buffer myself to perform the retrying. Othersize I'm not able to get the data failed to be flushed. Any suggestions?

You'll have to use a custom io.Writer that keeps a copy of all data, so that it can be re-used in case of a retry.

This functionality is not part of the standard library, but shouldn't be hard to implement yourself.

When bufio.Writer fails on a Write(..) it will return the amount of bytes written (n) to the buffer the reason why (err).

What you could do is the following. (Note I haven't yet tried this so it may be a little wrong and could use some cleaning up)

func writeSomething(data []byte, w *bufio.Writer) (err error) {
  var pos, written int = 0

  for pos != len(data) {
    written, err = w.Write(data[pos:])
    if err != nil {
      if err == io.ErrShortWrite {
        pos += written // Write was shot. Update pos and keep going
        continue 
      } else netErr, ok := err.(net.Error); ok && netErr.Temporary() {
        continue // Temporary error, don't update pos so it will try writing again
      } else {
        break // Unrecoverable error, bail
      }
    } else {
      pos += written
    }
  }

  return nil
}