什么错误输出到 http.Server 的 ErrorLog 结构字段?

What errors are outputted to http.Server's ErrorLog struct field?

我正在尝试了解 http.Server 结构中 ErrorLog 结构字段的用途。根据它的名字,我怀疑这些是某种错误,但是哪些错误呢?

什么会触发在那里输出错误?断网? http 请求太大?

package main

import (
    "log"
    "net/http"
)

func main() {
    _ = &http.Server{
        ErrorLog: log.Default(), // what errors are outputted here?
    }
}

官方documentation概述了该字段的使用方式:

    // ErrorLog specifies an optional logger for errors accepting
    // connections, unexpected behavior from handlers, and
    // underlying FileSystem errors.
    // If nil, logging is done via the log package's standard logger.
    ErrorLog *log.Logger // Go 1.3

实际上,该字段是在 *http.Serverlogf 方法中访问的。您可以检查调用该方法的位置。简而言之(并非详尽无遗):

  • 关于处理 HTTP 请求的恐慌(connserve(ctx context.Context)
  • 关于 TLS 握手错误
  • 服务器 Serve(l net.Listener) error 错误
  • 将 non-empty 数据写入响应,如果连接是 hijacked
  • 如果Content-Length无效
  • 如果您多次调用 WriteHeader(code int) 同一响应
  • 如果Content-Length和非identityTransfer-Encodingheaders一起使用
 type serverErrorLogWriter struct{}
    
    func (*serverErrorLogWriter) Write(p []byte) (int, error) {
        m := string(p)
        if strings.HasPrefix(m, "http: TLS handshake error") && strings.HasSuffix(m, ": EOF\n") {
            // handle EOF error
        } else {
            // handle other errors
        }
        return len(p), nil
    }
    
    func newServerErrorLog() *log.Logger {
        return log.New(&serverErrorLogWriter{}, "", 0)
    }

然后

ErrorLog:          log.New(&serverErrorLogWriter{}, "", 0)