...

Source file src/google.golang.org/api/option/internaloption/internaloption_external_test.go

Documentation: google.golang.org/api/option/internaloption

     1  // Copyright 2022 Google LLC.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package internaloption_test
     6  
     7  import (
     8  	"context"
     9  	"fmt"
    10  
    11  	"google.golang.org/api/option"
    12  	"google.golang.org/api/option/internaloption"
    13  )
    14  
    15  type config struct {
    16  	i int
    17  }
    18  
    19  type clientSpecificOption interface {
    20  	option.ClientOption
    21  	ApplyOpt(*config)
    22  }
    23  
    24  func WithFavoriteNumber(i int) option.ClientOption {
    25  	return &withFavoriteNumber{i: i}
    26  }
    27  
    28  type withFavoriteNumber struct {
    29  	internaloption.EmbeddableAdapter
    30  	i int
    31  }
    32  
    33  func (w *withFavoriteNumber) ApplyOpt(c *config) {
    34  	c.i = w.i
    35  }
    36  
    37  type Foo struct {
    38  	i int
    39  }
    40  
    41  func NewFoo(ctx context.Context, opts ...option.ClientOption) (*Foo, error) {
    42  	var conf config
    43  	for _, opt := range opts {
    44  		if fooOpt, ok := opt.(clientSpecificOption); ok {
    45  			fooOpt.ApplyOpt(&conf)
    46  		}
    47  	}
    48  	// Pass options to internals for dialing. All client-specific options will
    49  	// be no-ops.
    50  	return &Foo{i: conf.i}, nil
    51  }
    52  
    53  func (f *Foo) Number() int { return f.i }
    54  
    55  func ExampleEmbeddableAdapter() {
    56  	f, err := NewFoo(context.Background(), WithFavoriteNumber(42))
    57  	if err != nil {
    58  		// TODO: handle error
    59  	}
    60  	fmt.Println(f.Number())
    61  	// Output: 42
    62  }
    63  

View as plain text