参考资料:
GO 编程模式:FUNCTIONAL OPTIONS
package option
import (
"crypto/tls"
"time"
)
type Server struct {
Addr string
Port int
Protocol string
Timeout time.Duration
MaxConns int
TLS *tls.Config
}
func NewServer(addr string, port int, options ...func(*Server)) (*Server, error) {
srv := Server{
Addr: addr,
Port: port,
Protocol: "tcp",
Timeout: 30 * time.Second,
MaxConns: 1000,
TLS: nil,
}
for _, option := range options {
option(&srv)
}
//...
return &srv, nil
}
type Option func(*Server)
func Protocol(p string) Option {
return func(s *Server) {
s.Protocol = p
}
}
func Timeout(timeout time.Duration) Option {
return func(s *Server) {
s.Timeout = timeout
}
}
func MaxConns(maxconns int) Option {
return func(s *Server) {
s.MaxConns = maxconns
}
}
func TLS(tls *tls.Config) Option {
return func(s *Server) {
s.TLS = tls
}
}
main.go
package main
import (
"fmt"
"time"
"functionalOption/option"
)
// 功能选项
func main() {
s1, _ := option.NewServer("localhost", 1024)
s2, _ := option.NewServer("localhost", 2048, option.Protocol("udp"))
s3, _ := option.NewServer("0.0.0.0", 8080, option.Timeout(300*time.Second), option.MaxConns(1000))
fmt.Println(s1)
fmt.Println(s2)
fmt.Println(s3)
}
结果:
&{localhost 1024 tcp 30s 1000 <nil>}
&{localhost 2048 udp 30s 1000 <nil>}
&{0.0.0.0 8080 tcp 5m0s 1000 <nil>}