git.zd.zone/hrpc/hrpc@v0.0.12/option/option.go (about) 1 package option 2 3 import ( 4 "errors" 5 6 "git.zd.zone/hrpc/hrpc/database" 7 "git.zd.zone/hrpc/hrpc/filter" 8 "git.zd.zone/hrpc/hrpc/life" 9 "git.zd.zone/hrpc/hrpc/mq" 10 "git.zd.zone/hrpc/hrpc/plugin" 11 ) 12 13 var ( 14 ErrMissingServerName = errors.New("missing server name") 15 ErrInvalidPort = errors.New("invalid port number") 16 ) 17 18 var DefaultOptions = Options{ 19 ListenPort: 8888, 20 ENV: Development, 21 DBs: make(map[string]database.Database), 22 MQs: make(map[string]mq.MQ), 23 HealthCheck: false, 24 MetricsEnabled: false, 25 StackSkip: 1, 26 } 27 28 // Option defines 29 type Options struct { 30 // ID is the service ID 31 ID string 32 ServerName string 33 ListenPort int 34 ENV Environment 35 ConsulCenter Consul 36 DBs map[string]database.Database 37 MQs map[string]mq.MQ 38 HealthCheck bool 39 MetricsEnabled bool 40 41 // StackSkip for logging that it can be used to debug stacks 42 // default: 1 43 StackSkip int 44 Plugins []plugin.Plugin 45 46 // ServerCerts ... 47 ServerCerts *certs 48 49 // ServerFilters defines all the customized filters that the server uses 50 ServerFilters []filter.ServerFilter 51 52 WhenExit []life.Listener 53 WhenRestart []life.Listener 54 } 55 56 func (o Options) Valid() error { 57 if o.ServerName == "" { 58 return ErrMissingServerName 59 } 60 if o.ListenPort == 0 { 61 return ErrInvalidPort 62 } 63 return nil 64 } 65 66 type Option func(*Options) 67 68 func WithStackSkip(i int) Option { 69 return func(o *Options) { 70 o.StackSkip = i 71 } 72 } 73 74 func WithServerName(name string) Option { 75 return func(o *Options) { 76 o.ServerName = name 77 } 78 } 79 80 func WithHealthCheck() Option { 81 return func(o *Options) { 82 o.HealthCheck = true 83 } 84 } 85 86 func WithListenPort(port int) Option { 87 return func(o *Options) { 88 o.ListenPort = port 89 } 90 } 91 92 func WithDatabases(dbs ...database.Database) Option { 93 return func(o *Options) { 94 for _, db := range dbs { 95 o.DBs[db.Name()] = db 96 } 97 } 98 } 99 100 func WithMessageQueues(mqs ...mq.MQ) Option { 101 return func(o *Options) { 102 for _, m := range mqs { 103 o.MQs[m.Name()] = m 104 } 105 } 106 } 107 108 func WithExitListeners(listeners ...life.Listener) Option { 109 return func(o *Options) { 110 o.WhenExit = append(o.WhenExit, listeners...) 111 } 112 } 113 114 func WithRestartListeners(listeners ...life.Listener) Option { 115 return func(o *Options) { 116 o.WhenRestart = append(o.WhenRestart, listeners...) 117 } 118 } 119 120 func WithMetrics() Option { 121 return func(o *Options) { 122 o.MetricsEnabled = true 123 } 124 }