add create options

This commit is contained in:
Asim Aslam 2019-09-24 18:32:35 +01:00
parent c52651c4d0
commit 1b08036a0b
3 changed files with 60 additions and 13 deletions

View File

@ -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]

27
runtime/options.go Normal file
View File

@ -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
}
}

View File

@ -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 {