Go 特有的模式,使用函数参数实现灵活的配置。
构造函数参数过多,且大部分有默认值。
定义 Option 函数类型,通过变长参数传递配置。
1type Server struct {2 host string3 port int4 timeout time.Duration5 tls bool6}7 8type Option func(*Server)9 10func WithPort(port int) Option {11 return func(s *Server) { s.port = port }12}13 14func WithTimeout(d time.Duration) Option {15 return func(s *Server) { s.timeout = d }16}17 18func WithTLS() Option {19 return func(s *Server) { s.tls = true }20}21 22func NewServer(host string, opts ...Option) *Server {23 s := &Server{24 host: host,25 port: 8080, // 默认值26 timeout: 30 * time.Second,27 }28 for _, opt := range opts {29 opt(s)30 }31 return s32}33 34// 使用35server := NewServer("0.0.0.0",36 WithPort(3000),37 WithTimeout(time.Minute),38 WithTLS(),39)配置 Web3 服务,如 RPC 端点、超时、重试策略等。