servicehub

package module
v1.0.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 8, 2025 License: MIT Imports: 23 Imported by: 8

README

servicehub

The servicehub.Hub is Service Manager, which manages the startup, initialization, dependency, and shutdown of services.

Provider provide one or more services, and implement the servicehub.Provider interface to provide services.

The servicehub.Hub manages all providers registered by function servicehub.RegisterProvider .

Example

The configuration file examples.yaml

hello:
    message: "hello world"
    sub:
        name: "recallsong"

The code file main.go

package main

import (
	"os"
	"time"

	"github.com/recallsong/go-utils/logs"
	"github.com/recallsong/servicehub"
)

// define Represents the definition of provider and provides some information
type define struct{}

// Declare what services the provider provides
func (d *define) Service() []string { return []string{"hello"} }

// Declare which services the provider depends on
func (d *define) Dependencies() []string { return []string{} }

// Describe information about this provider
func (d *define) Description() string { return "hello for example" }

// Return an instance representing the configuration
func (d *define) Config() interface{} { return &config{} }

// Return a provider creator
func (d *define) Creator() servicehub.Creator {
	return func() servicehub.Provider {
		return &provider{}
	}
}

type config struct {
	Message   string    `file:"message" flag:"msg" default:"hi" desc:"message to show"`
	SubConfig subConfig `file:"sub"`
}

type subConfig struct {
	Name string `file:"name" flag:"hello_name" default:"recallsong" desc:"name to show"`
}

type provider struct {
	C       *config
	L       logs.Logger
	closeCh chan struct{}
}

func (p *provider) Init(ctx servicehub.Context) error {
	p.L.Info("message: ", p.C.Message)
	p.closeCh = make(chan struct{})
	return nil
}

func (p *provider) Start() error {
	p.L.Info("now hello provider is running...")
	tick := time.Tick(10 * time.Second)
	for {
		select {
		case <-tick:
			p.L.Info("do something...")
		case <-p.closeCh:
			return nil
		}
	}
}

func (p *provider) Close() error {
	p.L.Info("now hello provider is closing...")
	close(p.closeCh)
	return nil
}

func init() {
	servicehub.RegisterProvider("hello", &define{})
}

func main() {
	hub := servicehub.New()
	hub.Run("examples", "", os.Args...)
}

Example details

Output:

➜  examples git:(master) ✗ go run main.go
INFO[2021-03-08 19:04:09.493] message: hello world                          module=hello
INFO[2021-03-08 19:04:09.493] provider hello initialized                   
INFO[2021-03-08 19:04:09.493] signals to quit:[hangup interrupt terminated quit] 
INFO[2021-03-08 19:04:09.493] now hello provider is running...              module=hello
INFO[2021-03-08 19:04:19.496] do something...                               module=hello
INFO[2021-03-08 19:04:29.497] do something...                               module=hello
^C
INFO[2021-03-08 19:04:32.984] now hello provider is closing...              module=hello
INFO[2021-03-08 19:04:32.984] provider hello exit     

Reading Config

Support the following ways to read config, the priority from low to high is:

  • default Tag In Struct
  • System Environment Variable
  • .env File Environment Variable
  • Config File
  • Flag

Supports file formats:

  • yaml、yml
  • json
  • hcl
  • toml
  • ...

TODO List

  • CLI tools to quick start
  • Test Case

License

Licensed under MIT

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Register added in v1.0.2

func Register(name string, spec *Spec)

Register .

func RegisterGlobalProvider added in v1.0.2

func RegisterGlobalProvider(name string, define ProviderDefine)

RegisterGlobalProvider .

func RegisterGlobalSpec added in v1.0.2

func RegisterGlobalSpec(name string, spec *Spec)

RegisterGlobalSpec .

func RegisterProvider

func RegisterProvider(name string, define ProviderDefine)

RegisterProvider .

func Usage

func Usage(names ...string) string

Usage .

func WithListener added in v1.0.0

func WithListener(l Listener) interface{}

WithListener .

func WithLogger

func WithLogger(logger logs.Logger) interface{}

WithLogger .

Types

type ConfigCreator

type ConfigCreator interface {
	Config() interface{}
}

ConfigCreator .

type Context

type Context interface {
	context.Context
	Hub() *Hub
	Config() interface{}
	Logger() logs.Logger
	Service(name string, options ...interface{}) interface{}
	AddTask(task func(context.Context) error, options ...TaskOption)
	Key() string
	Label() string
	Provider() Provider
}

Context .

type Creator

type Creator func() Provider

Creator .

type DefaultListener added in v1.0.2

type DefaultListener struct {
	BeforeInitFunc func(h *Hub, config map[string]interface{}) error
	AfterInitFunc  func(h *Hub) error
	AfterStartFunc func(h *Hub) error
	BeforeExitFunc func(h *Hub, err error) error
}

DefaultListener .

func (*DefaultListener) AfterInitialization added in v1.0.2

