generated from xmidt-org/.go-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
option.go
62 lines (51 loc) · 1.51 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
61
62
// SPDX-FileCopyrightText: 2023 Comcast Cable Communications Management, LLC
// SPDX-License-Identifier: Apache-2.0
package praetor
import (
"net/http"
"reflect"
"github.com/hashicorp/consul/api"
)
// Option is a functional option for tailoring the consul client
// configuration prior to creating it. Each option can modify the
// *api.Config prior to it being passed to api.NewClient.
type Option func(*api.Config) error
var (
optionType = reflect.TypeOf(Option(nil))
noErrorOptionType = reflect.TypeOf((func(*api.Config))(nil))
)
// OptionFunc represents the types of functions that can be coerced into Options.
type OptionFunc interface {
~func(*api.Config) error | ~func(*api.Config)
}
// AsOption coerces a function into an Option.
func AsOption[OF OptionFunc](of OF) Option {
// trivial conversions
switch oft := any(of).(type) {
case Option:
return oft
case func(*api.Config):
return func(cfg *api.Config) error {
oft(cfg)
return nil
}
}
// now we convert to the underlying type
ofv := reflect.ValueOf(of)
if ofv.CanConvert(optionType) {
return ofv.Convert(optionType).Interface().(Option)
}
// there are only (2) types, so the other type must be it
f := ofv.Convert(noErrorOptionType).Interface().(func(*api.Config))
return func(cfg *api.Config) error {
f(cfg)
return nil
}
}
// WithHTTPClient configures the consul client with a custom HTTP client.
func WithHTTPClient(client *http.Client) Option {
return func(cfg *api.Config) error {
cfg.HttpClient = client
return nil
}
}