ML
    • Recent
    • Categories
    • Tags
    • Popular
    • Users
    • Groups
    • Register
    • Login

    Functional Options In Go

    IT Discussion
    golang development
    1
    2
    432
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • stacksofplatesS
      stacksofplates
      last edited by

      I wrote a thing if you care:

      https://hooks.technology/2020/08/functional-options/

      1 Reply Last reply Reply Quote 3
      • stacksofplatesS
        stacksofplates
        last edited by

        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)
        	}
        
        1 Reply Last reply Reply Quote 1
        • 1 / 1
        • First post
          Last post