name.go 2.5 KB
Newer Older
1 2 3 4 5 6
package options

import (
	"time"
)

7 8 9 10
const (
	DefaultNameValidTime = 24 * time.Hour
)

11 12 13 14 15 16 17 18
type NamePublishSettings struct {
	ValidTime time.Duration
	Key       string
}

type NameResolveSettings struct {
	Recursive bool
	Local     bool
19
	Cache     bool
20 21 22 23 24 25 26
}

type NamePublishOption func(*NamePublishSettings) error
type NameResolveOption func(*NameResolveSettings) error

func NamePublishOptions(opts ...NamePublishOption) (*NamePublishSettings, error) {
	options := &NamePublishSettings{
27
		ValidTime: DefaultNameValidTime,
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
		Key:       "self",
	}

	for _, opt := range opts {
		err := opt(options)
		if err != nil {
			return nil, err
		}
	}

	return options, nil
}

func NameResolveOptions(opts ...NameResolveOption) (*NameResolveSettings, error) {
	options := &NameResolveSettings{
		Recursive: false,
		Local:     false,
45
		Cache:     true,
46 47 48 49 50 51 52 53 54 55 56 57
	}

	for _, opt := range opts {
		err := opt(options)
		if err != nil {
			return nil, err
		}
	}

	return options, nil
}

58
type nameOpts struct{}
59

60 61 62 63 64
var Name nameOpts

// ValidTime is an option for Name.Publish which specifies for how long the
// entry will remain valid. Default value is 24h
func (_ nameOpts) ValidTime(validTime time.Duration) NamePublishOption {
65 66 67 68 69 70
	return func(settings *NamePublishSettings) error {
		settings.ValidTime = validTime
		return nil
	}
}

71 72 73 74 75 76
// Key is an option for Name.Publish which specifies the key to use for
// publishing. Default value is "self" which is the node's own PeerID.
// The key parameter must be either PeerID or keystore key alias.
//
// You can use KeyAPI to list and generate more names and their respective keys.
func (_ nameOpts) Key(key string) NamePublishOption {
77 78 79 80 81 82
	return func(settings *NamePublishSettings) error {
		settings.Key = key
		return nil
	}
}

83 84 85
// Recursive is an option for Name.Resolve which specifies whether to perform a
// recursive lookup. Default value is false
func (_ nameOpts) Recursive(recursive bool) NameResolveOption {
86 87 88 89 90 91
	return func(settings *NameResolveSettings) error {
		settings.Recursive = recursive
		return nil
	}
}

92 93 94
// Local is an option for Name.Resolve which specifies if the lookup should be
// offline. Default value is false
func (_ nameOpts) Local(local bool) NameResolveOption {
95 96 97 98 99 100
	return func(settings *NameResolveSettings) error {
		settings.Local = local
		return nil
	}
}

101 102 103
// Cache is an option for Name.Resolve which specifies if cache should be used.
// Default value is true
func (_ nameOpts) Cache(cache bool) NameResolveOption {
104
	return func(settings *NameResolveSettings) error {
105
		settings.Cache = cache
106 107 108
		return nil
	}
}