What does the int returned by ResponseWriter.Write mean?

Viewed 570

https://golang.org/src/net/http/server.go#L139

I would've expected the signature to be Write([]byte) error, not Write([]byte) (int, error). I also can't find any good explanation from looking through usages, and the documentation comment doesn't explain the return values.

What does the returned int mean?

1 Answers

The ResponseWriter.Write() method is to implement the general io.Writer interface, so a value of http.ResponseWriter can be used / passed to any utility function that accepts / works on an io.Writer.

io.Writer has exactly one Write() method and it details exactly the "contract" of Write, what it should return and how it should work:

type Writer interface {
    Write(p []byte) (n int, err error)
}

Write writes len(p) bytes from p to the underlying data stream. It returns the number of bytes written from p (0 <= n <= len(p)) and any error encountered that caused the write to stop early. Write must return a non-nil error if it returns n < len(p).

Related