See the blog post: https://derekchiang.com/posts/reusable-and-type-safe-options-for-go-apis
package main | |
import "fmt" | |
// WithPrefix | |
type prefixOption struct{} | |
func WithPrefix() interface { | |
GetOption | |
DeleteOption | |
} { | |
return &prefixOption{} | |
} | |
func (o *prefixOption) SetGetOption(opts *getOptions) { | |
opts.Prefix = true | |
} | |
func (o *prefixOption) SetDeleteOption(opts *deleteOptions) { | |
opts.Prefix = true | |
} | |
// WithRev | |
type revOption struct { | |
rev int64 | |
} | |
func WithRev(rev int64) interface { | |
GetOption | |
} { | |
return &revOption{ | |
rev: rev, | |
} | |
} | |
func (o *revOption) SetGetOption(opts *getOptions) { | |
opts.Rev = o.rev | |
} | |
// Get | |
type getOptions struct { | |
Prefix bool | |
Rev int64 | |
} | |
type GetOption interface { | |
SetGetOption(*getOptions) | |
} | |
func Get(key string, ops ...GetOption) { | |
opts := &getOptions{} | |
for _, op := range ops { | |
op.SetGetOption(opts) | |
} | |
fmt.Printf("Get got options: %+v\n", opts) | |
// do things... | |
} | |
// Delete | |
type deleteOptions struct { | |
Prefix bool | |
} | |
type DeleteOption interface { | |
SetDeleteOption(*deleteOptions) | |
} | |
func Delete(key string, ops ...DeleteOption) { | |
opts := &deleteOptions{} | |
for _, op := range ops { | |
op.SetDeleteOption(opts) | |
} | |
fmt.Printf("Delete got options: %+v\n", opts) | |
// do things... | |
} | |
func main() { | |
// Note how we can reuse `WithPrefix` | |
Get("sample_key", WithPrefix(), WithRev(1)) | |
Delete("sample_key", WithPrefix()) | |
// The following code won't compile since `Delete` doesn't accept `WithRev` | |
// Delete("sample_key", WithRev(1)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment