英文:
How to get the current response length from a http.ResponseWriter
问题
给定一个已经使用了一些.Write()
的http.ResponseWriter
,能直接获取当前响应的累积长度吗?
我相信这可以通过Hijack
转换来实现,但我想知道是否可以直接实现。
英文:
Given a http.ResponseWriter
that has had some number of .Write()
s done to it, can the current accumulated length of the response be obtained directly?
I'm pretty sure this could be done with a Hijack
conversion, but I'd like to know if it can be done directly.
答案1
得分: 12
即使你知道你得到了什么,底层的http.ResponseWriter
接口的机会很低,有可用的东西。如果你仔细看使用http包的标准ServeHTTP
得到的结构体,你会发现除了劫持它之外,没有其他方法可以得到缓冲区的长度。
作为替代方案,你可以使用影子写入器:
type ResponseWriterWithLength struct {
http.ResponseWriter
length int
}
func (w *ResponseWriterWithLength) Write(b []byte) (n int, err error) {
n, err = w.ResponseWriter.Write(b)
w.length += n
return
}
func (w *ResponseWriterWithLength) Length() int {
return w.length
}
func MyServant(w http.ResponseWriter, r *http.Request) {
lengthWriter := &ResponseWriterWithLength{w, 0}
}
你甚至可以编写自己的http.Server
版本,默认使用ResponseWriterWithLength
进行服务。
英文:
Even if you'd know what you get, underlying the http.ResponseWriter
interface, the chances are low, that there is something usable. If you look closer at the struct you get using the standard ServeHTTP
of the http package, you'll see that there's no way to get to the length of the buffer but hijacking it.
What you can do alternatively, is shadowing the writer:
type ResponseWriterWithLength struct {
http.ResponseWriter
length int
}
func (w *ResponseWriterWithLength) Write(b []byte) (n int, err error) {
n, err = w.ResponseWriter.Write(b)
w.length += n
return
}
func (w *ResponseWriterWithLength) Length() int {
return w.length
}
func MyServant(w http.ResponseWriter, r *http.Request) {
lengthWriter := &ResponseWriterWithLength{w, 0}
}
You might even want to write your own version of http.Server
, which serves the ResponseWriterWithLength
by default.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论