In previous posts, we discussed in depth the functional options pattern and listed the benefits of using this pattern over others such as the builder pattern when designing our APIs:
In this post, we are going to see a common use case where we can apply this pattern. Many times, the application we are building needs different information from other services, whether of our company or external to it. For this purpose we use the http protocol for the exchange of information.
The simplest way to do this exchange of information in Go is to use the net/http package. In most cases it can be adjusted to our needs:
Use net/http package
However, we quickly appreciate how the need to reuse the calls to these services and encapsulate certain business logic makes us think of creating a specific package for communication with these services.
Use a separate package
Using this package results simple too:
This solution is totally acceptable, however it is far from exposing a friendly API, easy to read or can be easily extended.
Functional Options
Let’s build our API using the builder pattern:
Use Functional Options
The use of this package will be really improved:
As we can see, we made our API more friendly. Let’s review the benefits of using functional options in this particular case:
- Makes code easier to read and test it.
- Makes more consistent the default values behaviour.
- Avoids breaking API breaks.
- Safe use of the API, avoids bad uses and values.
- Can be easily extended with our options implementation.
- Self documenting API.
- Highly configurable.
You can view the functional options pattern in other user cases: