http - 从服务器的角度来看 HTTP 跟踪
问题描述
在 Go 1.7 中引入了 http 跟踪,但它只能从客户端的角度工作。是否有可能从服务器的角度跟踪请求,我的意思是我想添加一些钩子,例如在建立连接时。它应该作为中间件实现还是什么?
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
推荐阅读
- android - Android Accessibility 服务同时与多个开关交互
- azure - 如何自动将数据从 CSV 文件加载到 Azure SQL
- javascript - 在本地使用 bootstrapValidator 发送静态数据
- javascript - 在 html 页面中自定义计数器
- flutter - 如何更改 CupertinoAlertDialog 的背景颜色?
- python-3.x - 如何指定叶热图中的颜色?
- javascript - 新手如何使用 d3.csv?它不起作用,我做错了什么?
- java - Java 中的 XSLT 转换能否在无效标签上输出警告
- python - 在数据框中插入缺失的行(可变索引范围)
- kubernetes - Kubernetes 上的 WSO2 APIM 模式 2 部署