Skip to content

Commit

Permalink
add tls dialer
Browse files Browse the repository at this point in the history
  • Loading branch information
phuslu committed Oct 26, 2024
1 parent cf59546 commit ad6a227
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 2 deletions.
4 changes: 2 additions & 2 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,13 +56,13 @@ func (c *Client) exchange(ctx context.Context, req, resp *Message) error {

_, err = conn.Write(req.Raw)
if err != nil {
return nil
return err
}

resp.Raw = resp.Raw[:cap(resp.Raw)]
n, err := conn.Read(resp.Raw)
if err != nil {
return nil
return err
}

resp.Raw = resp.Raw[:n]
Expand Down
56 changes: 56 additions & 0 deletions client_dialer.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package fastdns

import (
"context"
"crypto/tls"
"fmt"
"io"
"net"
Expand Down Expand Up @@ -66,6 +67,61 @@ func (d *UDPDialer) put(conn net.Conn) {
d.conns <- conn
}

// TLSDialer is a custom dialer for creating TLS connections.
// It manages a pool of connections to optimize performance in scenarios
// where multiple TLS connections to the same server are required.
type TLSDialer struct {
// Addr specifies the remote TLS address that the dialer will connect to.
Addr *net.TCPAddr

TLSConfig *tls.Config

// Timeout specifies the maximum duration for a query to complete.
// If a query exceeds this duration, it will result in a timeout error.
Timeout time.Duration

// MaxConns limits the maximum number of TLS connections that can be created
// and reused. Once this limit is reached, no new connections will be made.
// If not set, use 64 as default.
MaxConns uint16

once sync.Once
conns chan net.Conn
}

func (d *TLSDialer) DialContext(ctx context.Context, network, addr string) (conn net.Conn, err error) {
return d.get()
}

func (d *TLSDialer) get() (_ net.Conn, err error) {
d.once.Do(func() {
if d.MaxConns == 0 {
d.MaxConns = 64
}
d.conns = make(chan net.Conn, d.MaxConns)
for range d.MaxConns {
var c *tls.Conn
c, err = tls.DialWithDialer(&net.Dialer{Timeout: d.Timeout}, "tcp", d.Addr.String(), d.TLSConfig)
if err != nil {
break
}
d.conns <- c
}
})

if err != nil {
return
}

c := <-d.conns

return c, nil
}

func (d *TLSDialer) put(conn net.Conn) {
d.conns <- conn
}

// HTTPDialer is a custom dialer for creating HTTP connections.
// It allows sending HTTP requests with a specified endpoint, user agent, and transport configuration.
type HTTPDialer struct {
Expand Down

0 comments on commit ad6a227

Please sign in to comment.