glider/service/service.go

30 lines
659 B
Go
Raw Normal View History

2020-09-27 19:50:21 +08:00
package service
import (
2022-02-24 18:41:03 +08:00
"errors"
2020-09-27 19:50:21 +08:00
"strings"
)
2022-02-24 18:41:03 +08:00
var creators = make(map[string]Creator)
2020-09-27 19:50:21 +08:00
// Service is a server that can be run.
2022-02-24 18:41:03 +08:00
type Service interface{ Run() }
2020-09-27 19:50:21 +08:00
2022-02-24 18:41:03 +08:00
// Creator is a function to create services.
type Creator func(args ...string) (Service, error)
2020-09-27 19:50:21 +08:00
// Register is used to register a service.
2022-02-24 18:41:03 +08:00
func Register(name string, c Creator) {
creators[strings.ToLower(name)] = c
2020-09-27 19:50:21 +08:00
}
2022-02-24 18:41:03 +08:00
// New calls the registered creator to create services.
func New(s string) (Service, error) {
args := strings.Split(s, ",")
c, ok := creators[strings.ToLower(args[0])]
if ok {
return c(args[1:]...)
2020-09-27 19:50:21 +08:00
}
2022-02-24 18:41:03 +08:00
return nil, errors.New("unknown service name: '" + args[0] + "'")
2020-09-27 19:50:21 +08:00
}