PPysolate SpineREAD THE CODE · UNDERSTAND THE SYSTEM
课程与章节
源码索引 / CURRENT IMPLEMENTATION

learning/go-patterns/patterns/construction/construction.go

64 行 · 点击行号可定位;函数链接随声明位置更新,不手填行号。

跳到函数 / 声明
// Package construction demonstrates functional options for optional configuration.
package construction

import (
	"net"
	"strconv"
)

// Config contains the settings used by Server.
type Config struct {
	Host   string
	Port   int
	Secure bool
}

// Option changes one part of a Server configuration.
type Option func(*Config)

// WithHost configures the listening host.
func WithHost(host string) Option {
	return func(config *Config) {
		config.Host = host
	}
}

// WithPort configures the listening port.
func WithPort(port int) Option {
	return func(config *Config) {
		config.Port = port
	}
}

// WithSecure configures whether the server uses a secure transport.
func WithSecure(secure bool) Option {
	return func(config *Config) {
		config.Secure = secure
	}
}

// Server is a configured endpoint. Its configuration is immutable after construction.
type Server struct {
	config Config
}

// NewServer constructs a Server with useful defaults and optional overrides.
func NewServer(options ...Option) *Server {
	config := Config{Host: "127.0.0.1", Port: 8080}
	for _, option := range options {
		if option != nil {
			option(&config)
		}
	}
	return &Server{config: config}
}

// Config returns a copy of the server configuration.
func (s *Server) Config() Config {
	return s.config
}

// Address returns the host:port endpoint, including correct IPv6 formatting.
func (s *Server) Address() string {
	return net.JoinHostPort(s.config.Host, strconv.Itoa(s.config.Port))
}