从服务器角度进行 HTTP 跟踪

HTTP Tracing from server perspective

在 Go 1.7 中引入了 http 跟踪,但它仅从客户端角度起作用。是否有可能从服务器的角度以某种方式跟踪请求,我的意思是我想添加一些挂钩,例如在建立连接时。它应该作为中间件实现还是什么?

http.HandlerFunc(func(w http.ResponseWriter, r *http.Request)

对服务器端跟踪的支持很早就在 Go 1.3. Create your own http.Server 中添加了,并在 Server.ConnState 字段中设置了回调函数。

// ConnState specifies an optional callback function that is
// called when a client connection changes state. See the
// ConnState type and associated constants for details.
ConnState func(net.Conn, ConnState) // Go 1.3

http.ConnState 通知回调的时间/连接状态的详细信息。

// StateNew represents a new connection that is expected to
// send a request immediately. Connections begin at this
// state and then transition to either StateActive or
// StateClosed.
StateNew ConnState = iota

// StateActive represents a connection that has read 1 or more
// bytes of a request. The Server.ConnState hook for
// StateActive fires before the request has entered a handler
// and doesn't fire again until the request has been
// handled. After the request is handled, the state
// transitions to StateClosed, StateHijacked, or StateIdle.
// For HTTP/2, StateActive fires on the transition from zero
// to one active request, and only transitions away once all
// active requests are complete. That means that ConnState
// cannot be used to do per-request work; ConnState only notes
// the overall state of the connection.
StateActive

// StateIdle represents a connection that has finished
// handling a request and is in the keep-alive state, waiting
// for a new request. Connections transition from StateIdle
// to either StateActive or StateClosed.
StateIdle

// StateHijacked represents a hijacked connection.
// This is a terminal state. It does not transition to StateClosed.
StateHijacked

// StateClosed represents a closed connection.
// This is a terminal state. Hijacked connections do not
// transition to StateClosed.
StateClosed

一个简单的例子:

srv := &http.Server{
    Addr: ":8080",
    ConnState: func(conn net.Conn, cs http.ConnState) {
        fmt.Println("Client:", conn.RemoteAddr(), "- new state:", cs)
    },
}
log.Fatal(srv.ListenAndServe())

正在向上述服务器发出请求:

curl localhost:8080

服务器输出将是:

Client: 127.0.0.1:39778 - new state: new
Client: 127.0.0.1:39778 - new state: active
Client: 127.0.0.1:39778 - new state: idle
Client: 127.0.0.1:39778 - new state: closed