Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

API Design: Optional Parameters #159

Open
luantranminh opened this issue Apr 18, 2023 · 0 comments
Open

API Design: Optional Parameters #159

luantranminh opened this issue Apr 18, 2023 · 0 comments
Labels

Comments

@luantranminh
Copy link
Owner

luantranminh commented Apr 18, 2023

https://samwho.dev/blog/api-design-optional-parameters/

Guiding principles

API design is hard. A good API needs to be:

  1. Easy to change without breaking user code.
  2. Simple for the common use-cases.
  3. Easy to understand without having to read documentation.
  4. Helpful when things go wrong.

Go: adding parameters a better way

type options struct {
  followRedirects bool
  headers map[string]string
}

type Option = func(*options)

var (
  FollowRedirects = func(o *options) {
    o.followRedirects = true
  }

  Header = func(key, value string) func(*options) {
    return func(o *options) {
      o.headers[key] = value
    }
  }
)

func Get(url string, os ...Option) (Response, error) {
  o := options{}
  for _, option := range os {
    option(&o)
  }

  // ...
}

Some examples of using this:

rsp, err := http.Get("http://example.com")

If you want to specify parameters:

rsp, err := http.Get("http://example.com",
  http.FollowRedirects,
  http.Header("Accept-Encoding", "gzip"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant