Member-only story

Practical Design Pattern in Go: Functional Options

A pattern that allows flexible configuration in Go with a functional programming style.

Jose Sitanggang
6 min readOct 30, 2023
Image by Refactoring.Guru

The Functional Options Pattern is a design pattern for creating objects with flexible configurations by using functions as arguments to modify the default behavior.

In my opinion, this pattern can be considered a Builder Pattern with a functional style: instead of chaining methods, we compose functions to configure the object.

This pattern is widely used in Go, which might be the reason it is not explained in most design pattern books. Nevertheless, to provide some context about this pattern, let’s examine the code below that I took from my httpkit package:

package httpkit

// GracefulRunner is a wrapper of http.Server that can be shutdown gracefully.
type GracefulRunner struct {
Runner
signalListener chan os.Signal
waitTimeout time.Duration
shutdownDone chan struct{}
eventListener func(event RunEvent, data string)
}

// NewGracefulRunner wraps a Server with graceful shutdown capability.
func NewGracefulRunner(server Runner) *GracefulRunner {
gs := GracefulRunner{
Runner: server,
shutdownDone: make(chan struct{}),
waitTimeout: 5 * time.Second,
signalListener: make(chan os.Signal, 1),
eventListener…

--

--

No responses yet