简体   繁体   中英

Why doesn't http.ResponseWriter implement a response stream End() call?

In Node.js, to finish writing to a stream (and in theory with HTTP, tell the client there is no more data), we use response.end() . Using Go, the ResponseWriter interface is like:

type ResponseWriter interface {
    Header() Header
    Write([]byte) (int, error)
    WriteHeader(statusCode int)
}

so my question is twofold:

  1. How can we get the HTTP status code from the ResponseWriter?
  2. more importantly: How does Go (and routers like Mux) know when the programmer is done writing to the ResponseWriter? Is it when the goroutine ends? What if you wanted to finish the response before the goroutine stack is empty? Seems like an implementation flaw to not have an End() method in the ResponseWriter interface.
  1. This is not possible with the standard http.ResponseWriter implementation. But this is an interface, so it's easy to write your own implementation that records the status. The beginning of a simple implementation might be:

     type statusRecorder struct { http.ResponseWriter status int } func (r *statusRecorder) WriteHeader(status int) { r.status = status r.ResponseWriter.WriteHeader(status) }

    While this may seem like a limitation of the API, it's actually the opposite. By using an interface, it is possible to create an implementation that does anything, or records any information you want, rather than being limited to whatever functionality the standard library authors may have decided to expose.

  2. When the handler returns, it is done. If you wish to do additional work after sending a response, you can spawn a goroutine to continue operating after the main handler returns.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM