从服务器角度进行HTTP跟踪

问题描述 投票:1回答:1

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

http.HandlerFunc(func(w http.ResponseWriter, r *http.Request)
http go server tracing
1个回答
2
投票

Go 1.3中,之前添加了对服务器端跟踪的支持。创建自己的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
© www.soinside.com 2019 - 2024. All rights reserved.