func (l *DefaultListener) AfterInitialization(h *Hub) error

AfterInitialization .

func (*DefaultListener) AfterStart added in v1.0.2

func (l *DefaultListener) AfterStart(h *Hub) error

AfterStart .

func (*DefaultListener) BeforeExit added in v1.0.2

func (l *DefaultListener) BeforeExit(h *Hub, err error) error

BeforeExit .

func (*DefaultListener) BeforeInitialization added in v1.0.2

func (l *DefaultListener) BeforeInitialization(h *Hub, config map[string]interface{}) error

BeforeInitialization .

type DependencyContext added in v1.0.2

type DependencyContext interface {
	Type() reflect.Type
	Tags() reflect.StructTag
	Service() string
	Key() string
	Label() string
	Caller() string
	CallerLabel() string
}

DependencyContext .

type DependencyProvider

type DependencyProvider interface {
	Provide(ctx DependencyContext, options ...interface{}) interface{}
}

DependencyProvider .

type Events added in v1.0.2

type Events interface {
	Initialized() <-chan error
	Started() <-chan error
	Exited() <-chan error
}

Events events about Hub

type Hub

type Hub struct {
	// contains filtered or unexported fields
}

Hub .

func New

func New(options ...interface{}) *Hub

New .

func Run added in v1.0.2

func Run(opts *RunOptions) *Hub

Run .

func (*Hub) Close

func (h *Hub) Close() error

Close .

func (*Hub) Events added in v1.0.2

func (h *Hub) Events() Events

Events return Events

func (*Hub) ForeachServices added in v1.0.2

func (h *Hub) ForeachServices(fn func(service string) bool)

ForeachServices .

func (*Hub) Init

func (h *Hub) Init(config map[string]interface{}, flags *pflag.FlagSet, args []string) (err error)

Init .

func (*Hub) IsServiceExist added in v1.0.2

func (h *Hub) IsServiceExist(service string) bool

IsServiceExist .

func (*Hub) Provider added in v1.0.2

func (h *Hub) Provider(name string) interface{}

Provider .

func (*Hub) Run

func (h *Hub) Run(name, cfgfile string, args ...string)

Run .

func (*Hub) RunWithOptions added in v1.0.2

func (h *Hub) RunWithOptions(opts *RunOptions)

RunWithOptions .

func (*Hub) Service added in v1.0.0

func (h *Hub) Service(name string, options ...interface{}) interface{}

Service .

func (*Hub) Start

func (h *Hub) Start(closer ...<-chan os.Signal) (err error)

Start .

func (*Hub) StartWithSignal

func (h *Hub) StartWithSignal() error

StartWithSignal .

type Listener added in v1.0.0

type Listener interface {
	BeforeInitialization(h *Hub, config map[string]interface{}) error
	AfterInitialization(h *Hub) error
	AfterStart(h *Hub) error
	BeforeExit(h *Hub, err error) error
}

Listener .

type Option

type Option func(hub *Hub)

Option .

type Provider

type Provider interface{}

Provider .

type ProviderDefine

type ProviderDefine interface {
	Creator() Creator
}

ProviderDefine .

type ProviderInitializer

type ProviderInitializer interface {
	Init(ctx Context) error
}

ProviderInitializer .

type ProviderRunner

type ProviderRunner interface {
	Start() error
	Close() error
}

ProviderRunner .

type ProviderRunnerWithContext added in v1.0.2

type ProviderRunnerWithContext interface {
	Run(context.Context) error
}

ProviderRunnerWithContext .

type ProviderServices added in v1.0.2

type ProviderServices interface {
	Services() []string
}

ProviderServices .

type ProviderUsage

type ProviderUsage interface {
	Description() string
}

ProviderUsage .

type ProviderUsageSummary added in v1.0.0

type ProviderUsageSummary interface {
	Summary() string
}

ProviderUsageSummary .

type RunOptions added in v1.0.2

type RunOptions struct {
	Name       string
	ConfigFile string
	Content    interface{}
	Format     string
	Args       []string
}

RunOptions .

type ServiceDependencies

type ServiceDependencies interface {
	Dependencies(*Hub) []string
}

ServiceDependencies .

type ServiceTypes added in v1.0.2

type ServiceTypes interface {
	Types() []reflect.Type
}

ServiceTypes .

type Spec added in v1.0.2

type Spec struct {
	Define               interface{}           // optional
	Services             []string              // optional
	Dependencies         []string              // optional
	OptionalDependencies []string              // optional
	DependenciesFunc     func(h *Hub) []string // optional
	Summary              string                // optional
	Description          string                // optional
	ConfigFunc           func() interface{}    // optional
	Types                []reflect.Type        // optional
	Creator              Creator               // required
}

Spec define provider and register with Register function

type TaskOption added in v1.0.2

type TaskOption func(*task)

TaskOption .

func WithTaskName added in v1.0.2

func WithTaskName(name string) TaskOption

WithTaskName .

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL