YouTube Summaries | The Most Efficient Struct Configuration Pattern for Golang
December 4th, 2023
Introduction
This video introduces a Go programming pattern designed for configuring structures, specifically targeting libraries or modules. This pattern relies on “option functions” and a “default options” function to offer users a flexible approach to structure configuration. As usual, this summary will help to further cement my learnings from the video, and hopefully provides value to you as well.
Basic Structure Configuration
The code below showcases the conventional method of creating a server structure with configurable options like max connections, ID, and TLS parameters. This often involves passing multiple arguments to the constructor, resulting in verbosity and potential complexity.
type Server struct {
MaxConnections int
ID string
TLS bool
}
func NewServer(maxConn int, id string, tls bool) *Server {
return &Server{
MaxConnections: maxConn,
ID: id,
TLS: tls,
}
}
Optimization with Option Functions
The optimization discussed in this video involves introducing an “opt thunk” type and a “default options” function. The default options function provides default values for configuration options, and the server constructor now accepts a slice of option functions, allowing users to customize configurations.
type OptThunk func(*Options)
type Options struct {
MaxConnections int
ID string
TLS bool
}
func DefaultOptions() *Options {
return &Options{
MaxConnections: 10,
ID: "default",
TLS: false,
}
}
func NewServer(opts ...OptThunk) *Server {
options := DefaultOptions()
for _, opt := range opts {
opt(options)
}
return &Server{
MaxConnections: options.MaxConnections,
ID: options.ID,
TLS: options.TLS,
}
}
Flexible Configuration
Users can provide no options, one option, or multiple options by utilizing ellipses in the constructor. This design choice allows users to tailor configurations according to their specific requirements.
server1 := NewServer() // Default options
server2 := NewServer(WithTLS(true)) // Configuring TLS
server3 := NewServer(WithMaxConnections(20), WithID("customID")) // Customizing multiple options
Demonstration of Option Functions
The video demonstrates the creation of option functions for specific configurations, like TLS and max connections. These functions modify the default options, providing a clear and concise method for users to customize their structures.
func WithTLS(tls bool) OptThunk {
return func(o *Options) {
o.TLS = tls
}
}
func WithMaxConnections(maxConn int) OptThunk {
return func(o *Options) {
o.MaxConnections = maxConn
}
}
Pattern Application in Practice
The practical showcase illustrates how users can easily configure a server with specific options like TLS or max connections, resulting in a structure that accurately reflects the desired configuration.
server := NewServer(WithTLS(true), WithMaxConnections(30))