Functional Options In Go
-
I wrote a thing if you care:
-
So here's a playground example of using functional options and error handling: https://play.golang.org/p/cfw7axv6pjO
The advantage over method chaining is that we can return our errors correctly this way. Using the following as an example, I can return my error the whole way to the function call in
main()
and only need to handle it in a single place.type MethodOption func(*http.Request) (*http.Request, error) func NewRequest(opt ...MethodOption) (*http.Request, error) { r := &http.Request{} var err error for _, opt := range opt { r, err = opt(r) if err != nil { return nil, err } } return r, nil } func SetURL(URL string) MethodOption { return func(r *http.Request) (*http.Request, error) { u, err := url.Parse(URL) if err != nil { return nil, err } r.URL = u return r, nil } } req, err := NewRequest( SetURL("https://google.com"), ) if err!= nil { fmt.Println(err) os.Exit(1) }