github.com/erda-project/erda-infra@v1.0.9/base/servicehub/options.go (about) 1 // Copyright (c) 2021 Terminus, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package servicehub 16 17 import "github.com/erda-project/erda-infra/base/logs" 18 19 // Option . 20 type Option func(hub *Hub) 21 22 func processOptions(hub *Hub, opt interface{}) { 23 if fn, ok := opt.(Option); ok { 24 fn(hub) 25 } 26 } 27 28 // WithLogger . 29 func WithLogger(logger logs.Logger) interface{} { 30 return Option(func(hub *Hub) { 31 hub.logger = logger 32 }) 33 } 34 35 // Listener . 36 type Listener interface { 37 BeforeInitialization(h *Hub, config map[string]interface{}) error 38 AfterInitialization(h *Hub) error 39 AfterStart(h *Hub) error 40 BeforeExit(h *Hub, err error) error 41 } 42 43 // WithListener . 44 func WithListener(l Listener) interface{} { 45 return Option(func(hub *Hub) { 46 hub.listeners = append(hub.listeners, l) 47 }) 48 } 49 50 // DefaultListener . 51 type DefaultListener struct { 52 BeforeInitFunc func(h *Hub, config map[string]interface{}) error 53 AfterInitFunc func(h *Hub) error 54 AfterStartFunc func(h *Hub) error 55 BeforeExitFunc func(h *Hub, err error) error 56 } 57 58 // BeforeInitialization . 59 func (l *DefaultListener) BeforeInitialization(h *Hub, config map[string]interface{}) error { 60 if l.BeforeInitFunc == nil { 61 return nil 62 } 63 return l.BeforeInitFunc(h, config) 64 } 65 66 // AfterInitialization . 67 func (l *DefaultListener) AfterInitialization(h *Hub) error { 68 if l.AfterInitFunc == nil { 69 return nil 70 } 71 return l.AfterInitFunc(h) 72 } 73 74 // AfterStart . 75 func (l *DefaultListener) AfterStart(h *Hub) error { 76 if l.AfterStartFunc == nil { 77 return nil 78 } 79 return l.AfterStartFunc(h) 80 } 81 82 // BeforeExit . 83 func (l *DefaultListener) BeforeExit(h *Hub, err error) error { 84 if l.BeforeExitFunc == nil { 85 return err 86 } 87 return l.BeforeExitFunc(h, err) 88 }