When you answer using io.Copy, who should be responsible for the error?

Suppose that the server needs to respond to some data with the client, and the data comes from a file on the local disk. Then we write:

n, err := io.Copy(w, f)  // w is the ResponseWriter and f is the *os.File

I think that io.Copy()he writes the header first and then copies the data from fto w.

If errnot nil(say unexpected EOF), the client will still receive a 200 status code, although the response body contains something wrong.

The local disk may be damaged, or the client network may be broken. How can we determine if a errserver or client is calling ?

+4
source share
2 answers

io.Copy Write io.Writer. http.ResponseWriter Write :

// Write writes the data to the connection as part of an HTTP reply.
// If WriteHeader has not yet been called, Write calls WriteHeader(http.StatusOK)
// before writing the data.  If the Header does not contain a
// Content-Type line, Write adds a Content-Type set to the result of passing
// the initial 512 bytes of written data to DetectContentType.
Write([]byte) (int, error)

, WriteHeader:

// WriteHeader sends an HTTP response header with status code.
// If WriteHeader is not called explicitly, the first call to Write
// will trigger an implicit WriteHeader(http.StatusOK).
// Thus explicit calls to WriteHeader are mainly used to
// send error codes.
WriteHeader(int)

, HD , Write 200 OK, , Content-Length, , - , .

HTTP 1.1 chunked transfer encoding HTTP-. , HTTP- -.

@OneOfOne: io.Copy , ; .

, , 4xx 5xx, ?

HTTP, , ; , .

+6

, - , .

, :

 w.Header().Set("Content-Length", strconv.Itoa(fileLen))

, .

, , . , .

, , . HTTP- .

, , . , .

, io.Copy - . ( , TLS , io.Copy,...), , io.Copy. .

: ( ), . io.Copy .

+4

All Articles