server-go/connection-handler.go

93 lines
2.1 KiB
Go
Raw Normal View History

2018-04-04 13:28:35 +00:00
package server
import (
"crypto/tls"
"net"
2018-04-13 07:11:43 +00:00
"sync/atomic"
2018-04-04 13:28:35 +00:00
"time"
)
type ConnectionHandler interface {
GetConcurrency() int
GetKeepAlive() time.Duration
GetHandshakeTimeout() time.Duration
GetTLSConfig() *tls.Config
Listener(serverCtx ServerCtx) (net.Listener, error)
}
type ConnectionHandlers struct {
// The maximum number of concurrent connections the server may serve.
//
// DefaultConcurrency is used if not set.
2018-04-10 04:02:00 +00:00
Network string `json:"network"`
Address string `json:"address"`
Concurrency int `json:"concurrency"`
KeepAlive time.Duration `json:"keepAlive"`
HandshakeTimeout time.Duration `json:"handshakeTimeout"`
2018-04-13 11:48:45 +00:00
TLSConfig *tls.Config `json:"-"`
2018-04-13 07:11:43 +00:00
validated atomic.Value
2018-04-04 13:28:35 +00:00
}
func (ch *ConnectionHandlers) Listener(serverCtx ServerCtx) (net.Listener, error) {
2018-04-10 04:02:00 +00:00
l, err := net.Listen(ch.Network, ch.Address)
if nil != err {
return nil, err
}
return l, nil
2018-04-04 13:28:35 +00:00
}
func (ch *ConnectionHandlers) GetConcurrency() int {
return ch.Concurrency
}
func (ch *ConnectionHandlers) GetKeepAlive() time.Duration {
return ch.KeepAlive
}
func (ch *ConnectionHandlers) GetHandshakeTimeout() time.Duration {
return ch.HandshakeTimeout
}
func (ch *ConnectionHandlers) GetTLSConfig() *tls.Config {
return ch.TLSConfig
}
2018-04-12 05:55:01 +00:00
func (ch *ConnectionHandlers) Clone() *ConnectionHandlers {
return &ConnectionHandlers{
Network: ch.Network,
Address: ch.Address,
Concurrency: ch.Concurrency,
KeepAlive: ch.KeepAlive,
HandshakeTimeout: ch.HandshakeTimeout,
TLSConfig: ch.TLSConfig,
2018-04-13 07:11:43 +00:00
validated: ch.validated,
2018-04-12 05:55:01 +00:00
}
}
2018-04-04 13:28:35 +00:00
func (ch *ConnectionHandlers) Validate() error {
2018-04-13 07:11:43 +00:00
if nil != ch.validated.Load() {
return nil
}
ch.validated.Store(true)
2018-04-04 13:28:35 +00:00
if ch.Concurrency <= 0 {
ch.Concurrency = DefaultConcurrency
}
if ch.KeepAlive <= 0 {
ch.KeepAlive = DefaultKeepAlive
2018-04-13 06:37:27 +00:00
} else {
ch.KeepAlive = ch.KeepAlive * time.Second
2018-04-04 13:28:35 +00:00
}
if ch.HandshakeTimeout <= 0 {
ch.HandshakeTimeout = DefaultHandshakeTimeout
2018-04-13 06:37:27 +00:00
} else {
ch.HandshakeTimeout = ch.HandshakeTimeout * time.Second
2018-04-04 13:28:35 +00:00
}
2018-04-13 06:37:27 +00:00
2018-04-04 13:28:35 +00:00
return nil
}