mirror of
https://github.com/libp2p/go-libp2p.git
synced 2025-09-27 04:26:41 +08:00
constructor: allow nil options
This can make it significantly easier to configure libp2p with optional options.
This commit is contained in:
@@ -242,6 +242,9 @@ type Option func(cfg *Config) error
|
||||
// encountered (if any).
|
||||
func (cfg *Config) Apply(opts ...Option) error {
|
||||
for _, opt := range opts {
|
||||
if opt == nil {
|
||||
continue
|
||||
}
|
||||
if err := opt(cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
|
23
config/config_test.go
Normal file
23
config/config_test.go
Normal file
@@ -0,0 +1,23 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestNilOption(t *testing.T) {
|
||||
var cfg Config
|
||||
optsRun := 0
|
||||
opt := func(c *Config) error {
|
||||
optsRun++
|
||||
return nil
|
||||
}
|
||||
if err := cfg.Apply(nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := cfg.Apply(opt, nil, nil, opt, opt, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if optsRun != 3 {
|
||||
t.Fatalf("expected to have handled 3 options, handled %d", optsRun)
|
||||
}
|
||||
}
|
@@ -19,6 +19,9 @@ type Option = config.Option
|
||||
func ChainOptions(opts ...Option) Option {
|
||||
return func(cfg *Config) error {
|
||||
for _, opt := range opts {
|
||||
if opt == nil {
|
||||
continue
|
||||
}
|
||||
if err := opt(cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
|
@@ -133,3 +133,28 @@ func makeRandomHost(t *testing.T, port int) (host.Host, error) {
|
||||
|
||||
return New(ctx, opts...)
|
||||
}
|
||||
|
||||
func TestChainOptions(t *testing.T) {
|
||||
var cfg Config
|
||||
var optsRun []int
|
||||
optcount := 0
|
||||
newOpt := func() Option {
|
||||
index := optcount
|
||||
optcount++
|
||||
return func(c *Config) error {
|
||||
optsRun = append(optsRun, index)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
if err := cfg.Apply(newOpt(), nil, ChainOptions(newOpt(), newOpt(), ChainOptions(), ChainOptions(nil, newOpt()))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if optcount != len(optsRun) {
|
||||
t.Errorf("expected to have handled %d options, handled %d", optcount, len(optsRun))
|
||||
}
|
||||
for i, x := range optsRun {
|
||||
if i != x {
|
||||
t.Errorf("expected opt %d, got opt %d", i, x)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user