2016. december 15., csütörtök 17:36:47 UTC+1 időpontban 彭望 a következőt írta: > > Hi all, I'm doing a simple message serialization, message defines like > below: > type Envelope struct { > Magic uint32 > DataSize uint32 > } > > type Message struct { > Envelope > Data []byte > } > > and I want to implement the io.WriterTo interface for Message > func (m *Message) WriteTo(w io.Writer) (n int64, err error) { > err = binary.Write(w, binary.BigEndian, &m.Envelope) > if err != nil { > // here, how should I return a proper n? Since w maybe > *net.TCPConn and binary.Write maybe write 1 bytes and peer has dropped the > connection. > return 0, fmt.Errorf("Write message envelope error: %s", err) > } > > // multiple lines skipped > } >
If you really want to know the number of bytes written, wrap w in a counting writer, which counts the bytes written. > type countingWriter struct { > w io.Writer > N int64 > } > func (w *countingWriter) Write(p []byte) (int, error) { > n, err := w.w.Write(p) > w.N += int64(n) > return n, err > } > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.