Documentation ¶
Overview ¶
Package core is a service container that elegantly bootstrap and coordinate twelve-factor apps in Go.
Checkout the README.md for an overview of this package.
Example (Minimal) ¶
package main import ( "context" "fmt" "io/ioutil" "net/http" "time" "github.com/DoNewsCode/core" "github.com/gorilla/mux" ) func main() { // Spin up a real server c := core.Default(core.WithInline("log.level", "none")) c.AddModule(core.HttpFunc(func(router *mux.Router) { router.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) { writer.Write([]byte("hello world")) }) })) ctx, cancel := context.WithCancel(context.Background()) go c.Serve(ctx) // Giver server sometime to be ready. time.Sleep(time.Second) // Let's try if the server works. resp, _ := http.Get("http://localhost:8080/") bytes, _ := ioutil.ReadAll(resp.Body) cancel() fmt.Println(string(bytes)) }
Output: hello world
Index ¶
- func NewServeModule(in serveIn) serveModule
- func ProvideAppName(conf contract.ConfigAccessor) contract.AppName
- func ProvideConfig(configStack []config.ProviderSet, configWatcher contract.ConfigWatcher) contract.ConfigAccessor
- func ProvideEnv(conf contract.ConfigAccessor) contract.Env
- func ProvideEventDispatcher(conf contract.ConfigAccessor) contract.Dispatcher
- func ProvideLogger(conf contract.ConfigAccessor, appName contract.AppName, env contract.Env) log.Logger
- func WithRemote(r *remote.Remote) (CoreOption, CoreOption)
- func WithRemoteYamlFile(key string, cfg clientv3.Config) (CoreOption, CoreOption)
- func WithYamlFile(path string) (CoreOption, CoreOption)
- type AppNameProvider
- type C
- type ConfParser
- type ConfProvider
- type ConfigProvider
- type CoreOption
- func SetAppNameProvider(provider AppNameProvider) CoreOption
- func SetConfigProvider(provider ConfigProvider) CoreOption
- func SetDiProvider(provider DiProvider) CoreOption
- func SetEnvProvider(provider EnvProvider) CoreOption
- func SetEventDispatcherProvider(provider EventDispatcherProvider) CoreOption
- func SetLoggerProvider(provider LoggerProvider) CoreOption
- func WithConfigStack(provider ConfProvider, parser ConfParser) CoreOption
- func WithConfigWatcher(watcher contract.ConfigWatcher) CoreOption
- func WithInline(key string, entry interface{}) CoreOption
- type DiContainer
- type DiProvider
- type EnvProvider
- type EventDispatcherProvider
- type HttpFunc
- type LoggerProvider
- type OnGRPCServerShutdown
- type OnGRPCServerStart
- type OnHTTPServerShutdown
- type OnHTTPServerStart
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func NewServeModule ¶
func NewServeModule(in serveIn) serveModule
func ProvideAppName ¶
func ProvideAppName(conf contract.ConfigAccessor) contract.AppName
ProvideAppName is the default AppNameProvider for package Core.
func ProvideConfig ¶
func ProvideConfig(configStack []config.ProviderSet, configWatcher contract.ConfigWatcher) contract.ConfigAccessor
ProvideConfig is the default ConfigProvider for package Core.
func ProvideEnv ¶
func ProvideEnv(conf contract.ConfigAccessor) contract.Env
ProvideEnv is the default EnvProvider for package Core.
func ProvideEventDispatcher ¶
func ProvideEventDispatcher(conf contract.ConfigAccessor) contract.Dispatcher
ProvideEventDispatcher is the default EventDispatcherProvider for package Core.
func ProvideLogger ¶
func ProvideLogger(conf contract.ConfigAccessor, appName contract.AppName, env contract.Env) log.Logger
ProvideLogger is the default LoggerProvider for package Core.
func WithRemote ¶ added in v0.5.0
func WithRemote(r *remote.Remote) (CoreOption, CoreOption)
WithRemote is a two-in-one coreOption. It uses the remote key on etcd as the source of configuration, and watches the change of that key for hot reloading.
func WithRemoteYamlFile ¶ added in v0.5.0
func WithRemoteYamlFile(key string, cfg clientv3.Config) (CoreOption, CoreOption)
WithRemoteYamlFile is a two-in-one coreOption. It uses the remote key on etcd as the source of configuration, and watches the change of that key for hot reloading.
func WithYamlFile ¶
func WithYamlFile(path string) (CoreOption, CoreOption)
WithYamlFile is a two-in-one coreOption. It uses the configuration file as the source of configuration, and watches the change of that file for hot reloading.
Types ¶
type AppNameProvider ¶
type AppNameProvider func(conf contract.ConfigAccessor) contract.AppName
AppNameProvider provides the contract.AppName to the core.
type C ¶
type C struct { AppName contract.AppName Env contract.Env contract.ConfigAccessor logging.LevelLogger contract.Container contract.Dispatcher // contains filtered or unexported fields }
C stands for the core of the application. It contains service definitions and dependencies. C is mean to be used in the boostrap phase of the application. Do not pass C into services and use it as a service locator.
Example (Stack) ¶
package main import ( "context" "flag" "net/http" "strings" "github.com/DoNewsCode/core" "github.com/gorilla/mux" "github.com/knadh/koanf/parsers/json" "github.com/knadh/koanf/providers/basicflag" "github.com/knadh/koanf/providers/env" "github.com/knadh/koanf/providers/file" ) func main() { fs := flag.NewFlagSet("example", flag.ContinueOnError) fs.String("log.level", "error", "the log level") // Spin up a real server c := core.New( core.WithConfigStack(basicflag.Provider(fs, "."), nil), core.WithConfigStack(env.Provider("APP_", ".", func(s string) string { return strings.ToLower(strings.Replace(s, "APP_", "", 1)) }), nil), core.WithConfigStack(file.Provider("./config/testdata/mock.json"), json.Parser()), ) c.AddModule(core.HttpFunc(func(router *mux.Router) { router.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) { writer.Write([]byte("hello world")) }) })) c.Serve(context.Background()) }
Output:
func Default ¶
func Default(opts ...CoreOption) *C
Default creates a core.C under its default state. Core dependencies are already provided, and the config module and serve module are bundled.
func (*C) AddModule ¶
func (c *C) AddModule(modules ...interface{})
AddModule adds one or more module(s) to the core. If any of the variadic arguments is an error, it would panic. This makes it easy to consume constructors directly, so instead of writing:
component, err := components.New() if err != nil { panic(err) } c.AddModule(component)
You can write:
c.AddModule(component.New())
A Module is a group of functionality. It must provide some runnable stuff: http handlers, grpc handlers, cron jobs, one-time command, etc.
Example ¶
package main import ( "fmt" "github.com/DoNewsCode/core" ) func main() { type Foo struct{} c := core.New() c.AddModule(Foo{}) fmt.Printf("%T\n", c.Modules()...) }
Output: core_test.Foo
func (*C) AddModuleFunc ¶
func (c *C) AddModuleFunc(constructor interface{})
AddModuleFunc add the module after Invoking its' constructor. Clean up functions and errors are handled automatically.
Example ¶
package main import ( "fmt" "github.com/DoNewsCode/core" ) func main() { type Foo struct{} c := core.New() c.AddModuleFunc(func() (Foo, func(), error) { return Foo{}, func() {}, nil }) fmt.Printf("%T\n", c.Modules()...) }
Output: core_test.Foo
func (*C) Invoke ¶
func (c *C) Invoke(function interface{})
Invoke runs the given function after instantiating its dependencies. Any arguments that the function has are treated as its dependencies. The dependencies are instantiated in an unspecified order along with any dependencies that they might have. The function may return an error to indicate failure. The error will be returned to the caller as-is.
It internally calls uber's dig library. Consult dig's documentation for details. (https://pkg.go.dev/go.uber.org/dig)
func (*C) Provide ¶
Provide adds a dependencies provider to the core. Note the dependency provider must be a function in the form of:
func(foo Foo) Bar
where foo is the upstream dependency and Bar is the provided type. The order for providers doesn't matter. They are only executed lazily when the Invoke is called.
This method internally calls uber's dig library. Consult dig's documentation for details. (https://pkg.go.dev/go.uber.org/dig)
The difference is, core.Provide has been made to accommodate the convention from google/wire (https://github.com/google/wire). All "func()" returned by constructor are treated as clean up functions. It also respect the core's unique "di.Module" annotation.
Example ¶
package main import ( "fmt" "github.com/DoNewsCode/core" "github.com/DoNewsCode/core/di" ) func main() { type Foo struct { Value string } type Bar struct { foo Foo } c := core.New() c.Provide(di.Deps{ func() (foo Foo, cleanup func(), err error) { return Foo{ Value: "test", }, func() {}, nil }, func(foo Foo) Bar { return Bar{foo: foo} }, }) c.Invoke(func(bar Bar) { fmt.Println(bar.foo.Value) }) }
Output: test
func (*C) ProvideEssentials ¶
func (c *C) ProvideEssentials()
ProvideEssentials adds the default core dependencies to the core.
type ConfParser ¶
type ConfParser interface { Unmarshal([]byte) (map[string]interface{}, error) Marshal(map[string]interface{}) ([]byte, error) }
ConfParser models a parser for configuration. For example, yaml.Parser.
type ConfProvider ¶
ConfProvider models a configuration provider. For example, file.Provider.
type ConfigProvider ¶
type ConfigProvider func(configStack []config.ProviderSet, configWatcher contract.ConfigWatcher) contract.ConfigAccessor
ConfigProvider provides contract.ConfigAccessor to the core.
type CoreOption ¶
type CoreOption func(*coreValues)
CoreOption is the option to modify core attribute.
func SetAppNameProvider ¶
func SetAppNameProvider(provider AppNameProvider) CoreOption
SetAppNameProvider is a CoreOption to replaces the default AppNameProvider.
func SetConfigProvider ¶
func SetConfigProvider(provider ConfigProvider) CoreOption
SetConfigProvider is a CoreOption to replaces the default ConfigProvider.
func SetDiProvider ¶
func SetDiProvider(provider DiProvider) CoreOption
SetDiProvider is a CoreOption to replaces the default DiContainer.
func SetEnvProvider ¶
func SetEnvProvider(provider EnvProvider) CoreOption
SetEnvProvider is a CoreOption to replaces the default EnvProvider.
func SetEventDispatcherProvider ¶
func SetEventDispatcherProvider(provider EventDispatcherProvider) CoreOption
SetEventDispatcherProvider is a CoreOption to replaces the default EventDispatcherProvider.
func SetLoggerProvider ¶
func SetLoggerProvider(provider LoggerProvider) CoreOption
SetLoggerProvider is a CoreOption to replaces the default LoggerProvider.
func WithConfigStack ¶
func WithConfigStack(provider ConfProvider, parser ConfParser) CoreOption
WithConfigStack is a CoreOption that defines a configuration layer. See package config for details.
func WithConfigWatcher ¶
func WithConfigWatcher(watcher contract.ConfigWatcher) CoreOption
WithConfigWatcher is a CoreOption that adds a config watcher to the core (for hot reloading configs).
func WithInline ¶
func WithInline(key string, entry interface{}) CoreOption
WithInline is a CoreOption that creates a inline config in the configuration stack.
type DiContainer ¶
type DiContainer interface { Provide(constructor interface{}) error Invoke(function interface{}) error }
DiContainer is a container roughly modeled after dig.Container
func ProvideDi ¶
func ProvideDi(conf contract.ConfigAccessor) DiContainer
ProvideDi is the default DiProvider for package Core.
type DiProvider ¶
type DiProvider func(conf contract.ConfigAccessor) DiContainer
DiProvider provides the DiContainer to the core.
type EnvProvider ¶
type EnvProvider func(conf contract.ConfigAccessor) contract.Env
EnvProvider provides the contract.Env to the core.
type EventDispatcherProvider ¶
type EventDispatcherProvider func(conf contract.ConfigAccessor) contract.Dispatcher
EventDispatcherProvider provides contract.Dispatcher to the core.
type HttpFunc ¶
HttpFunc converts a function to a module provides http.
func (HttpFunc) ProvideHTTP ¶ added in v0.2.0
ProvideHTTP implements container.HTTPProvider
type LoggerProvider ¶
type LoggerProvider func(conf contract.ConfigAccessor, appName contract.AppName, env contract.Env) log.Logger
LoggerProvider provides the log.Logger to the core.
type OnGRPCServerShutdown ¶ added in v0.4.0
OnGRPCServerShutdown is an event triggered when the http server is shutting down. traffic. At this point The traffic can no longer reach the server, but the database and other infrastructures are not closed yet. This event is useful to unregister service to service discovery.
type OnGRPCServerStart ¶ added in v0.4.0
OnGRPCServerStart is an event triggered when the grpc server is ready to serve traffic. At this point the module is already wired up. This event is useful to register service to service discovery.
type OnHTTPServerShutdown ¶ added in v0.4.0
OnHTTPServerShutdown is an event triggered when the http server is shutting down. traffic. At this point The traffic can no longer reach the server, but the database and other infrastructures are not closed yet. This event is useful to unregister service to service discovery.
type OnHTTPServerStart ¶ added in v0.4.0
OnHTTPServerStart is an event triggered when the http server is ready to serve traffic. At this point the module is already wired up. This event is useful to register service to service discovery.
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
Package clihttp adds opentracing support to http client.
|
Package clihttp adds opentracing support to http client. |
Package config provides supports to a fully customizable layered configuration stack.
|
Package config provides supports to a fully customizable layered configuration stack. |
Package container includes the Container type, witch contains a collection of modules.
|
Package container includes the Container type, witch contains a collection of modules. |
Package contract defines a set of common interfaces for all packages in this repository.
|
Package contract defines a set of common interfaces for all packages in this repository. |
Package cronopts contains the options for cron.
|
Package cronopts contains the options for cron. |
Package di is a thin wrapper around dig.
|
Package di is a thin wrapper around dig. |
Package dtx contains a variety of patterns in the field of distributed transaction.
|
Package dtx contains a variety of patterns in the field of distributed transaction. |
sagas
Package sagas implements the orchestration based saga pattern.
|
Package sagas implements the orchestration based saga pattern. |
sagas/mysqlstore
Package mysqlstore provides a mysql store implementation for sagas.
|
Package mysqlstore provides a mysql store implementation for sagas. |
Package events provides a simple and effective implementation of event system.
|
Package events provides a simple and effective implementation of event system. |
Package key provides a way to distribute labels to component.
|
Package key provides a way to distribute labels to component. |
Package leader provides a simple leader election implementation.
|
Package leader provides a simple leader election implementation. |
leaderetcd
Package leaderetcd provides a etcd driver for package leader
|
Package leaderetcd provides a etcd driver for package leader |
leaderredis
Package leaderredis provides a redis driver for package leader
|
Package leaderredis provides a redis driver for package leader |
Package logging provides a kitlog compatible logger.
|
Package logging provides a kitlog compatible logger. |
Package observability provides a tracer and a histogram to measure all incoming requests to the system.
|
Package observability provides a tracer and a histogram to measure all incoming requests to the system. |
Package otes provides es client with opentracing.
|
Package otes provides es client with opentracing. |
Package otetcd provides etcd client with opentracing.
|
Package otetcd provides etcd client with opentracing. |
Package otgorm provides gorm with opentracing.
|
Package otgorm provides gorm with opentracing. |
mocks
Package mock_metrics is a generated GoMock package.
|
Package mock_metrics is a generated GoMock package. |
Package otkafka contains the opentracing integrated a kafka transport for package Core.
|
Package otkafka contains the opentracing integrated a kafka transport for package Core. |
mocks
Package mock_metrics is a generated GoMock package.
|
Package mock_metrics is a generated GoMock package. |
Package otmongo provides mongo client with opentracing.
|
Package otmongo provides mongo client with opentracing. |
Package otredis provides redis client with opentracing.
|
Package otredis provides redis client with opentracing. |
mocks
Package mock_metrics is a generated GoMock package.
|
Package mock_metrics is a generated GoMock package. |
Package ots3 provides a s3 uploader with opentracing capabilities.
|
Package ots3 provides a s3 uploader with opentracing capabilities. |
Package queue provides a persistent queue implementation that interplays with the Dispatcher in the contract package.
|
Package queue provides a persistent queue implementation that interplays with the Dispatcher in the contract package. |
Package srvhttp groups helpers for server side http use cases.
|
Package srvhttp groups helpers for server side http use cases. |
Package text provides utilities to generate textual output.
|
Package text provides utilities to generate textual output. |
Package unierr presents an unification error model between gRPC transport and HTTP transport, and between server and client.
|
Package unierr presents an unification error model between gRPC transport and HTTP transport, and between server and client. |