github.com/zly-app/zapp@v1.3.3/config/watch.opts.go (about)

     1  package config
     2  
     3  import (
     4  	"go.uber.org/zap"
     5  
     6  	"github.com/zly-app/zapp/core"
     7  	"github.com/zly-app/zapp/logger"
     8  )
     9  
    10  type StructType string
    11  
    12  const (
    13  	Json StructType = "json"
    14  	Yaml StructType = "yaml"
    15  )
    16  
    17  type watchOptions struct {
    18  	Provider   core.IConfigWatchProvider
    19  	StructType StructType
    20  }
    21  
    22  func newWatchOptions(opts []core.ConfigWatchOption) *watchOptions {
    23  	o := &watchOptions{}
    24  	for _, fn := range opts {
    25  		fn(o)
    26  	}
    27  
    28  	if o.StructType == "" {
    29  		o.StructType = Json
    30  	}
    31  	o.check()
    32  	return o
    33  }
    34  
    35  // 检查状态
    36  func (o *watchOptions) check() {
    37  	if o.Provider == nil {
    38  		o.Provider = GetDefaultConfigWatchProvider()
    39  	}
    40  	if o.Provider == nil {
    41  		logger.Log.Fatal("默认配置观察提供者不存在")
    42  	}
    43  }
    44  
    45  func getWatchOptions(a interface{}) *watchOptions {
    46  	opts, ok := a.(*watchOptions)
    47  	if !ok {
    48  		logger.Log.Fatal("无法转换为*watchOptions", zap.Any("a", a))
    49  	}
    50  	return opts
    51  }
    52  
    53  // 选择provider
    54  func WithWatchProvider(name string) core.ConfigWatchOption {
    55  	return func(a interface{}) {
    56  		p := GetConfigWatchProvider(name)
    57  		if p == nil {
    58  			logger.Log.Fatal("配置观察提供者不存在", zap.String("name", name))
    59  		}
    60  
    61  		opts := getWatchOptions(a)
    62  		opts.Provider = p
    63  	}
    64  }
    65  
    66  // 设置观察结构化类型
    67  func WithWatchStructType(t StructType) core.ConfigWatchOption {
    68  	return func(a interface{}) {
    69  		opts := getWatchOptions(a)
    70  		opts.StructType = t
    71  	}
    72  }
    73  
    74  // 设置观察结构化类型为json
    75  func WithWatchStructJson() core.ConfigWatchOption {
    76  	return func(a interface{}) {
    77  		opts := getWatchOptions(a)
    78  		opts.StructType = Json
    79  	}
    80  }
    81  
    82  // 设置观察结构化类型为Yaml
    83  func WithWatchStructYaml() core.ConfigWatchOption {
    84  	return func(a interface{}) {
    85  		opts := getWatchOptions(a)
    86  		opts.StructType = Yaml
    87  	}
    88  }