如何解决如何在* tls.Conn上设置SetKeepAlivePeriod
我想增加HTTP和HTTPS请求的TCP连接的保持期。
对于HTTP请求,可以这样完成:
package main
import (
"fmt"
"io"
"log"
"net"
"net/http"
"time"
)
func main() {
server := &http.Server{Addr: ":8080",Handler: http.HandlerFunc(func(w http.ResponseWriter,r *http.Request) {
io.WriteString(w,"Hello,World!")
})}
server.ConnState = func(conn net.Conn,state http.ConnState) {
if state == http.StateNew {
if err := conn.(*net.TCPConn).SetKeepAlivePeriod(1000 * time.Second); err != nil {
fmt.Println("Could not set keep alive period",err)
} else {
fmt.Println("update keep alive period")
}
}
}
log.Fatal(server.ListenAndServe())
}
对于HTTPS请求,无法通过server.ConnState
完成此操作,因为将在函数内部传递的net.Conn
是*tls.Conn
。此连接不会公开类似SetKeepAlivePeriod
的函数,也不会提供对基础*net.TCPConn
的访问。
func main() {
server := &http.Server{Addr: ":8080",state http.ConnState) {
if state == http.StateNew {
tlsConn := conn.(*tls.Conn)
// how to set SetKeepAlivePeriod
}
}
log.Fatal(server.ListenAndServeTLS("../example.crt","../example.key"))
}
如何设置tls连接的保留期限?
解决方法
(至少)有两种方法可以做到这一点:
使用net.ListenConfig:
net.ListenConfig
对象具有一个KeepAlive time.Duration
字段。如果为非零值,则将用于在接受的连接上设置保持活动状态(例如:for TCP on posix)。
您可以将侦听器传递给ServeTLS
:
server := &http.Server{...}
lc := net.ListenConfig{KeepAlive: 1000 * time.Second}
ln,err := lc.Listen(context.Background(),"tcp",":8080")
if err != nil {
panic(err)
}
defer ln.Close()
log.Fatal(server.ServeTLS(ln,"../example.crt","../example.key"))
如前所述,接受的TCP连接将自动启用保持活动状态,并将周期设置为指定值。
使用tls.Config回调:
您可以通过设置tls.Config net.Conn
或tls.Conn
回调来访问GetConfigForClient
下的GetCertificate
。
只要返回nil
即可使TLS代码恢复为默认行为,那么使用哪一个都没关系。重要的部分是访问tls.ClientHelloInfo,该{{3}}具有指向基础连接的.Conn
字段。这将是net.TCPConn
。
setTCPKeepAlive := func(clientHello *tls.ClientHelloInfo) (*tls.Config,error) {
// Check that the underlying connection really is TCP.
if tcpConn,ok := clientHello.Conn.(*net.TCPConn); ok {
if err := tcpConn.SetKeepAlivePeriod(1000 * time.Second); err != nil {
fmt.Println("Could not set keep alive period",err)
} else {
fmt.Println("update keep alive period")
}
} else {
fmt.Println("TLS over non-TCP connection")
}
// Make sure to return nil,nil to let the caller fall back on the default behavior.
return nil,nil
}
tlsConfig := &tls.Config{
...
GetConfigForClient: setTCPKeepAlive,...
}
server := &http.Server{
Addr: ":8080",TLSConfig: tlsConfig,}
server.ListenAndServeTLS("../example.crt","../example.key")
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。