commons-go/core/interfaces/Service.go

98 lines
2.0 KiB
Go
Raw Permalink Normal View History

2018-04-12 09:38:04 +00:00
package interfaces
2018-04-17 09:58:31 +00:00
import (
"fmt"
"reflect"
)
2018-04-12 09:38:04 +00:00
type Service interface {
2018-04-17 10:42:50 +00:00
InitService() error
StartService() error
2018-04-17 10:58:42 +00:00
StopService()
DestroyService()
2018-04-17 09:58:31 +00:00
}
type ServiceMethodType int
const (
2018-04-17 10:01:24 +00:00
ServiceMethodInit ServiceMethodType = iota
ServiceMethodStart
ServiceMethodStop
ServiceMethodDestroy
2018-04-17 09:58:31 +00:00
)
var (
serviceMethodTypeID = map[ServiceMethodType]string{
2018-04-17 10:42:50 +00:00
ServiceMethodInit: "InitService",
ServiceMethodStart: "StartService",
ServiceMethodStop: "StopService",
ServiceMethodDestroy: "DestroyService",
2018-04-17 09:58:31 +00:00
}
)
func (t ServiceMethodType) String() string {
return serviceMethodTypeID[t]
}
func ExecServices(services []interface{}, method ServiceMethodType, orderedTypes []reflect.Type, reverse bool) error {
if nil == services || 0 == len(services) {
return nil
}
if nil == orderedTypes || 0 == len(orderedTypes) {
return nil
}
tlen := len(orderedTypes)
var _services []interface{}
if reverse {
for indexI := tlen - 1; indexI >= 0; indexI-- {
t := orderedTypes[indexI]
i := findServicesByType(services, t)
if nil == i {
return fmt.Errorf("service[%s] is not exist", t.Name())
}
_services = append(_services, i)
}
} else {
for indexI := 0; indexI < tlen; indexI++ {
t := orderedTypes[indexI]
i := findServicesByType(services, t)
if nil == i {
return fmt.Errorf("service[%s] is not exist", t.Name())
}
_services = append(_services, i)
}
}
if 0 == len(_services) {
return nil
}
for indexI := 0; indexI < len(_services); indexI++ {
i := _services[indexI]
iv := reflect.ValueOf(i)
m := iv.MethodByName(method.String())
2018-04-17 10:24:06 +00:00
rvs := m.Call([]reflect.Value{})
2018-04-17 10:58:42 +00:00
switch method {
case ServiceMethodInit, ServiceMethodStart:
if nil != rvs && 1 == len(rvs) && nil != rvs[0].Interface() {
return rvs[0].Interface().(error)
}
default:
2018-04-17 09:58:31 +00:00
}
}
return nil
}
func findServicesByType(services []interface{}, t reflect.Type) interface{} {
for _, i := range services {
if reflect.TypeOf(i) == t {
return i
}
}
return nil
2018-04-12 09:38:04 +00:00
}