gpt4 book ai didi

从服务器角度进行 HTTP 跟踪

转载 作者:IT王子 更新时间:2023-10-29 02:00:44 26 4
gpt4 key购买 nike

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

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

最佳答案

对服务器端跟踪的支持很早以前就添加了,在 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

关于从服务器角度进行 HTTP 跟踪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55883292/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com