前言

上一篇 咱们讲了服务注册的外部设计, 写了一个服务的管理工具

type Server struct {    serviceMap map[string]*service    options    *Options    beforeMiddleware     []MiddlewareFunc    afterMiddleware      []MiddlewareFunc    beforeMiddlewarePath map[string][]MiddlewareFunc    afterMiddlewarePath  map[string][]MiddlewareFunc}

这次咱们看看服务的配置如何写 才最优雅

先来看看Options

type Options struct {    Protocol transport.Protocol    UseHttp  bool    Uri      string    nl       net.Listener    ctx      context.Context    options  map[string]interface{} // 零散配置    Trace    bool    readTimeout     time.Duration    writeTimeout    time.Duration    processChanSize int    MaximumLoad   int64    RSAPublicKey  []byte    RSAPrivateKey []byte    AuthFunc      AuthFunc    Discovery     discovery.Discovery    registryAddr  string    weights       float64}

这里有十分多 能够填写的中央
如果咱们采纳 最原始的形式 这个配置就会十分的简短 不好保护

func NewServer(protocol  transport.Protocol, useHttp bool, uri string, nl net.listener ...)

咱们当初引入一个新的设计形式

type Option func(options *Options)

咱们定义一个 办法, 这个办法的入参 就是 咱们下面看到配置的指针 咱们能够更具下面的参数定义多个相似的办法

func UseTCP(host string) Option {    return func(options *Options) {        options.Uri = host        options.Protocol = transport.TCP    }}func UseUnix(addr string) Option {    return func(options *Options) {        options.Uri = addr        options.Protocol = transport.UNIX    }}func UseKCP(host string) Option {    return func(options *Options) {        options.Uri = host        options.Protocol = transport.KCP    }}

当应用时 咱们只有传入多个Option办法 就能够实现对配置的设置

func (s *Server) Run(options ...Option) error {    for _, fn := range options {        fn(s.options)    }}

是不是就十分 清晰了呢 ...