Improve service name lookup on TCP routers

This commit is contained in:
Douglas De Toni Machado 2020-11-13 08:48:04 -03:00 committed by GitHub
parent 459200dd01
commit 598dcf6b62
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 96 additions and 1 deletions

View file

@ -10,8 +10,10 @@ import (
// Proxy forwards a TCP request to a TCP service.
type Proxy struct {
address string
target *net.TCPAddr
terminationDelay time.Duration
refreshTarget bool
}
// NewProxy creates a new Proxy.
@ -21,7 +23,18 @@ func NewProxy(address string, terminationDelay time.Duration) (*Proxy, error) {
return nil, err
}
return &Proxy{target: tcpAddr, terminationDelay: terminationDelay}, nil
// enable the refresh of the target only if the address in an IP
refreshTarget := false
if host, _, err := net.SplitHostPort(address); err == nil && net.ParseIP(host) == nil {
refreshTarget = true
}
return &Proxy{
address: address,
target: tcpAddr,
refreshTarget: refreshTarget,
terminationDelay: terminationDelay,
}, nil
}
// ServeTCP forwards the connection to a service.
@ -31,6 +44,15 @@ func (p *Proxy) ServeTCP(conn WriteCloser) {
// needed because of e.g. server.trackedConnection
defer conn.Close()
if p.refreshTarget {
tcpAddr, err := net.ResolveTCPAddr("tcp", p.address)
if err != nil {
log.Errorf("Error resolving tcp address: %v", err)
return
}
p.target = tcpAddr
}
connBackend, err := net.DialTCP("tcp", nil, p.target)
if err != nil {
log.Errorf("Error while connection to backend: %v", err)