如何在Go语言中正确设置ldapsearch的超时时间?
如何设置go-ldap中ldapsearch的超时时间
SearchRequest.TimeLimit的单位
SearchRequest.TimeLimit的单位是秒,这遵循LDAP协议(RFC 4511)的标准定义,用于限制LDAP服务器执行搜索操作的最长时长。超过该时间后,服务器会终止搜索并返回已检索到的结果。
设置搜索超时的示例
创建SearchRequest时,直接传入秒数作为TimeLimit参数即可:
import "github.com/go-ldap/ldap/v3" // 构造搜索请求,设置10秒的服务器端搜索超时 searchReq := ldap.NewSearchRequest( "dc=example,dc=com", ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, // SizeLimit:返回结果的最大数量,0表示无限制 10, // TimeLimit:服务器执行搜索的最长时间(秒) false, "(objectClass=*)", []string{"cn", "mail"}, nil, ) // 执行搜索 result, err := conn.Search(searchReq) if err != nil { // 处理错误 }
区分客户端与服务器端超时
需要注意TimeLimit是服务器端的执行时间限制,若要控制客户端层面的超时(比如网络连接超时、等待响应的超时),需在建立连接或执行搜索时设置客户端超时:
import "time" import "context" import "github.com/go-ldap/ldap/v3" // 设置5秒的客户端连接超时 conn, err := ldap.DialURL("ldap://ldap.example.com", ldap.DialWithTimeout(5*time.Second)) if err != nil { // 处理连接错误 } defer conn.Close() // 使用Context设置15秒的客户端搜索响应超时 ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) defer cancel() result, err := conn.SearchWithContext(ctx, searchReq) if err != nil { // 处理超时或其他错误 }
内容的提问来源于stack exchange,提问作者fpawel
相关产品推荐
相关产品推荐

