network/server_options.go

74 lines
1.7 KiB
Go
Raw Normal View History

2022-10-11 17:36:09 +08:00
package network
import (
"crypto/tls"
"git.hpds.cc/Component/network/auth"
2023-04-05 16:15:59 +08:00
"git.hpds.cc/Component/network/log"
"github.com/quic-go/quic-go"
)
const (
// DefaultListenAddr is the default address to listen.
DefaultListenAddr = "0.0.0.0:9000"
2022-10-11 17:36:09 +08:00
)
2023-04-05 16:15:59 +08:00
// ServerOption is the option for server.
type ServerOption func(*serverOptions)
2022-10-11 17:36:09 +08:00
// ServerOptions are the options for HPDS Network server.
2023-04-05 16:15:59 +08:00
type serverOptions struct {
quicConfig *quic.Config
tlsConfig *tls.Config
addr string
auths map[string]auth.Authentication
alpnHandler func(proto string) error
}
func defaultServerOptions() *serverOptions {
opts := &serverOptions{
quicConfig: DefaultQuicConfig,
tlsConfig: nil,
addr: DefaultListenAddr,
auths: map[string]auth.Authentication{},
}
opts.alpnHandler = func(proto string) error {
log.Infof("client alpn proto", "component", "server", "proto", proto)
return nil
}
return opts
2022-10-11 17:36:09 +08:00
}
// WithAddr sets the server address.
func WithAddr(addr string) ServerOption {
2023-04-05 16:15:59 +08:00
return func(o *serverOptions) {
o.addr = addr
2022-10-11 17:36:09 +08:00
}
}
// WithAuth sets the server authentication method.
func WithAuth(name string, args ...string) ServerOption {
2023-04-05 16:15:59 +08:00
return func(o *serverOptions) {
if a, ok := auth.GetAuth(name); ok {
a.Init(args...)
if o.auths == nil {
o.auths = make(map[string]auth.Authentication)
}
o.auths[a.Name()] = a
2022-10-11 17:36:09 +08:00
}
}
}
// WithServerTLSConfig sets the TLS configuration for the server.
func WithServerTLSConfig(tc *tls.Config) ServerOption {
2023-04-05 16:15:59 +08:00
return func(o *serverOptions) {
o.tlsConfig = tc
2022-10-11 17:36:09 +08:00
}
}
// WithServerQuicConfig sets the QUIC configuration for the server.
func WithServerQuicConfig(qc *quic.Config) ServerOption {
2023-04-05 16:15:59 +08:00
return func(o *serverOptions) {
o.quicConfig = qc
2022-10-11 17:36:09 +08:00
}
}