/
internaloption_external_test.go
62 lines (50 loc) · 1.18 KB
/
internaloption_external_test.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
// Copyright 2022 Google LLC.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package internaloption_test
import (
"context"
"fmt"
"google.golang.org/api/option"
"google.golang.org/api/option/internaloption"
)
type config struct {
i int
}
type clientSpecificOption interface {
option.ClientOption
ApplyOpt(*config)
}
func WithFavoriteNumber(i int) option.ClientOption {
return &withFavoriteNumber{i: i}
}
type withFavoriteNumber struct {
internaloption.EmbeddableAdapter
i int
}
func (w *withFavoriteNumber) ApplyOpt(c *config) {
c.i = w.i
}
type Foo struct {
i int
}
func NewFoo(ctx context.Context, opts ...option.ClientOption) (*Foo, error) {
var conf config
for _, opt := range opts {
if fooOpt, ok := opt.(clientSpecificOption); ok {
fooOpt.ApplyOpt(&conf)
}
}
// Pass options to internals for dialing. All client-specific options will
// be no-ops.
return &Foo{i: conf.i}, nil
}
func (f *Foo) Number() int { return f.i }
func ExampleEmbeddableAdapter() {
f, err := NewFoo(context.Background(), WithFavoriteNumber(42))
if err != nil {
// TODO: handle error
}
fmt.Println(f.Number())
// Output: 42
}