golang code option

1. golang code option

1.1. option definition

type option struct {
    
    
	enabled       bool
	namespace, id string
	puller        Puller
	mode          electionMode
}

type ElectionOption func(opt *option)

func WithElectionEnabled(on bool) ElectionOption {
    
    
	return func(opt *option) {
    
    
		opt.enabled = on
	}
}

func WithID(id string) ElectionOption {
    
    
	return func(opt *option) {
    
    
		opt.id = id
	}
}

func WithNamespace(ns string) ElectionOption {
    
    
	return func(opt *option) {
    
    
		opt.namespace = ns
	}
}

1.2. interface

type Puller interface {
    
    
	Election(namespace, id string, reqBody io.Reader) ([]byte, error)
	ElectionHeartbeat(namespace, id string, reqBody io.Reader) ([]byte, error)
}

1.3. use Start caller

electionsOpts := []election.ElectionOption{
    
    
    election.WithElectionEnabled(config.Cfg.Election.Enable),
    election.WithID(config.Cfg.Hostname),
    election.WithNamespace(config.Cfg.Election.Namespace),
}

//...

election.Start(electionsOpts...)
func Start(opts ...ElectionOption) {
    
    
	log = logger.SLogger("dk-election")

	opt := option{
    
    }
	for idx := range opts {
    
    
		opts[idx](&opt)
	}
    
    //...
}

猜你喜欢

转载自blog.csdn.net/wan212000/article/details/130808308