-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathoption.go
60 lines (51 loc) · 1.18 KB
/
option.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// Copyright (c) Jim Lambert
// SPDX-License-Identifier: MIT
package gldap
import (
"io"
"reflect"
)
// Option defines a common functional options type which can be used in a
// variadic parameter pattern.
type Option func(interface{})
// applyOpts takes a pointer to the options struct as a set of default options
// and applies the slice of opts as overrides.
func applyOpts(opts interface{}, opt ...Option) {
for _, o := range opt {
if o == nil { // ignore any nil Options
continue
}
o(opts)
}
}
type generalOptions struct {
withWriter io.Writer
}
func generalDefaults() generalOptions {
return generalOptions{}
}
func getGeneralOpts(opt ...Option) generalOptions {
opts := generalDefaults()
applyOpts(&opts, opt...)
return opts
}
// WithWriter allows you to specify an optional writer.
func WithWriter(w io.Writer) Option {
return func(o interface{}) {
if o, ok := o.(*generalOptions); ok {
if !isNil(w) {
o.withWriter = w
}
}
}
}
func isNil(i interface{}) bool {
if i == nil {
return true
}
switch reflect.TypeOf(i).Kind() {
case reflect.Ptr, reflect.Map, reflect.Array, reflect.Chan, reflect.Slice:
return reflect.ValueOf(i).IsNil()
}
return false
}