diff --git a/runtime/default.go b/runtime/default.go index 9d4f6288..af9772d9 100644 --- a/runtime/default.go +++ b/runtime/default.go @@ -2,7 +2,6 @@ package runtime import ( "errors" - "os" "strings" "sync" "time" @@ -50,13 +49,25 @@ func newRuntime() *runtime { } } -func newService(s *Service) *service { - parts := strings.Split(s.Exec, " ") - exec := parts[0] - args := []string{} +func newService(s *Service, c CreateOptions) *service { + var exec string + var args []string - if len(parts) > 1 { - args = parts[1:] + if len(s.Exec) > 0 { + parts := strings.Split(s.Exec, " ") + exec = parts[0] + args = []string{} + + if len(parts) > 1 { + args = parts[1:] + } + } else { + // set command + exec = c.Command[0] + // set args + if len(c.Command) > 1 { + args = c.Command[1:] + } } return &service{ @@ -67,7 +78,7 @@ func newService(s *Service) *service { Name: s.Name, Path: exec, }, - Env: os.Environ(), + Env: c.Env, Args: args, }, } @@ -189,7 +200,7 @@ func (r *runtime) run() { } } -func (r *runtime) Create(s *Service) error { +func (r *runtime) Create(s *Service, opts ...CreateOption) error { r.Lock() defer r.Unlock() @@ -197,8 +208,17 @@ func (r *runtime) Create(s *Service) error { return errors.New("service already registered") } + var options CreateOptions + for _, o := range opts { + o(&options) + } + + if len(s.Exec) == 0 && len(options.Command) == 0 { + return errors.New("missing exec command") + } + // save service - r.services[s.Name] = newService(s) + r.services[s.Name] = newService(s, options) // push into start queue r.start <- r.services[s.Name] diff --git a/runtime/options.go b/runtime/options.go new file mode 100644 index 00000000..99ae40c5 --- /dev/null +++ b/runtime/options.go @@ -0,0 +1,27 @@ +package runtime + +type CreateOption func(o *CreateOptions) + +type CreateOptions struct { + // command to execute including args + Command []string + // Environment to configure + Env []string +} + +// Command specifies the command to execute +func WithCommand(c string, args ...string) CreateOption { + return func(o *CreateOptions) { + // set command + o.Command = []string{c} + // set args + o.Command = append(o.Command, args...) + } +} + +// Env sets the created service env +func WithEnv(env []string) CreateOption { + return func(o *CreateOptions) { + o.Env = env + } +} diff --git a/runtime/runtime.go b/runtime/runtime.go index 9a306b63..63216867 100644 --- a/runtime/runtime.go +++ b/runtime/runtime.go @@ -4,7 +4,7 @@ package runtime // Runtime is a service runtime manager type Runtime interface { // Registers a service - Create(*Service) error + Create(*Service, ...CreateOption) error // Remove a service Delete(*Service) error // starts the runtime @@ -28,8 +28,8 @@ var ( DefaultRuntime = newRuntime() ) -func Create(s *Service) error { - return DefaultRuntime.Create(s) +func Create(s *Service, opts ...CreateOption) error { + return DefaultRuntime.Create(s, opts...) } func Delete(s *Service) error {