`package main
import ( “crypto/tls” “fmt” “time” )
// Business entity
type Server struct { Addr string Port int Protocol string Timeout time.Duration MaxConns int TLS *tls.Config }
// Higher order function
type Option func(*Server)
func Protocol(p string) Option { return func(server *Server) { server.Protocol = p } }
func Timeout(timeout time.Duration) Option { return func(server *Server) { server.Timeout = timeout } }
func MaxConns(maxconns int) Option { return func(server *Server) { server.MaxConns = maxconns } }
func TLS(tls *tls.Config) Option { return func(server *Server) { server.TLS = tls } }
func NewServer(addr string, port int, options … func(*Server)) (*Server, error) { serv := Server{ Addr: addr, Port: port, Protocol: “tcp”, Timeout: 30 * time.Second, MaxConns: 1000, TLS: nil, }
for _, option := range options {
option(&serv)
}
return &serv, nil
Copy the code
}
Func main() {server, _ := NewServer(“127.0.0.1”, 9999, Protocol(“UDP”), MaxConns(100)) fmt.Println(server.Protocol) fmt.Println(server.MaxConns) }`