有什么办法可以获取“ http:劫持连接上的response.WriteHeader”错误的堆栈跟踪信息?

Our web application is logging a large number of 'http: response.WriteHeader on hijacked connection' messages to stderr.

Is there any way to make the http library output a stack trace, or additional debugging information, along with this message, (or upgrade it to an error) to make it possible to track down where in our application this is occurring?

If you are using a debugger, set a breakpoint on the line where the message is logged. Examine the stack from there.

If not using a debugger, then temporarily add a call to panic at the line and rebuild the net/http package with go install net/http. The stack trace will show the cause of the problem.

Another option is to create an io.Writer that calls debug.PrintStack on every call to Write. Use this writer to create a log.Logger. Set this logger as the server's ErrorLog. Examine the printed stack traces to find the cause of the error.

Since the error is never returned, and written directly to the http.Server.ErrorLog, that is the only place you could intercept it.

You can run it in a debugger and break at that point, but that may not be useful if this is running in production.

You can create a new *log.Logger with an io.Writer which adds the stack trace to the output when it encounters that particular message.

type stackWriter struct {
    w io.Writer
}
func (s stackWriter) Write(d []byte) (int, error) {
    if bytes.Contains(d, []byte("WriteHeader on hijacked connection")) {
        s.w.Write(debug.Stack())
    }
    return s.w.Write(d)
}

Another option of course is to modify net/http/server.go to print the stack at that point.