如何从http.ResponseWriter中获取当前响应的长度

huangapple go评论115阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2012年12月21日 03:24:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/13979078.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定